Keycloak

Форк
0
1308 строк · 36.3 Кб
1
// tslint:disable:no-unused-expression
2
import { faker } from "@faker-js/faker";
3
import * as chai from "chai";
4
import { KeycloakAdminClient } from "../src/client.js";
5
import type ClientRepresentation from "../src/defs/clientRepresentation.js";
6
import type ClientScopeRepresentation from "../src/defs/clientScopeRepresentation.js";
7
import type PolicyRepresentation from "../src/defs/policyRepresentation.js";
8
import { Logic } from "../src/defs/policyRepresentation.js";
9
import type ProtocolMapperRepresentation from "../src/defs/protocolMapperRepresentation.js";
10
import type ResourceRepresentation from "../src/defs/resourceRepresentation.js";
11
import type ScopeRepresentation from "../src/defs/scopeRepresentation.js";
12
import type UserRepresentation from "../src/defs/userRepresentation.js";
13
import { credentials } from "./constants.js";
14

15
const expect = chai.expect;
16

17
describe("Clients", () => {
18
  let kcAdminClient: KeycloakAdminClient;
19
  let currentClient: ClientRepresentation;
20
  let currentClientScope: ClientScopeRepresentation;
21
  let currentRoleName: string;
22

23
  before(async () => {
24
    kcAdminClient = new KeycloakAdminClient();
25
    await kcAdminClient.auth(credentials);
26

27
    // create client and also test it
28
    // NOTICE: to be clear, clientId stands for the property `clientId` of client
29
    // clientUniqueId stands for property `id` of client
30
    const clientId = faker.internet.userName();
31
    const createdClient = await kcAdminClient.clients.create({
32
      clientId,
33
    });
34
    expect(createdClient.id).to.be.ok;
35

36
    const client = await kcAdminClient.clients.findOne({
37
      id: createdClient.id,
38
    });
39
    expect(client).to.be.ok;
40
    currentClient = client!;
41
  });
42

43
  after(async () => {
44
    // delete the current one
45
    await kcAdminClient.clients.del({
46
      id: currentClient.id!,
47
    });
48
  });
49

50
  it("list clients", async () => {
51
    const clients = await kcAdminClient.clients.find();
52
    expect(clients).to.be.ok;
53
  });
54

55
  it("get single client", async () => {
56
    const clientUniqueId = currentClient.id!;
57
    const client = await kcAdminClient.clients.findOne({
58
      id: clientUniqueId,
59
    });
60
    // not sure why entity from list api will not have property: authorizationServicesEnabled
61
    expect(client).to.deep.include(currentClient);
62
  });
63

64
  it("update single client", async () => {
65
    const { clientId, id: clientUniqueId } = currentClient;
66
    await kcAdminClient.clients.update(
67
      { id: clientUniqueId! },
68
      {
69
        // clientId is required in client update. no idea why...
70
        clientId,
71
        description: "test",
72
      },
73
    );
74

75
    const client = await kcAdminClient.clients.findOne({
76
      id: clientUniqueId!,
77
    });
78
    expect(client).to.include({
79
      description: "test",
80
    });
81
  });
82

83
  it("delete single client", async () => {
84
    // create another one for delete test
85
    const clientId = faker.internet.userName();
86
    const { id } = await kcAdminClient.clients.create({
87
      clientId,
88
    });
89

90
    // delete it
91
    await kcAdminClient.clients.del({
92
      id,
93
    });
94

95
    const delClient = await kcAdminClient.clients.findOne({
96
      id,
97
    });
98
    expect(delClient).to.be.null;
99
  });
100

101
  /**
102
   * client roles
103
   */
104
  describe("client roles", () => {
105
    before(async () => {
106
      const roleName = faker.internet.userName();
107
      // create a client role
108
      const { roleName: createdRoleName } =
109
        await kcAdminClient.clients.createRole({
110
          id: currentClient.id,
111
          name: roleName,
112
        });
113

114
      expect(createdRoleName).to.be.equal(roleName);
115

116
      // assign currentClientRole
117
      currentRoleName = roleName;
118
    });
119

120
    after(async () => {
121
      // delete client role
122
      await kcAdminClient.clients.delRole({
123
        id: currentClient.id!,
124
        roleName: currentRoleName,
125
      });
126
    });
127

128
    it("list the client roles", async () => {
129
      const roles = await kcAdminClient.clients.listRoles({
130
        id: currentClient.id!,
131
      });
132

133
      expect(roles[0]).to.include({
134
        name: currentRoleName,
135
      });
136
    });
137

138
    it("find the client role", async () => {
139
      const role = await kcAdminClient.clients.findRole({
140
        id: currentClient.id!,
141
        roleName: currentRoleName,
142
      });
143

144
      expect(role).to.include({
145
        name: currentRoleName,
146
        clientRole: true,
147
        containerId: currentClient.id,
148
      });
149
    });
150

151
    it("update the client role", async () => {
152
      // NOTICE: roleName MUST be in the payload, no idea why...
153
      const delta = {
154
        name: currentRoleName,
155
        description: "test",
156
      };
157
      await kcAdminClient.clients.updateRole(
158
        {
159
          id: currentClient.id!,
160
          roleName: currentRoleName,
161
        },
162
        delta,
163
      );
164

165
      // check the change
166
      const role = await kcAdminClient.clients.findRole({
167
        id: currentClient.id!,
168
        roleName: currentRoleName,
169
      });
170

171
      expect(role).to.include(delta);
172
    });
173

174
    it("delete a client role", async () => {
175
      const roleName = faker.internet.userName();
176
      // create a client role
177
      await kcAdminClient.clients.createRole({
178
        id: currentClient.id,
179
        name: roleName,
180
      });
181

182
      // delete
183
      await kcAdminClient.clients.delRole({
184
        id: currentClient.id!,
185
        roleName,
186
      });
187

188
      // check it's null
189
      const role = await kcAdminClient.clients.findRole({
190
        id: currentClient.id!,
191
        roleName,
192
      });
193

194
      expect(role).to.be.null;
195
    });
196
  });
197

198
  describe("client secret", () => {
199
    before(async () => {
200
      const { clientId, id: clientUniqueId } = currentClient;
201
      // update with serviceAccountsEnabled: true
202
      await kcAdminClient.clients.update(
203
        {
204
          id: clientUniqueId!,
205
        },
206
        {
207
          clientId,
208
          serviceAccountsEnabled: true,
209
        },
210
      );
211
    });
212

213
    it("get client secret", async () => {
214
      const credential = await kcAdminClient.clients.getClientSecret({
215
        id: currentClient.id!,
216
      });
217

218
      expect(credential).to.have.all.keys("type", "value");
219
    });
220

221
    it("generate new client secret", async () => {
222
      const newCredential = await kcAdminClient.clients.generateNewClientSecret(
223
        {
224
          id: currentClient.id!,
225
        },
226
      );
227

228
      const credential = await kcAdminClient.clients.getClientSecret({
229
        id: currentClient.id!,
230
      });
231

232
      expect(newCredential).to.be.eql(credential);
233
    });
234

235
    it("generate new registration access token", async () => {
236
      const newRegistrationAccessToken =
237
        await kcAdminClient.clients.generateRegistrationAccessToken({
238
          id: currentClient.id!,
239
        });
240

241
      expect(newRegistrationAccessToken).to.be.ok;
242
    });
243

244
    it("invalidate rotation token", async () => {
245
      await kcAdminClient.clients.invalidateSecret({
246
        id: currentClient.id!,
247
      });
248
    });
249

250
    it("get installation providers", async () => {
251
      const installationProvider =
252
        await kcAdminClient.clients.getInstallationProviders({
253
          id: currentClient.id!,
254
          providerId: "keycloak-oidc-jboss-subsystem",
255
        });
256
      expect(installationProvider).to.be.ok;
257
      expect(typeof installationProvider).to.be.equal("string");
258
    });
259

260
    it("get service account user", async () => {
261
      const serviceAccountUser =
262
        await kcAdminClient.clients.getServiceAccountUser({
263
          id: currentClient.id!,
264
        });
265

266
      expect(serviceAccountUser).to.be.ok;
267
    });
268
  });
269

270
  describe("default client scopes", () => {
271
    let dummyClientScope: ClientScopeRepresentation;
272

273
    beforeEach(async () => {
274
      dummyClientScope = {
275
        name: "does-anyone-read-this",
276
        description: "Oh - seems like you are reading  Hey there!",
277
        protocol: "openid-connect",
278
      };
279

280
      // setup dummy client scope
281
      await kcAdminClient.clientScopes.create(dummyClientScope);
282
      currentClientScope = (await kcAdminClient.clientScopes.findOneByName({
283
        name: dummyClientScope.name!,
284
      }))!;
285
    });
286

287
    afterEach(async () => {
288
      // cleanup default scopes
289
      try {
290
        const { id } = currentClient;
291
        const { id: clientScopeId } = currentClientScope;
292
        await kcAdminClient.clients.delDefaultClientScope({
293
          clientScopeId: clientScopeId!,
294
          id: id!,
295
        });
296
      } catch (e) {
297
        // ignore
298
      }
299

300
      // cleanup client scopes
301
      try {
302
        await kcAdminClient.clientScopes.delByName({
303
          name: dummyClientScope.name!,
304
        });
305
      } catch (e) {
306
        // ignore
307
      }
308
    });
309

310
    it("list default client scopes", async () => {
311
      const defaultClientScopes =
312
        await kcAdminClient.clients.listDefaultClientScopes({
313
          id: currentClient.id!,
314
        });
315

316
      expect(defaultClientScopes).to.be.ok;
317
    });
318

319
    it("add default client scope", async () => {
320
      const { id } = currentClient;
321
      const { id: clientScopeId } = currentClientScope;
322

323
      await kcAdminClient.clients.addDefaultClientScope({
324
        id: id!,
325
        clientScopeId: clientScopeId!,
326
      });
327

328
      const defaultScopes = await kcAdminClient.clients.listDefaultClientScopes(
329
        { id: id! },
330
      );
331

332
      expect(defaultScopes).to.be.ok;
333

334
      const clientScope = defaultScopes.find(
335
        (scope) => scope.id === clientScopeId,
336
      );
337
      expect(clientScope).to.be.ok;
338
    });
339

340
    it("delete default client scope", async () => {
341
      const { id } = currentClient;
342
      const { id: clientScopeId } = currentClientScope;
343

344
      await kcAdminClient.clients.addDefaultClientScope({
345
        id: id!,
346
        clientScopeId: clientScopeId!,
347
      });
348

349
      await kcAdminClient.clients.delDefaultClientScope({
350
        id: id!,
351
        clientScopeId: clientScopeId!,
352
      });
353
      const defaultScopes = await kcAdminClient.clients.listDefaultClientScopes(
354
        { id: id! },
355
      );
356

357
      const clientScope = defaultScopes.find(
358
        (scope) => scope.id === clientScopeId,
359
      );
360
      expect(clientScope).not.to.be.ok;
361
    });
362
  });
363

364
  describe("optional client scopes", () => {
365
    let dummyClientScope: ClientScopeRepresentation;
366

367
    beforeEach(async () => {
368
      dummyClientScope = {
369
        name: "i-hope-your-well",
370
        description: "Everyone has that one friend.",
371
        protocol: "openid-connect",
372
      };
373

374
      // setup dummy client scope
375
      await kcAdminClient.clientScopes.create(dummyClientScope);
376
      currentClientScope = (await kcAdminClient.clientScopes.findOneByName({
377
        name: dummyClientScope.name!,
378
      }))!;
379
    });
380

381
    afterEach(async () => {
382
      // cleanup optional scopes
383
      try {
384
        const { id } = currentClient;
385
        const { id: clientScopeId } = currentClientScope;
386
        await kcAdminClient.clients.delOptionalClientScope({
387
          clientScopeId: clientScopeId!,
388
          id: id!,
389
        });
390
      } catch (e) {
391
        // ignore
392
      }
393

394
      // cleanup client scopes
395
      try {
396
        await kcAdminClient.clientScopes.delByName({
397
          name: dummyClientScope.name!,
398
        });
399
      } catch (e) {
400
        // ignore
401
      }
402
    });
403

404
    it("list optional client scopes", async () => {
405
      const optionalClientScopes =
406
        await kcAdminClient.clients.listOptionalClientScopes({
407
          id: currentClient.id!,
408
        });
409

410
      expect(optionalClientScopes).to.be.ok;
411
    });
412

413
    it("add optional client scope", async () => {
414
      const { id } = currentClient;
415
      const { id: clientScopeId } = currentClientScope;
416

417
      await kcAdminClient.clients.addOptionalClientScope({
418
        id: id!,
419
        clientScopeId: clientScopeId!,
420
      });
421

422
      const optionalScopes =
423
        await kcAdminClient.clients.listOptionalClientScopes({ id: id! });
424

425
      expect(optionalScopes).to.be.ok;
426

427
      const clientScope = optionalScopes.find(
428
        (scope) => scope.id === clientScopeId,
429
      );
430
      expect(clientScope).to.be.ok;
431
    });
432

433
    it("delete optional client scope", async () => {
434
      const { id } = currentClient;
435
      const { id: clientScopeId } = currentClientScope;
436

437
      await kcAdminClient.clients.addOptionalClientScope({
438
        id: id!,
439
        clientScopeId: clientScopeId!,
440
      });
441

442
      await kcAdminClient.clients.delOptionalClientScope({
443
        id: id!,
444
        clientScopeId: clientScopeId!,
445
      });
446
      const optionalScopes =
447
        await kcAdminClient.clients.listOptionalClientScopes({ id: id! });
448

449
      const clientScope = optionalScopes.find(
450
        (scope) => scope.id === clientScopeId,
451
      );
452
      expect(clientScope).not.to.be.ok;
453
    });
454
  });
455

456
  describe("protocol mappers", () => {
457
    let dummyMapper: ProtocolMapperRepresentation;
458

459
    beforeEach(() => {
460
      dummyMapper = {
461
        name: "become-a-farmer",
462
        protocol: "openid-connect",
463
        protocolMapper: "oidc-role-name-mapper",
464
        config: {
465
          role: "admin",
466
          "new.role.name": "farmer",
467
        },
468
      };
469
    });
470

471
    afterEach(async () => {
472
      try {
473
        const { id: clientUniqueId } = currentClient;
474
        const { id: mapperId } =
475
          (await kcAdminClient.clients.findProtocolMapperByName({
476
            id: clientUniqueId!,
477
            name: dummyMapper.name!,
478
          }))!;
479
        await kcAdminClient.clients.delProtocolMapper({
480
          id: clientUniqueId!,
481
          mapperId: mapperId!,
482
        });
483
      } catch (e) {
484
        // ignore
485
      }
486
    });
487

488
    it("list protocol mappers", async () => {
489
      const { id } = currentClient;
490
      const mapperList = await kcAdminClient.clients.listProtocolMappers({
491
        id: id!,
492
      });
493
      expect(mapperList).to.be.ok;
494
    });
495

496
    it("add multiple protocol mappers", async () => {
497
      const { id } = currentClient;
498
      await kcAdminClient.clients.addMultipleProtocolMappers({ id: id! }, [
499
        dummyMapper,
500
      ]);
501

502
      const mapper = (await kcAdminClient.clients.findProtocolMapperByName({
503
        id: id!,
504
        name: dummyMapper.name!,
505
      }))!;
506
      expect(mapper).to.be.ok;
507
      expect(mapper.protocol).to.eq(dummyMapper.protocol);
508
      expect(mapper.protocolMapper).to.eq(dummyMapper.protocolMapper);
509
    });
510

511
    it("add single protocol mapper", async () => {
512
      const { id } = currentClient;
513
      await kcAdminClient.clients.addProtocolMapper({ id: id! }, dummyMapper);
514

515
      const mapper = (await kcAdminClient.clients.findProtocolMapperByName({
516
        id: id!,
517
        name: dummyMapper.name!,
518
      }))!;
519
      expect(mapper).to.be.ok;
520
      expect(mapper.protocol).to.eq(dummyMapper.protocol);
521
      expect(mapper.protocolMapper).to.eq(dummyMapper.protocolMapper);
522
    });
523

524
    it("find protocol mapper by id", async () => {
525
      const { id } = currentClient;
526
      await kcAdminClient.clients.addProtocolMapper({ id: id! }, dummyMapper);
527

528
      const { id: mapperId } =
529
        (await kcAdminClient.clients.findProtocolMapperByName({
530
          id: id!,
531
          name: dummyMapper.name!,
532
        }))!;
533

534
      const mapper = await kcAdminClient.clients.findProtocolMapperById({
535
        mapperId: mapperId!,
536
        id: id!,
537
      });
538

539
      expect(mapper).to.be.ok;
540
      expect(mapper.id).to.eql(mapperId);
541
    });
542

543
    it("find protocol mapper by name", async () => {
544
      const { id } = currentClient;
545
      await kcAdminClient.clients.addProtocolMapper({ id: id! }, dummyMapper);
546

547
      const mapper = (await kcAdminClient.clients.findProtocolMapperByName({
548
        id: id!,
549
        name: dummyMapper.name!,
550
      }))!;
551

552
      expect(mapper).to.be.ok;
553
      expect(mapper.name).to.eql(dummyMapper.name);
554
    });
555

556
    it("find protocol mappers by protocol", async () => {
557
      const { id } = currentClient;
558
      await kcAdminClient.clients.addProtocolMapper({ id: id! }, dummyMapper);
559

560
      const mapperList =
561
        await kcAdminClient.clients.findProtocolMappersByProtocol({
562
          id: id!,
563
          protocol: dummyMapper.protocol!,
564
        });
565

566
      expect(mapperList).to.be.ok;
567
      expect(mapperList.length).to.be.gte(1);
568

569
      const mapper = mapperList.find((item) => item.name === dummyMapper.name);
570
      expect(mapper).to.be.ok;
571
    });
572

573
    it("update protocol mapper", async () => {
574
      const { id } = currentClient;
575

576
      dummyMapper.config = { "access.token.claim": "true" };
577
      await kcAdminClient.clients.addProtocolMapper({ id: id! }, dummyMapper);
578
      const mapper = (await kcAdminClient.clients.findProtocolMapperByName({
579
        id: id!,
580
        name: dummyMapper.name!,
581
      }))!;
582

583
      expect(mapper.config!["access.token.claim"]).to.eq("true");
584

585
      mapper.config = { "access.token.claim": "false" };
586

587
      await kcAdminClient.clients.updateProtocolMapper(
588
        { id: id!, mapperId: mapper.id! },
589
        mapper,
590
      );
591

592
      const updatedMapper =
593
        (await kcAdminClient.clients.findProtocolMapperByName({
594
          id: id!,
595
          name: dummyMapper.name!,
596
        }))!;
597

598
      expect(updatedMapper.config!["access.token.claim"]).to.eq("false");
599
    });
600

601
    it("delete protocol mapper", async () => {
602
      const { id } = currentClient;
603
      await kcAdminClient.clients.addProtocolMapper({ id: id! }, dummyMapper);
604

605
      const { id: mapperId } =
606
        (await kcAdminClient.clients.findProtocolMapperByName({
607
          id: id!,
608
          name: dummyMapper.name!,
609
        }))!;
610

611
      await kcAdminClient.clients.delProtocolMapper({
612
        id: id!,
613
        mapperId: mapperId!,
614
      });
615

616
      const mapper = await kcAdminClient.clients.findProtocolMapperByName({
617
        id: id!,
618
        name: dummyMapper.name!,
619
      });
620

621
      expect(mapper).not.to.be.ok;
622
    });
623
  });
624

625
  describe("scope mappings", () => {
626
    it("list client and realm scope mappings", async () => {
627
      const { id } = currentClient;
628
      const scopes = await kcAdminClient.clients.listScopeMappings({
629
        id: id!,
630
      });
631
      expect(scopes).to.be.ok;
632
    });
633

634
    describe("client", () => {
635
      const dummyRoleName = "clientScopeMappingsRole-dummy";
636

637
      beforeEach(async () => {
638
        const { id } = currentClient;
639
        await kcAdminClient.clients.createRole({
640
          id,
641
          name: dummyRoleName,
642
        });
643
      });
644

645
      afterEach(async () => {
646
        try {
647
          const { id } = currentClient;
648
          await kcAdminClient.clients.delRole({
649
            id: id!,
650
            roleName: dummyRoleName,
651
          });
652
        } catch (e) {
653
          // ignore
654
        }
655
      });
656

657
      it("add scope mappings", async () => {
658
        const { id: clientUniqueId } = currentClient;
659

660
        const availableRoles =
661
          await kcAdminClient.clients.listAvailableClientScopeMappings({
662
            id: clientUniqueId!,
663
            client: clientUniqueId!,
664
          });
665

666
        await kcAdminClient.clients.addClientScopeMappings(
667
          {
668
            id: clientUniqueId!,
669
            client: clientUniqueId!,
670
          },
671
          availableRoles,
672
        );
673

674
        const roles = await kcAdminClient.clients.listClientScopeMappings({
675
          id: clientUniqueId!,
676
          client: clientUniqueId!,
677
        });
678

679
        expect(roles).to.be.ok;
680
        expect(roles).to.be.eql(availableRoles);
681
      });
682

683
      it("list scope mappings", async () => {
684
        const { id: clientUniqueId } = currentClient;
685
        const roles = await kcAdminClient.clients.listClientScopeMappings({
686
          id: clientUniqueId!,
687
          client: clientUniqueId!,
688
        });
689
        expect(roles).to.be.ok;
690
      });
691

692
      it("list available scope mappings", async () => {
693
        const { id: clientUniqueId } = currentClient;
694
        const roles =
695
          await kcAdminClient.clients.listAvailableClientScopeMappings({
696
            id: clientUniqueId!,
697
            client: clientUniqueId!,
698
          });
699
        expect(roles).to.be.ok;
700
      });
701

702
      it("list composite scope mappings", async () => {
703
        const { id: clientUniqueId } = currentClient;
704
        const roles =
705
          await kcAdminClient.clients.listCompositeClientScopeMappings({
706
            id: clientUniqueId!,
707
            client: clientUniqueId!,
708
          });
709
        expect(roles).to.be.ok;
710
      });
711

712
      it("delete scope mappings", async () => {
713
        const { id: clientUniqueId } = currentClient;
714

715
        const rolesBefore = await kcAdminClient.clients.listClientScopeMappings(
716
          {
717
            id: clientUniqueId!,
718
            client: clientUniqueId!,
719
          },
720
        );
721

722
        await kcAdminClient.clients.delClientScopeMappings(
723
          {
724
            id: clientUniqueId!,
725
            client: clientUniqueId!,
726
          },
727
          rolesBefore,
728
        );
729

730
        const rolesAfter = await kcAdminClient.clients.listClientScopeMappings({
731
          id: clientUniqueId!,
732
          client: clientUniqueId!,
733
        });
734

735
        expect(rolesAfter).to.be.ok;
736
        expect(rolesAfter).to.eql([]);
737
      });
738

739
      it("get effective scope mapping of all roles for a specific container", async () => {
740
        const { id: clientUniqueId } = currentClient;
741
        const roles = await kcAdminClient.clients.evaluatePermission({
742
          id: clientUniqueId!,
743
          roleContainer: "master",
744
          type: "granted",
745
          scope: "openid",
746
        });
747

748
        expect(roles).to.be.ok;
749
        expect(roles.length).to.be.eq(5);
750
      });
751

752
      it("get list of all protocol mappers", async () => {
753
        const { id: clientUniqueId } = currentClient;
754
        const protocolMappers =
755
          await kcAdminClient.clients.evaluateListProtocolMapper({
756
            id: clientUniqueId!,
757
            scope: "openid",
758
          });
759
        expect(protocolMappers).to.be.ok;
760
        expect(protocolMappers.length).to.be.gt(10);
761
      });
762

763
      it("get JSON with payload of examples", async () => {
764
        const { id: clientUniqueId } = currentClient;
765
        const username = faker.internet.userName();
766
        const user = await kcAdminClient.users.create({
767
          username,
768
        });
769
        const accessToken =
770
          await kcAdminClient.clients.evaluateGenerateAccessToken({
771
            id: clientUniqueId!,
772
            userId: user.id,
773
            scope: "openid",
774
          });
775
        const idToken = await kcAdminClient.clients.evaluateGenerateIdToken({
776
          id: clientUniqueId!,
777
          userId: user.id,
778
          scope: "openid",
779
        });
780
        const userInfo = await kcAdminClient.clients.evaluateGenerateUserInfo({
781
          id: clientUniqueId!,
782
          userId: user.id,
783
          scope: "openid",
784
        });
785

786
        expect(accessToken).to.be.ok;
787
        expect(idToken).to.be.ok;
788
        expect(userInfo).to.be.ok;
789
        await kcAdminClient.users.del({ id: user.id });
790
      });
791
    });
792

793
    describe("realm", () => {
794
      const dummyRoleName = "realmScopeMappingsRole-dummy";
795

796
      beforeEach(async () => {
797
        await kcAdminClient.roles.create({
798
          name: dummyRoleName,
799
        });
800
      });
801

802
      afterEach(async () => {
803
        try {
804
          await kcAdminClient.roles.delByName({
805
            name: dummyRoleName,
806
          });
807
        } catch (e) {
808
          // ignore
809
        }
810
      });
811

812
      it("add scope mappings", async () => {
813
        const { id } = currentClient;
814

815
        const availableRoles =
816
          await kcAdminClient.clients.listAvailableRealmScopeMappings({
817
            id: id!,
818
          });
819

820
        await kcAdminClient.clients.addRealmScopeMappings(
821
          { id: id! },
822
          availableRoles,
823
        );
824

825
        const roles = await kcAdminClient.clients.listRealmScopeMappings({
826
          id: id!,
827
        });
828

829
        expect(roles).to.be.ok;
830
        expect(roles).to.deep.members(availableRoles);
831
      });
832

833
      it("list scope mappings", async () => {
834
        const { id } = currentClient;
835
        const roles = await kcAdminClient.clients.listRealmScopeMappings({
836
          id: id!,
837
        });
838
        expect(roles).to.be.ok;
839
      });
840

841
      it("list available scope mappings", async () => {
842
        const { id } = currentClient;
843
        const roles =
844
          await kcAdminClient.clients.listAvailableRealmScopeMappings({
845
            id: id!,
846
          });
847
        expect(roles).to.be.ok;
848
      });
849

850
      it("list composite scope mappings", async () => {
851
        const { id } = currentClient;
852
        const roles =
853
          await kcAdminClient.clients.listCompositeRealmScopeMappings({
854
            id: id!,
855
          });
856
        expect(roles).to.be.ok;
857
      });
858

859
      it("delete scope mappings", async () => {
860
        const { id } = currentClient;
861

862
        const rolesBefore = await kcAdminClient.clients.listRealmScopeMappings({
863
          id: id!,
864
        });
865

866
        await kcAdminClient.clients.delRealmScopeMappings(
867
          { id: id! },
868
          rolesBefore,
869
        );
870

871
        const rolesAfter = await kcAdminClient.clients.listRealmScopeMappings({
872
          id: id!,
873
        });
874

875
        expect(rolesAfter).to.be.ok;
876
        expect(rolesAfter).to.eql([]);
877
      });
878
    });
879
  });
880

881
  describe("sessions", () => {
882
    it("list clients user sessions", async () => {
883
      const clientUniqueId = currentClient.id;
884
      const userSessions = await kcAdminClient.clients.listSessions({
885
        id: clientUniqueId!,
886
      });
887
      expect(userSessions).to.be.ok;
888
    });
889

890
    it("list clients offline user sessions", async () => {
891
      const clientUniqueId = currentClient.id;
892
      const userSessions = await kcAdminClient.clients.listOfflineSessions({
893
        id: clientUniqueId!,
894
      });
895
      expect(userSessions).to.be.ok;
896
    });
897

898
    it("list clients user session count", async () => {
899
      const clientUniqueId = currentClient.id;
900
      const userSessions = await kcAdminClient.clients.getSessionCount({
901
        id: clientUniqueId!,
902
      });
903
      expect(userSessions).to.be.ok;
904
    });
905

906
    it("list clients offline user session count", async () => {
907
      const clientUniqueId = currentClient.id;
908
      const userSessions = await kcAdminClient.clients.getOfflineSessionCount({
909
        id: clientUniqueId!,
910
      });
911
      expect(userSessions).to.be.ok;
912
    });
913
  });
914

915
  describe("nodes", () => {
916
    const host = "127.0.0.1";
917
    it("register a node manually", async () => {
918
      await kcAdminClient.clients.addClusterNode({
919
        id: currentClient.id!,
920
        node: host,
921
      });
922
      const client = (await kcAdminClient.clients.findOne({
923
        id: currentClient.id!,
924
      }))!;
925

926
      expect(Object.keys(client.registeredNodes!)).to.be.eql([host]);
927
    });
928

929
    it("remove registered host", async () => {
930
      await kcAdminClient.clients.deleteClusterNode({
931
        id: currentClient.id!,
932
        node: host,
933
      });
934
      const client = (await kcAdminClient.clients.findOne({
935
        id: currentClient.id!,
936
      }))!;
937

938
      expect(client.registeredNodes).to.be.undefined;
939
    });
940
  });
941

942
  describe("client attribute certificate", () => {
943
    const keystoreConfig = {
944
      format: "JKS",
945
      keyAlias: "new",
946
      keyPassword: "password",
947
      realmAlias: "master",
948
      realmCertificate: false,
949
      storePassword: "password",
950
    };
951
    const attr = "jwt.credential";
952

953
    it("generate and download keys", async () => {
954
      const result = await kcAdminClient.clients.generateAndDownloadKey(
955
        { id: currentClient.id!, attr },
956
        keystoreConfig,
957
      );
958

959
      expect(result).to.be.ok;
960
    });
961

962
    it("generate key and updated info", async () => {
963
      const certificate = await kcAdminClient.clients.generateKey({
964
        id: currentClient.id!,
965
        attr,
966
      });
967

968
      expect(certificate).to.be.ok;
969
      expect(certificate.certificate).to.be.ok;
970

971
      const info = await kcAdminClient.clients.getKeyInfo({
972
        id: currentClient.id!,
973
        attr,
974
      });
975
      expect(info).to.be.eql(certificate);
976
    });
977

978
    it("download key", async () => {
979
      const result = await kcAdminClient.clients.downloadKey(
980
        { id: currentClient.id!, attr },
981
        keystoreConfig,
982
      );
983

984
      expect(result).to.be.ok;
985
    });
986
  });
987

988
  describe("authorization", async () => {
989
    const resourceConfig = {
990
      name: "testResourceName",
991
      type: "testResourceType",
992
      scopeNames: ["testScopeA", "testScopeB", "testScopeC"],
993
    };
994
    const policyConfig = {
995
      name: "testPolicyName",
996
      type: "user",
997
      logic: Logic.POSITIVE,
998
    };
999
    const permissionConfig = {
1000
      name: "testPermissionName",
1001
      type: "scope",
1002
      logic: Logic.POSITIVE,
1003
    };
1004
    let scopes: ScopeRepresentation[];
1005
    let resource: ResourceRepresentation;
1006
    let policy: PolicyRepresentation;
1007
    let permission: PolicyRepresentation;
1008
    let user: UserRepresentation;
1009

1010
    before("enable authorization services", async () => {
1011
      await kcAdminClient.clients.update(
1012
        { id: currentClient.id! },
1013
        {
1014
          clientId: currentClient.clientId,
1015
          authorizationServicesEnabled: true,
1016
          serviceAccountsEnabled: true,
1017
        },
1018
      );
1019
    });
1020

1021
    before("create test user", async () => {
1022
      const username = faker.internet.userName();
1023
      user = await kcAdminClient.users.create({
1024
        username,
1025
      });
1026
    });
1027

1028
    after("delete test user", async () => {
1029
      await kcAdminClient.users.del({
1030
        id: user.id!,
1031
      });
1032
    });
1033

1034
    after("disable authorization services", async () => {
1035
      await kcAdminClient.clients.update(
1036
        { id: currentClient.id! },
1037
        {
1038
          clientId: currentClient.clientId,
1039
          authorizationServicesEnabled: false,
1040
          serviceAccountsEnabled: false,
1041
        },
1042
      );
1043
    });
1044

1045
    it("create authorization scopes", async () => {
1046
      scopes = (
1047
        await Promise.all(
1048
          resourceConfig.scopeNames.map(async (name) => {
1049
            const result = await kcAdminClient.clients.createAuthorizationScope(
1050
              { id: currentClient.id! },
1051
              {
1052
                name,
1053
              },
1054
            );
1055
            expect(result).to.be.ok;
1056
            return result;
1057
          }),
1058
        )
1059
      ).sort((a, b) => (a.name < b.name ? -1 : 1));
1060
    });
1061

1062
    it("list all authorization scopes", async () => {
1063
      const result = await kcAdminClient.clients.listAllScopes({
1064
        id: currentClient.id!,
1065
      });
1066
      expect(result.sort((a, b) => (a.name! < b.name! ? -1 : 1))).to.deep.equal(
1067
        scopes,
1068
      );
1069
    });
1070

1071
    it("update authorization scope", async () => {
1072
      const updatedScope = { ...scopes[0], displayName: "Hello" };
1073
      await kcAdminClient.clients.updateAuthorizationScope(
1074
        { id: currentClient.id!, scopeId: scopes[0].id! },
1075
        updatedScope,
1076
      );
1077

1078
      const fetchedScope = await kcAdminClient.clients.getAuthorizationScope({
1079
        id: currentClient.id!,
1080
        scopeId: scopes[0].id!,
1081
      });
1082

1083
      expect(fetchedScope).to.deep.equal(updatedScope);
1084
    });
1085

1086
    it("list all resources by scope", async () => {
1087
      const result = await kcAdminClient.clients.listAllResourcesByScope({
1088
        id: currentClient.id!,
1089
        scopeId: scopes[0].id!,
1090
      });
1091
      expect(result).to.deep.equal([]);
1092
    });
1093

1094
    it("list all permissions by scope", async () => {
1095
      const result = await kcAdminClient.clients.listAllPermissionsByScope({
1096
        id: currentClient.id!,
1097
        scopeId: scopes[0].id!,
1098
      });
1099
      expect(result).to.deep.equal([]);
1100
    });
1101

1102
    it("import resource", async () => {
1103
      await kcAdminClient.clients.importResource(
1104
        { id: currentClient.id! },
1105
        {
1106
          allowRemoteResourceManagement: true,
1107
          policyEnforcementMode: "ENFORCING",
1108
          resources: [],
1109
          policies: [],
1110
          scopes: [],
1111
          decisionStrategy: "UNANIMOUS",
1112
        },
1113
      );
1114
    });
1115

1116
    it("export resource", async () => {
1117
      const result = await kcAdminClient.clients.exportResource({
1118
        id: currentClient.id!,
1119
      });
1120

1121
      expect(result.allowRemoteResourceManagement).to.be.equal(true);
1122
      expect(result.resources?.length).to.be.equal(1);
1123
    });
1124

1125
    it("create resource", async () => {
1126
      resource = await kcAdminClient.clients.createResource(
1127
        { id: currentClient.id! },
1128
        {
1129
          name: resourceConfig.name,
1130
          type: resourceConfig.type,
1131
          scopes,
1132
        },
1133
      );
1134
      expect(resource).to.be.ok;
1135
    });
1136

1137
    it("get resource", async () => {
1138
      const r = await kcAdminClient.clients.getResource({
1139
        id: currentClient.id!,
1140
        resourceId: resource._id!,
1141
      });
1142
      expect(r).to.deep.equal(resource);
1143
    });
1144

1145
    it("get resource server", async () => {
1146
      const resourceServer = await kcAdminClient.clients.getResourceServer({
1147
        id: currentClient.id!,
1148
      });
1149
      expect(resourceServer).to.be.ok;
1150
      expect(resourceServer.clientId).to.be.equal(currentClient.id);
1151

1152
      resourceServer.decisionStrategy = "UNANIMOUS";
1153
      await kcAdminClient.clients.updateResourceServer(
1154
        { id: currentClient.id! },
1155
        resourceServer,
1156
      );
1157
    });
1158

1159
    it("list permission by resource", async () => {
1160
      const result = await kcAdminClient.clients.listPermissionsByResource({
1161
        id: currentClient.id!,
1162
        resourceId: resource._id!,
1163
      });
1164

1165
      expect(result).to.be.ok;
1166
    });
1167

1168
    it("list scopes by resource", async () => {
1169
      const result = await kcAdminClient.clients.listScopesByResource({
1170
        id: currentClient.id!,
1171
        resourceName: resource._id!,
1172
      });
1173
      expect(result.sort((a, b) => (a.name < b.name ? -1 : 1))).to.deep.equal(
1174
        scopes,
1175
      );
1176
    });
1177

1178
    it("list resources", async () => {
1179
      const result = await kcAdminClient.clients.listResources({
1180
        id: currentClient.id!,
1181
      });
1182
      expect(result).to.deep.include(resource);
1183
    });
1184

1185
    it("update resource", async () => {
1186
      resource.name = "foo";
1187
      await kcAdminClient.clients.updateResource(
1188
        {
1189
          id: currentClient.id!,
1190
          resourceId: resource._id!,
1191
        },
1192
        resource,
1193
      );
1194
      const result = await kcAdminClient.clients.getResource({
1195
        id: currentClient.id!,
1196
        resourceId: resource._id!,
1197
      });
1198

1199
      expect(result.name).to.equal("foo");
1200
    });
1201

1202
    it("create policy", async () => {
1203
      policy = await kcAdminClient.clients.createPolicy(
1204
        {
1205
          id: currentClient.id!,
1206
          type: policyConfig.type,
1207
        },
1208
        {
1209
          name: policyConfig.name,
1210
          logic: policyConfig.logic,
1211
          users: [user.id!],
1212
        },
1213
      );
1214
      expect(policy).to.be.ok;
1215
    });
1216

1217
    it("policy list dependencies", async () => {
1218
      const dependencies = await kcAdminClient.clients.listDependentPolicies({
1219
        id: currentClient.id!,
1220
        policyId: policy.id!,
1221
      });
1222
      expect(dependencies).to.be.ok;
1223
    });
1224

1225
    it("create permission", async () => {
1226
      permission = await kcAdminClient.clients.createPermission(
1227
        {
1228
          id: currentClient.id!,
1229
          type: "scope",
1230
        },
1231
        {
1232
          name: permissionConfig.name,
1233
          logic: permissionConfig.logic,
1234
          // @ts-ignore
1235
          resources: [resource._id],
1236
          policies: [policy.id!],
1237
          scopes: scopes.map((scope) => scope.id!),
1238
        },
1239
      );
1240

1241
      const p = await kcAdminClient.clients.findPermissions({
1242
        id: currentClient.id!,
1243
        name: permissionConfig.name,
1244
      });
1245

1246
      expect(p.length).to.be.eq(1);
1247
      expect(p[0].logic).to.be.eq(permissionConfig.logic);
1248
    });
1249

1250
    it("get associated scopes for permission", async () => {
1251
      const result = await kcAdminClient.clients.getAssociatedScopes({
1252
        id: currentClient.id!,
1253
        permissionId: permission.id!,
1254
      });
1255
      expect(result.sort((a, b) => (a.name < b.name ? -1 : 1))).to.deep.equal(
1256
        scopes,
1257
      );
1258
    });
1259

1260
    it("get associated policies for permission", async () => {
1261
      const result = await kcAdminClient.clients.getAssociatedPolicies({
1262
        id: currentClient.id!,
1263
        permissionId: permission.id!,
1264
      });
1265

1266
      expect(result.length).to.be.eq(1);
1267
      expect(result[0].id).to.be.eq(policy.id);
1268
    });
1269

1270
    it("get associated resources for permission", async () => {
1271
      const result = await kcAdminClient.clients.getAssociatedResources({
1272
        id: currentClient.id!,
1273
        permissionId: permission.id!,
1274
      });
1275
      expect(result).to.deep.equal([
1276
        {
1277
          _id: resource._id,
1278
          name: resource.name,
1279
        },
1280
      ]);
1281
    });
1282

1283
    it("list policy providers", async () => {
1284
      const result = await kcAdminClient.clients.listPolicyProviders({
1285
        id: currentClient.id!,
1286
      });
1287
      expect(result).to.be.ok;
1288
    });
1289

1290
    it.skip("Enable fine grained permissions", async () => {
1291
      const permission = await kcAdminClient.clients.updateFineGrainPermission(
1292
        { id: currentClient.id! },
1293
        { enabled: true },
1294
      );
1295
      expect(permission).to.include({
1296
        enabled: true,
1297
      });
1298
    });
1299

1300
    it.skip("List fine grained permissions for this client", async () => {
1301
      const permissions = (await kcAdminClient.clients.listFineGrainPermissions(
1302
        { id: currentClient.id! },
1303
      ))!;
1304

1305
      expect(permissions.scopePermissions).to.be.an("object");
1306
    });
1307
  });
1308
});
1309

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.