@virtru/dsp-sdk 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/.rush/temp/chunked-rush-logs/dsp-sdk._phase_build.chunks.jsonl +3 -3
  2. package/.rush/temp/chunked-rush-logs/dsp-sdk._phase_test.chunks.jsonl +37 -9
  3. package/.rush/temp/package-deps__phase_build.json +16 -8
  4. package/.rush/temp/shrinkwrap-deps.json +39 -35
  5. package/CHANGELOG.json +28 -0
  6. package/CHANGELOG.md +15 -1
  7. package/README.md +55 -0
  8. package/buf.gen.yaml +17 -0
  9. package/buf.yaml +4 -0
  10. package/dist/src/gen/virtru/common/common_pb.d.ts +151 -0
  11. package/dist/src/gen/virtru/common/common_pb.js +57 -0
  12. package/dist/src/gen/virtru/policy/certificates/v1/certificates_pb.d.ts +215 -0
  13. package/dist/src/gen/virtru/policy/certificates/v1/certificates_pb.js +50 -0
  14. package/dist/src/gen/virtru/policy/objects_pb.d.ts +188 -0
  15. package/dist/src/gen/virtru/policy/objects_pb.js +126 -0
  16. package/dist/src/index.d.ts +1 -1
  17. package/dist/src/index.js +1 -1
  18. package/dist/src/lib/client.d.ts +2 -0
  19. package/dist/src/lib/client.js +2 -0
  20. package/dist/src/lib/consts.d.ts +2 -0
  21. package/dist/src/lib/consts.js +7 -0
  22. package/dist/src/lib/utils.d.ts +136 -0
  23. package/dist/src/lib/utils.js +355 -2
  24. package/package.json +5 -3
  25. package/src/gen/virtru/common/common_pb.ts +179 -0
  26. package/src/gen/virtru/policy/certificates/v1/certificates_connect.ts +44 -0
  27. package/src/gen/virtru/policy/certificates/v1/certificates_pb.ts +260 -0
  28. package/src/gen/virtru/policy/objects_pb.ts +235 -0
  29. package/src/index.ts +15 -1
  30. package/src/lib/client.ts +3 -0
  31. package/src/lib/consts.ts +8 -0
  32. package/src/lib/utils.test.ts +376 -0
  33. package/src/lib/utils.ts +460 -4
@@ -0,0 +1,376 @@
1
+ /*
2
+ * Copyright (c) Virtru Corporation. All rights reserved.
3
+ *
4
+ * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
8
+
9
+ // Mock all @opentdf imports BEFORE importing utils
10
+ vi.mock('@opentdf/sdk', () => ({
11
+ AuthProviders: {
12
+ refreshAuthProvider: vi.fn()
13
+ },
14
+ OpenTDF: vi.fn(),
15
+ PermissionDeniedError: class PermissionDeniedError extends Error {}
16
+ }));
17
+
18
+ vi.mock('@opentdf/sdk/platform', () => ({
19
+ PlatformClient: vi.fn()
20
+ }));
21
+
22
+ vi.mock('@opentdf/sdk/platform/policy/objects_pb.js', () => ({
23
+ Certificate: class Certificate {
24
+ pem?: string;
25
+ constructor(data?: any) {
26
+ if (data) Object.assign(this, data);
27
+ }
28
+ }
29
+ }));
30
+
31
+ vi.mock('@opentdf/sdk/platform/common/common_pb.js', () => ({
32
+ ActiveStateEnum: {
33
+ ACTIVE: 1
34
+ }
35
+ }));
36
+
37
+ // Polyfill atob if needed
38
+ if (typeof (globalThis as any).atob === 'undefined') {
39
+ (globalThis as any).atob = (b64: string) => Buffer.from(b64, 'base64').toString('binary');
40
+ }
41
+
42
+ // Mock pkijs/asn1js with a way to control them
43
+ const mockState = {
44
+ asn1Mode: 'ok' as 'ok' | 'bad-der',
45
+ verifyResult: { result: true } as { result: boolean; resultMessage?: string },
46
+ };
47
+
48
+ vi.mock('asn1js', () => ({
49
+ fromBER: vi.fn((_: ArrayBuffer) => {
50
+ if (mockState.asn1Mode === 'bad-der') return { offset: -1 };
51
+ return { offset: 0, result: { subject: { typesAndValues: [] }, issuer: { typesAndValues: [] } } };
52
+ }),
53
+ }));
54
+
55
+ vi.mock('pkijs', () => {
56
+ return {
57
+ Certificate: class Certificate {
58
+ public subject: any = { typesAndValues: [] };
59
+ public issuer: any = { typesAndValues: [] };
60
+ public subjectPublicKeyInfo: any = {};
61
+ constructor(_: any) {}
62
+ },
63
+ CertificateChainValidationEngine: class CertificateChainValidationEngine {
64
+ constructor(_: any) {}
65
+ async verify() {
66
+ return mockState.verifyResult;
67
+ }
68
+ }
69
+ };
70
+ });
71
+
72
+ // Mock DSPClient
73
+ vi.mock('./client', () => ({
74
+ DSPClient: vi.fn()
75
+ }));
76
+
77
+ // NOW import utils
78
+ import { validateJWSCertificateChain, getTrustedCertificates } from './utils';
79
+ import { DSPClient } from './client';
80
+ import { PlatformClient } from '@opentdf/sdk/platform';
81
+ import { AuthProviders } from '@opentdf/sdk';
82
+
83
+ describe('validateJWSCertificateChain', () => {
84
+ beforeEach(() => {
85
+ mockState.asn1Mode = 'ok';
86
+ mockState.verifyResult = { result: true };
87
+ });
88
+
89
+ it('throws error when x5c is empty', async () => {
90
+ await expect(validateJWSCertificateChain([], [{ pem: '---' }] as any))
91
+ .rejects.toThrow(/No certificates provided in x5c array/);
92
+ });
93
+
94
+ it('throws error when too many certificates in x5c', async () => {
95
+ const tooMany = new Array(11).fill('AQI=');
96
+ await expect(validateJWSCertificateChain(tooMany, [{ pem: '---' }] as any))
97
+ .rejects.toThrow(/Too many certificates in x5c/);
98
+ });
99
+
100
+ it('throws error when no trusted roots provided', async () => {
101
+ await expect(validateJWSCertificateChain(['AQI='], [] as any))
102
+ .rejects.toThrow(/No trusted root certificates provided/);
103
+ });
104
+
105
+ it('fails on invalid base64 in x5c', async () => {
106
+ await expect(validateJWSCertificateChain(['***not-base64***'], [{ pem: '---' }] as any))
107
+ .rejects.toThrow(/Failed to parse certificate at x5c\[0]/);
108
+ });
109
+
110
+ it('fails on ASN.1 parse error', async () => {
111
+ mockState.asn1Mode = 'bad-der';
112
+ await expect(validateJWSCertificateChain(['AQI='], [{ pem: '---' }] as any))
113
+ .rejects.toThrow(/Invalid DER encoding/);
114
+ });
115
+
116
+ it('returns valid true on successful verification', async () => {
117
+ const pem = '-----BEGIN CERTIFICATE-----\nAQI=\n-----END CERTIFICATE-----';
118
+ mockState.verifyResult = { result: true };
119
+ const res = await validateJWSCertificateChain(['AQI='], [{ pem }] as any);
120
+ expect(res.valid).toBe(true);
121
+ expect(res.validationResult.warnings).toEqual([]);
122
+ });
123
+
124
+ it('returns warnings when some trusted roots fail to parse', async () => {
125
+ const pem = '-----BEGIN CERTIFICATE-----\nAQI=\n-----END CERTIFICATE-----';
126
+ const res = await validateJWSCertificateChain(['AQI='], [{ pem: '' }, { pem }] as any);
127
+ expect(res.valid).toBe(true);
128
+ expect(res.validationResult.warnings).toHaveLength(1);
129
+ expect(res.validationResult.warnings[0]).toMatch(/has no PEM data/);
130
+ });
131
+ });
132
+
133
+ describe('getTrustedCertificates', () => {
134
+ const mockOptions = {
135
+ oidc: {
136
+ clientId: 'test-client-id',
137
+ tokenEndpoint: 'https://auth.test.com/token',
138
+ userInfoEndpoint: 'https://auth.test.com/userinfo',
139
+ },
140
+ platformEndpoint: 'https://platform.test.com',
141
+ refreshToken: 'test-refresh-token',
142
+ };
143
+
144
+ let mockAuthProvider: any;
145
+ let mockPlatformClient: any;
146
+ let mockDSPClient: any;
147
+ let mockCertificateService: any;
148
+
149
+ beforeEach(() => {
150
+ vi.clearAllMocks();
151
+
152
+ // Mock crypto.subtle.generateKey for DPoP signing keys
153
+ if (!globalThis.crypto) {
154
+ (globalThis as any).crypto = {};
155
+ }
156
+ if (!globalThis.crypto.subtle) {
157
+ (globalThis.crypto as any).subtle = {};
158
+ }
159
+ (globalThis.crypto.subtle as any).generateKey = vi.fn().mockResolvedValue({
160
+ publicKey: {},
161
+ privateKey: {},
162
+ });
163
+
164
+ // Mock auth provider
165
+ mockAuthProvider = {
166
+ updateClientPublicKey: vi.fn().mockResolvedValue(undefined),
167
+ };
168
+
169
+ (AuthProviders.refreshAuthProvider as any).mockResolvedValue(mockAuthProvider);
170
+
171
+ // Mock certificate service
172
+ mockCertificateService = {
173
+ listCertificatesByNamespace: vi.fn(),
174
+ };
175
+
176
+ // Mock DSP client
177
+ mockDSPClient = {
178
+ v1: {
179
+ certificateService: mockCertificateService,
180
+ },
181
+ };
182
+
183
+ (DSPClient as any).mockImplementation(() => mockDSPClient);
184
+
185
+ // Mock platform client
186
+ mockPlatformClient = {
187
+ v1: {
188
+ namespace: {
189
+ listNamespaces: vi.fn(),
190
+ },
191
+ },
192
+ };
193
+
194
+ (PlatformClient as any).mockImplementation(() => mockPlatformClient);
195
+ });
196
+
197
+ it('successfully retrieves certificates from a single namespace', async () => {
198
+ const mockCertificate1 = { pem: 'cert1-pem-data' };
199
+ const mockCertificate2 = { pem: 'cert2-pem-data' };
200
+
201
+ mockPlatformClient.v1.namespace.listNamespaces.mockResolvedValue({
202
+ namespaces: [{ id: 'namespace-1' }],
203
+ });
204
+
205
+ mockCertificateService.listCertificatesByNamespace.mockResolvedValue({
206
+ certificates: [mockCertificate1, mockCertificate2],
207
+ pagination: { nextOffset: 0 },
208
+ });
209
+
210
+ const result = await getTrustedCertificates(mockOptions);
211
+
212
+ expect(result).toHaveLength(2);
213
+ expect(result).toEqual([mockCertificate1, mockCertificate2]);
214
+ expect(mockCertificateService.listCertificatesByNamespace).toHaveBeenCalledWith({
215
+ namespaceId: 'namespace-1',
216
+ pagination: { limit: (100), offset: (0) },
217
+ });
218
+ });
219
+
220
+ it('successfully retrieves certificates from multiple namespaces', async () => {
221
+ const mockCert1 = { pem: 'cert1-pem' };
222
+ const mockCert2 = { pem: 'cert2-pem' };
223
+ const mockCert3 = { pem: 'cert3-pem' };
224
+
225
+ mockPlatformClient.v1.namespace.listNamespaces.mockResolvedValue({
226
+ namespaces: [{ id: 'namespace-1' }, { id: 'namespace-2' }],
227
+ });
228
+
229
+ mockCertificateService.listCertificatesByNamespace
230
+ .mockResolvedValueOnce({
231
+ certificates: [mockCert1, mockCert2],
232
+ pagination: { nextOffset: (0) },
233
+ })
234
+ .mockResolvedValueOnce({
235
+ certificates: [mockCert3],
236
+ pagination: { nextOffset: (0) },
237
+ });
238
+
239
+ const result = await getTrustedCertificates(mockOptions);
240
+
241
+ expect(result).toHaveLength(3);
242
+ expect(result).toEqual([mockCert1, mockCert2, mockCert3]);
243
+ expect(mockCertificateService.listCertificatesByNamespace).toHaveBeenCalledTimes(2);
244
+ });
245
+
246
+ it('handles pagination correctly (multiple pages)', async () => {
247
+ const mockCert1 = { pem: 'cert1' };
248
+ const mockCert2 = { pem: 'cert2' };
249
+ const mockCert3 = { pem: 'cert3' };
250
+
251
+ mockPlatformClient.v1.namespace.listNamespaces.mockResolvedValue({
252
+ namespaces: [{ id: 'namespace-1' }],
253
+ });
254
+
255
+ // First page
256
+ mockCertificateService.listCertificatesByNamespace
257
+ .mockResolvedValueOnce({
258
+ certificates: [mockCert1, mockCert2],
259
+ pagination: { nextOffset: (100) },
260
+ })
261
+ // Second page
262
+ .mockResolvedValueOnce({
263
+ certificates: [mockCert3],
264
+ pagination: { nextOffset: (0) },
265
+ });
266
+
267
+ const result = await getTrustedCertificates(mockOptions);
268
+
269
+ expect(result).toHaveLength(3);
270
+ expect(result).toEqual([mockCert1, mockCert2, mockCert3]);
271
+ expect(mockCertificateService.listCertificatesByNamespace).toHaveBeenCalledTimes(2);
272
+ expect(mockCertificateService.listCertificatesByNamespace).toHaveBeenNthCalledWith(1, {
273
+ namespaceId: 'namespace-1',
274
+ pagination: { limit: (100), offset: (0) },
275
+ });
276
+ expect(mockCertificateService.listCertificatesByNamespace).toHaveBeenNthCalledWith(2, {
277
+ namespaceId: 'namespace-1',
278
+ pagination: { limit: (100), offset: (100) },
279
+ });
280
+ });
281
+
282
+ it('handles empty certificate list', async () => {
283
+ mockPlatformClient.v1.namespace.listNamespaces.mockResolvedValue({
284
+ namespaces: [{ id: 'namespace-1' }],
285
+ });
286
+
287
+ mockCertificateService.listCertificatesByNamespace.mockResolvedValue({
288
+ certificates: [],
289
+ pagination: { nextOffset: (0) },
290
+ });
291
+
292
+ const result = await getTrustedCertificates(mockOptions);
293
+
294
+ expect(result).toHaveLength(0);
295
+ expect(result).toEqual([]);
296
+ });
297
+
298
+ it('handles errors from certificate service', async () => {
299
+ mockPlatformClient.v1.namespace.listNamespaces.mockResolvedValue({
300
+ namespaces: [{ id: 'namespace-1' }],
301
+ });
302
+
303
+ mockCertificateService.listCertificatesByNamespace.mockRejectedValue(
304
+ new Error('Certificate service error')
305
+ );
306
+
307
+ await expect(getTrustedCertificates(mockOptions)).rejects.toThrow('Certificate service error');
308
+ });
309
+
310
+ it('handles errors from namespace listing', async () => {
311
+ mockPlatformClient.v1.namespace.listNamespaces.mockRejectedValue(
312
+ new Error('Namespace listing error')
313
+ );
314
+
315
+ await expect(getTrustedCertificates(mockOptions)).rejects.toThrow('Namespace listing error');
316
+ });
317
+
318
+ it('initializes auth provider correctly', async () => {
319
+ mockPlatformClient.v1.namespace.listNamespaces.mockResolvedValue({
320
+ namespaces: [],
321
+ });
322
+
323
+ await getTrustedCertificates(mockOptions);
324
+
325
+ expect(AuthProviders.refreshAuthProvider).toHaveBeenCalled();
326
+ expect(mockAuthProvider.updateClientPublicKey).toHaveBeenCalled();
327
+ expect(globalThis.crypto.subtle.generateKey).toHaveBeenCalledWith(
328
+ {
329
+ name: 'ECDSA',
330
+ namedCurve: 'P-256',
331
+ },
332
+ true,
333
+ ['sign', 'verify']
334
+ );
335
+ });
336
+
337
+ it('creates both PlatformClient and DSPClient with correct config', async () => {
338
+ mockPlatformClient.v1.namespace.listNamespaces.mockResolvedValue({
339
+ namespaces: [],
340
+ });
341
+
342
+ await getTrustedCertificates(mockOptions);
343
+
344
+ expect(PlatformClient).toHaveBeenCalledWith({
345
+ authProvider: mockAuthProvider,
346
+ platformUrl: mockOptions.platformEndpoint,
347
+ });
348
+
349
+ expect(DSPClient).toHaveBeenCalledWith({
350
+ platformUrl: mockOptions.platformEndpoint,
351
+ authProvider: mockAuthProvider,
352
+ });
353
+ });
354
+
355
+ it('returns same Certificate type compatible with validateJWSCertificateChain', async () => {
356
+ const mockCert = { pem: '-----BEGIN CERTIFICATE-----\nAQI=\n-----END CERTIFICATE-----' };
357
+
358
+ mockPlatformClient.v1.namespace.listNamespaces.mockResolvedValue({
359
+ namespaces: [{ id: 'namespace-1' }],
360
+ });
361
+
362
+ mockCertificateService.listCertificatesByNamespace.mockResolvedValue({
363
+ certificates: [mockCert],
364
+ pagination: { nextOffset: (0) },
365
+ });
366
+
367
+ const result = await getTrustedCertificates(mockOptions);
368
+
369
+ // Verify the result can be used with validateJWSCertificateChain
370
+ expect(result[0].pem).toBeDefined();
371
+
372
+ // Integration test: verify compatibility with validateJWSCertificateChain
373
+ const validationResult = await validateJWSCertificateChain(['AQI='], result);
374
+ expect(validationResult.valid).toBe(true);
375
+ });
376
+ });