-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathOpenFgaClientTests.cs
More file actions
3371 lines (3008 loc) · 134 KB
/
Copy pathOpenFgaClientTests.cs
File metadata and controls
3371 lines (3008 loc) · 134 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
using Moq;
using Moq.Protected;
using OpenFga.Sdk.ApiClient;
using OpenFga.Sdk.Client;
using OpenFga.Sdk.Client.Model;
using OpenFga.Sdk.Exceptions;
using OpenFga.Sdk.Exceptions.Parsers;
using OpenFga.Sdk.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace OpenFga.Sdk.Test.Client;
public class OpenFgaClientTests : IDisposable {
private readonly string _storeId;
private readonly string _apiUrl = "https://api.fga.example";
private readonly ClientConfiguration _config;
private static class TestHeaders {
public const string RequestId = "X-Request-ID";
public const string TraceId = "X-Trace-ID";
public const string SessionId = "X-Session-ID";
public const string UserId = "X-User-ID";
public const string CorrelationId = "X-Correlation-ID";
public const string CustomHeader = "X-Custom-Header";
}
public OpenFgaClientTests() {
_storeId = "01H0H015178Y2V4CX10C2KGHF4";
_config = new ClientConfiguration() { StoreId = _storeId, ApiUrl = _apiUrl };
}
private HttpResponseMessage GetCheckResponse(CheckResponse content, bool shouldRetry = false) {
var response = new HttpResponseMessage() {
StatusCode = shouldRetry ? (HttpStatusCode)429 : HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(content),
Headers = { }
};
if (shouldRetry) {
response.Headers.Add(RateLimitParser.RateLimitHeader.LimitRemaining, "0");
response.Headers.Add(RateLimitParser.RateLimitHeader.LimitResetIn, "100");
response.Headers.Add(RateLimitParser.RateLimitHeader.LimitTotalInPeriod, "2");
}
return response;
}
private (OpenFgaClient client, Mock<HttpMessageHandler> handler) CreateTestClientForHeaders<TResponse>(
TResponse response,
Func<HttpRequestMessage, bool>? requestValidator = null,
ClientConfiguration? config = null) {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
requestValidator != null
? ItExpr.Is<HttpRequestMessage>(req => requestValidator(req))
: ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(() => new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(response),
});
var httpClient = new HttpClient(mockHandler.Object);
return (new OpenFgaClient(config ?? _config, httpClient), mockHandler);
}
private void AssertHeaderPresent(Mock<HttpMessageHandler> mockHandler, string headerName, string expectedValue) {
mockHandler.Protected().Verify(
"SendAsync",
Times.AtLeastOnce(),
ItExpr.Is<HttpRequestMessage>(req =>
req.Headers.Contains(headerName) &&
req.Headers.GetValues(headerName).First() == expectedValue),
ItExpr.IsAny<CancellationToken>()
);
}
public void Dispose() {
// Cleanup when everything is done.
}
/// <summary>
/// Test StoreId validation
/// </summary>
[Fact]
public async Task ConfigurationInValidStoreIdTest() {
var config = new ClientConfiguration() {
ApiUrl = _apiUrl,
StoreId = "invalid-format"
};
void ActionInvalidId() => config.EnsureValid();
var exception = Assert.Throws<FgaValidationError>(ActionInvalidId);
Assert.Equal("StoreId is not in a valid ulid format", exception.Message);
}
/// <summary>
/// Test Auth Model ID validation
/// </summary>
[Fact]
public async Task ConfigurationInValidAuthorizationModelIdTest() {
var config = new ClientConfiguration() {
ApiUrl = _apiUrl,
StoreId = _config.StoreId,
AuthorizationModelId = "invalid-format"
};
void ActionInvalidId() => new OpenFgaClient(config);
var exception = Assert.Throws<FgaValidationError>(ActionInvalidId);
Assert.Equal("AuthorizationModelId is not in a valid ulid format", exception.Message);
}
/// <summary>
/// Test Auth Model ID validation
/// </summary>
[Fact]
public async Task ConfigurationInValidAuthModelIdInOptionsTest() {
var config = new ClientConfiguration() {
ApiUrl = _apiUrl,
StoreId = _config.StoreId,
};
var fgaClient = new OpenFgaClient(config);
async Task<ReadAuthorizationModelResponse> ActionMissingStoreId() => await fgaClient.ReadAuthorizationModel(new ClientReadAuthorizationModelOptions() {
AuthorizationModelId = "invalid-format"
});
var exception = await Assert.ThrowsAsync<FgaValidationError>(ActionMissingStoreId);
Assert.Equal("AuthorizationModelId is not in a valid ulid format", exception.Message);
}
/// <summary>
/// Test DefaultHeaders with reserved headers should throw
/// </summary>
[Theory]
[InlineData("Content-Type", "application/xml")]
[InlineData("content-type", "text/plain")]
[InlineData("CONTENT-TYPE", "application/json")]
[InlineData("Authorization", "Bearer fake-token")]
[InlineData("authorization", "Bearer fake-token")]
[InlineData("Content-Length", "1234")]
[InlineData("content-length", "1234")]
[InlineData("Host", "evil.com")]
[InlineData("host", "evil.com")]
[InlineData("Accept", "application/xml")]
[InlineData("accept", "application/xml")]
[InlineData("Accept-Encoding", "gzip")]
[InlineData("accept-encoding", "gzip")]
[InlineData("Transfer-Encoding", "chunked")]
[InlineData("transfer-encoding", "chunked")]
[InlineData("Connection", "close")]
[InlineData("connection", "close")]
[InlineData("Cookie", "sessionid=abc123")]
[InlineData("cookie", "sessionid=abc123")]
[InlineData("Set-Cookie", "sessionid=abc123")]
[InlineData("set-cookie", "sessionid=abc123")]
[InlineData("Date", "Mon, 01 Jan 2024 00:00:00 GMT")]
[InlineData("date", "Mon, 01 Jan 2024 00:00:00 GMT")]
public void EnsureValid_WithReservedDefaultHeader_ShouldThrowArgumentException(string headerName, string headerValue) {
var config = new ClientConfiguration {
ApiUrl = _apiUrl,
StoreId = _storeId
};
config.DefaultHeaders[headerName] = headerValue;
var exception = Assert.Throws<ArgumentException>(() => config.EnsureValid());
Assert.Contains("is a reserved HTTP header", exception.Message);
Assert.Contains("should not be set via custom headers", exception.Message);
Assert.Contains(headerName, exception.Message, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Test DefaultHeaders with valid custom headers should not throw
/// </summary>
[Fact]
public void EnsureValid_WithValidCustomDefaultHeaders_ShouldNotThrow() {
var config = new ClientConfiguration {
ApiUrl = _apiUrl,
StoreId = _storeId
};
config.DefaultHeaders["X-Custom-Header"] = "custom-value";
config.DefaultHeaders["X-Request-ID"] = "req-123";
config.DefaultHeaders["X-Correlation-ID"] = "corr-456";
config.EnsureValid();
}
/// <summary>
/// Test DefaultHeaders with empty header name should throw
/// </summary>
[Fact]
public void EnsureValid_WithEmptyDefaultHeaderName_ShouldThrowArgumentException() {
var config = new ClientConfiguration {
ApiUrl = _apiUrl,
StoreId = _storeId
};
config.DefaultHeaders[""] = "value";
var exception = Assert.Throws<ArgumentException>(() => config.EnsureValid());
Assert.Contains("Header name cannot be null, empty, or whitespace", exception.Message);
}
/// <summary>
/// Test DefaultHeaders with null header value should throw
/// </summary>
[Fact]
public void EnsureValid_WithNullDefaultHeaderValue_ShouldThrowArgumentException() {
var config = new ClientConfiguration {
ApiUrl = _apiUrl,
StoreId = _storeId
};
config.DefaultHeaders["X-Custom"] = null!;
var exception = Assert.Throws<ArgumentException>(() => config.EnsureValid());
Assert.Contains("has a null value", exception.Message);
}
/// <summary>
/// Test DefaultHeaders with header injection should throw
/// </summary>
[Fact]
public void EnsureValid_WithHeaderInjectionInDefaultHeaders_ShouldThrowArgumentException() {
var config = new ClientConfiguration {
ApiUrl = _apiUrl,
StoreId = _storeId
};
config.DefaultHeaders["X-Custom"] = "value\r\nX-Injected: malicious";
var exception = Assert.Throws<ArgumentException>(() => config.EnsureValid());
Assert.Contains("CR/LF", exception.Message);
Assert.Contains("header injection", exception.Message);
}
/// <summary>
/// Test Content-Type in DefaultHeaders should throw with specific error
/// </summary>
[Fact]
public void EnsureValid_ContentTypeInDefaultHeaders_ShouldThrowWithSpecificError() {
var config = new ClientConfiguration {
ApiUrl = _apiUrl,
StoreId = _storeId
};
config.DefaultHeaders["Content-Type"] = "application/xml";
var exception = Assert.Throws<ArgumentException>(() => config.EnsureValid());
Assert.Contains("Content-Type", exception.Message);
Assert.Contains("reserved", exception.Message);
Assert.Contains("DefaultHeaders", exception.ParamName);
}
/// <summary>
/// Test Content-Type in DefaultHeaders is case-insensitive
/// </summary>
[Fact]
public void EnsureValid_ContentTypeInDefaultHeaders_CaseInsensitive_ShouldThrow() {
var casings = new[] { "content-type", "CONTENT-TYPE", "Content-type", "CoNtEnT-tYpE" };
foreach (var casing in casings) {
var config = new ClientConfiguration {
ApiUrl = _apiUrl,
StoreId = _storeId
};
config.DefaultHeaders[casing] = "application/xml";
var exception = Assert.Throws<ArgumentException>(() => config.EnsureValid());
Assert.Contains("reserved", exception.Message);
}
}
/// <summary>
/// Test Authorization in DefaultHeaders should throw with specific error
/// </summary>
[Fact]
public void EnsureValid_AuthorizationInDefaultHeaders_ShouldThrowWithSpecificError() {
var config = new ClientConfiguration {
ApiUrl = _apiUrl,
StoreId = _storeId
};
config.DefaultHeaders["Authorization"] = "Bearer custom-token";
var exception = Assert.Throws<ArgumentException>(() => config.EnsureValid());
Assert.Contains("Authorization", exception.Message);
Assert.Contains("reserved", exception.Message);
Assert.Contains("authentication failures", exception.Message);
}
/// <summary>
/// Test that updating StoreId after initialization works
/// </summary>
[Fact]
public void UpdateStoreIdTest() {
var config = new ClientConfiguration() { ApiUrl = _apiUrl };
var fgaClient = new OpenFgaClient(config);
Assert.Null(fgaClient.StoreId);
var storeId = "some-id";
fgaClient.StoreId = storeId;
Assert.Equal(storeId, fgaClient.StoreId);
}
/// <summary>
/// Test that updating AuthorizationModelId after initialization works
/// </summary>
[Fact]
public void UpdateAuthorizationModelIdTest() {
var config = new ClientConfiguration() { ApiUrl = _apiUrl };
var fgaClient = new OpenFgaClient(config);
Assert.Null(fgaClient.AuthorizationModelId);
var modelId = "some-id";
fgaClient.AuthorizationModelId = modelId;
Assert.Equal(modelId, fgaClient.AuthorizationModelId);
}
/**********
* Stores *
**********/
/// <summary>
/// Test ListStores
/// </summary>
[Fact]
public async Task ListStoresTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var expectedResponse = new ListStoresResponse() {
Stores = new List<Store>() {
new() {Id = "45678", Name = "TestStore", CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now}
}
};
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores?name=TestStore&") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(expectedResponse),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var response = await fgaClient.ListStores(
new ClientListStoresRequest() {
Name = "TestStore"
},
new ClientListStoresOptions() { }
);
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores?name=TestStore&") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<ListStoresResponse>(response);
Assert.Single(response.Stores);
Assert.Equal(response, expectedResponse);
}
/// <summary>
/// Test ListStores with Null DateTime
/// </summary>
[Fact]
public async Task ListStoresTestNullDeletedAt() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var content =
"{ \"stores\": [{\"id\": \"xyz123\", \"name\": \"abcdefg\", \"created_at\": \"2022-10-07T14:00:40.205Z\", \"updated_at\": \"2022-10-07T14:00:40.205Z\", \"deleted_at\": null}], \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"}";
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri($"{_config.BasePath}/stores") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = new StringContent(content, Encoding.UTF8, "application/json")
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var response = await fgaClient.ListStores(new ClientListStoresRequest());
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<ListStoresResponse>(response);
Assert.Single(response.Stores);
Assert.Equal("xyz123", response.Stores[0].Id);
Assert.Equal("abcdefg", response.Stores[0].Name);
Assert.Null(response.Stores[0].DeletedAt);
}
/// <summary>
/// Test ListStores for empty array
/// </summary>
[Fact]
public async Task ListStoresEmptyTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var expectedResponse = new ListStoresResponse() { Stores = new List<Store>() { } };
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri($"{_config.BasePath}/stores") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(expectedResponse),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var response = await fgaClient.ListStores(new ClientListStoresRequest());
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<ListStoresResponse>(response);
Assert.Empty(response.Stores);
Assert.Equal(response, expectedResponse);
}
/// <summary>
/// Test CreateStore
/// </summary>
[Fact]
public async Task CreateStoreTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var expectedResponse = new CreateStoreResponse() { Id = "45678", Name = "TestStore", CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now };
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri($"{_config.BasePath}/stores") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(expectedResponse),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var response = await fgaClient.CreateStore(new ClientCreateStoreRequest() { Name = "FGA Test Store" });
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<CreateStoreResponse>(response);
Assert.Equal(response, expectedResponse);
}
/// <summary>
/// Test GetStore
/// </summary>
[Fact]
public async Task GetStoreTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var expectedResponse = new GetStoreResponse() { Id = "45678", Name = "TestStore", CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now };
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri($"{_config.BasePath}/stores/{_config.StoreId}") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(expectedResponse),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var response = await fgaClient.GetStore();
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{fgaClient.StoreId}") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<GetStoreResponse>(response);
Assert.Equal(response, expectedResponse);
}
/// <summary>
/// Test DeleteStore
/// </summary>
[Fact]
public async Task DeleteStoreTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri($"{_config.BasePath}/stores/{_config.StoreId}") &&
req.Method == HttpMethod.Delete),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.NoContent
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
await fgaClient.DeleteStore();
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{fgaClient.StoreId}") &&
req.Method == HttpMethod.Delete),
ItExpr.IsAny<CancellationToken>()
);
}
/************************
* Authorization Models *
************************/
/// <summary>
/// Test WriteAuthorizationModel
/// </summary>
[Fact]
public async Task WriteAuthorizationModelTest() {
const string authorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1";
var body = new ClientWriteAuthorizationModelRequest {
SchemaVersion = "1.1",
TypeDefinitions = new List<TypeDefinition> {
new() {
Type = "user", Relations = new Dictionary<string, Userset>()
},
new() {
Type = "document",
Relations = new Dictionary<string, Userset> {
{
"writer", new Userset {
This = new object()
}
}, {
"viewer", new Userset {
Union = new Usersets {
Child = new List<Userset> {
new() {
This = new object()
},
new() {
ComputedUserset = new ObjectRelation {
Relation = "writer"
}
}
}
}
}
}
},
Metadata = new Metadata {
Relations = new Dictionary<string, RelationMetadata> {
{
"writer", new RelationMetadata {
DirectlyRelatedUserTypes = new List<RelationReference> {
new() {
Type = "user"
}
}
}
}, {
"viewer", new RelationMetadata {
DirectlyRelatedUserTypes = new List<RelationReference> {
new() {
Type = "user"
}
}
}
}
}
}
}
}
};
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{_config.StoreId}/authorization-models") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(
new WriteAuthorizationModelResponse() { AuthorizationModelId = authorizationModelId }),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var response = await fgaClient.WriteAuthorizationModel(body);
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{_config.StoreId}/authorization-models") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<WriteAuthorizationModelResponse>(response);
}
/// <summary>
/// Test ReadAuthorizationModel
/// </summary>
[Fact]
public async Task ReadAuthorizationModelTest() {
const string authorizationModelId = "01FMJA27YCE3QAT8RDS9VZFN0T";
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri(
$"{_config.BasePath}/stores/{_config.StoreId}/authorization-models/{authorizationModelId}") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(new ReadAuthorizationModelResponse() {
AuthorizationModel = new AuthorizationModel(id: authorizationModelId,
typeDefinitions: new List<TypeDefinition>(), schemaVersion: "1.1")
}),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var response = await fgaClient.ReadAuthorizationModel(new ClientReadAuthorizationModelOptions {
AuthorizationModelId = authorizationModelId,
});
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri($"{_config.BasePath}/stores/{_config.StoreId}/authorization-models/{authorizationModelId}") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<ReadAuthorizationModelResponse>(response);
Assert.Equal(authorizationModelId, response.AuthorizationModel.Id);
}
/// <summary>
/// Test ReadAuthorizationModel
/// </summary>
[Fact]
public async Task ReadAuthorizationModelModelIdInConfigTest() {
const string authorizationModelId = "01FMJA27YCE3QAT8RDS9VZFN0T";
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri(
$"{_config.BasePath}/stores/{_config.StoreId}/authorization-models/{authorizationModelId}") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(new ReadAuthorizationModelResponse() {
AuthorizationModel = new AuthorizationModel(id: authorizationModelId,
typeDefinitions: new List<TypeDefinition>(), schemaVersion: "1.1")
}),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(new ClientConfiguration(_config) {
StoreId = _storeId,
AuthorizationModelId = authorizationModelId,
}, httpClient);
var response = await fgaClient.ReadAuthorizationModel();
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri($"{_config.BasePath}/stores/{_config.StoreId}/authorization-models/{authorizationModelId}") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<ReadAuthorizationModelResponse>(response);
Assert.Equal(authorizationModelId, response.AuthorizationModel.Id);
}
/// <summary>
/// Test ReadAuthorizationModel
/// </summary>
[Fact]
public async Task ReadLatestAuthorizationModelTest() {
const string authorizationModelId = "01FMJA27YCE3QAT8RDS9VZFN0T";
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri(
$"{_config.BasePath}/stores/{_config.StoreId}/authorization-models?page_size=1&") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(new ReadAuthorizationModelsResponse() {
AuthorizationModels = new List<AuthorizationModel>() {new (id: authorizationModelId,
typeDefinitions: new List<TypeDefinition>(), schemaVersion: "1.1")}
}),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var response = await fgaClient.ReadLatestAuthorizationModel();
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri ==
new Uri($"{_config.BasePath}/stores/{_config.StoreId}/authorization-models?page_size=1&") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<ReadAuthorizationModelResponse>(response);
Assert.Equal(authorizationModelId, response.AuthorizationModel.Id);
}
/***********************
* Relationship Tuples *
***********************/
/// <summary>
/// Test ReadChanges
/// </summary>
[Fact]
public async Task ReadChangesTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var expectedResponse = new ReadChangesResponse() {
Changes = new List<TupleChange>() {
new(new TupleKey {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a"
},
TupleOperation.TUPLEOPERATIONWRITE, DateTime.Now),
},
ContinuationToken =
"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="
};
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri.ToString()
.StartsWith($"{_config.BasePath}/stores/{_config.StoreId}/changes") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(expectedResponse),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var type = "repo";
var pageSize = 25;
var startTime = DateTime.Parse("2022-01-01T00:00:00Z");
var continuationToken =
"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==";
var response = await fgaClient.ReadChanges(new ClientReadChangesRequest { Type = type, StartTime = startTime }, new ClientReadChangesOptions {
PageSize = pageSize,
ContinuationToken = continuationToken,
});
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri.ToString()
.StartsWith($"{_config.BasePath}/stores/{_config.StoreId}/changes") &&
req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>()
);
Assert.IsType<ReadChangesResponse>(response);
Assert.Single(response.Changes);
Assert.Equal(response, expectedResponse);
}
/// <summary>
/// Test Read
/// </summary>
[Fact]
public async Task ReadTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
string capturedContent = "";
var expectedResponse = new ReadResponse() {
Tuples = new List<Model.Tuple>() {
new(new TupleKey {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a"
},
DateTime.Now)
}
};
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{_config.StoreId}/read") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
)
.Callback<HttpRequestMessage, CancellationToken>((req, token) => {
capturedContent = req.Content.ReadAsStringAsync().Result;
})
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(expectedResponse),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var body = new ClientReadRequest() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
};
var options = new ClientReadOptions { };
var response = await fgaClient.Read(body, options);
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{_config.StoreId}/read") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
);
Assert.Contains("tuple", capturedContent);
Assert.IsType<ReadResponse>(response);
Assert.Single(response.Tuples);
Assert.Equal(response, expectedResponse);
}
/// <summary>
/// Test Read with Empty Body
/// </summary>
[Fact]
public async Task ReadEmptyTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
string capturedContent = "";
var expectedResponse = new ReadResponse() {
Tuples = new List<Model.Tuple>() {
new(new TupleKey {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a"
},
DateTime.Now)
}
};
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{_config.StoreId}/read") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
)
.Callback<HttpRequestMessage, CancellationToken>((req, token) => {
capturedContent = req.Content.ReadAsStringAsync().Result;
})
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(expectedResponse),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);
var body = new ClientReadRequest() { };
var options = new ClientReadOptions { };
var response = await fgaClient.Read(body, options);
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{_config.StoreId}/read") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
);
Assert.DoesNotContain("tuple", capturedContent);
Assert.IsType<ReadResponse>(response);
Assert.Single(response.Tuples);
Assert.Equal(response, expectedResponse);
}
/// <summary>
/// Test Write (Write Relationship Tuples)
/// </summary>
[Fact]
public async Task WriteWriteTest() {
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri == new Uri($"{_config.BasePath}/stores/{_config.StoreId}/write") &&
req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() {
StatusCode = HttpStatusCode.OK,
Content = Utils.CreateJsonStringContent(new Object()),
});
var httpClient = new HttpClient(mockHandler.Object);
var fgaClient = new OpenFgaClient(_config, httpClient);