@tdxvolt/volt-client-grpc 0.1.1 → 0.11.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.
@@ -5,285 +5,355 @@ import bent from "bent";
5
5
  import forge from "node-forge";
6
6
  import lodash from "lodash";
7
7
  import VoltConnection from "./volt-connection.js";
8
- import {getServiceDescriptors} from "./proto-utils.js";
9
- import {createClient as createGrpcClient} from "./grpc-utils.js";
8
+ import { getServiceDescriptors } from "./proto-utils.js";
9
+ import { createClient as createGrpcClient } from "./grpc-utils.js";
10
10
  import * as voltUtils from "./utils.js";
11
- import {constants} from "./constants.js";
11
+ import { constants } from "./constants.js";
12
12
  import GRPCCall from "./grpc-call.js";
13
13
 
14
- const {pki} = forge;
15
- const {filter, pick} = lodash;
14
+ const { pki } = forge;
15
+ const { filter, pick } = lodash;
16
16
 
17
17
  const log = debug("volt-client-grpc:volt-client-internal");
18
18
  const voltServices = [
19
- constants.serviceType.voltAPI,
20
- constants.serviceType.fileAPI,
21
- constants.serviceType.sqliteDatabaseAPI,
22
- constants.serviceType.sqliteServerAPI,
23
- constants.serviceType.ssiAPI,
24
- constants.serviceType.tunnelAPI,
25
- constants.serviceType.wireAPI,
19
+ constants.serviceType.voltAPI,
20
+ constants.serviceType.fileAPI,
21
+ constants.serviceType.sqliteDatabaseAPI,
22
+ constants.serviceType.sqliteServerAPI,
23
+ constants.serviceType.ssiAPI,
24
+ constants.serviceType.relayAPI,
25
+ constants.serviceType.wireAPI,
26
26
  ];
27
27
 
28
28
  function issueBind(bindRequest, ttl) {
29
- // eslint-disable-next-line no-use-before-define
30
- return unaryCall.call(this, "Bind", bindRequest).then((bindResponse) => {
31
- log("got binding request response %j", bindResponse);
32
- if (bindResponse.status && bindResponse.status.code) {
33
- log("error in bind response: %s", bindResponse.status.message);
34
- return Promise.reject(new Error(bindResponse.status.message));
35
- } else {
36
- switch (bindResponse.decision) {
37
- case "POLICY_DECISION_PERMIT":
38
- //
39
- // The request status is permit => cache the bind response info.
40
- //
41
-
42
- // This is the certificate assigned to us by the volt.
43
- this._crypto.cache.cert = bindResponse.cert;
44
-
45
- // This is the signing CA used by the volt (don't ov)
46
- this._crypto.cache.ca = bindResponse.chain;
47
-
48
- // Resource id is assigned by the volt.
49
- this._crypto.cache.client_id = bindResponse.identity_id;
50
- this._crypto.saveCache();
51
- break;
52
- case "POLICY_DECISION_DENY":
53
- log(">>>>>>>>>>>>>>> access request is DENIED <<<<<<<<<<<<<<<<<<<");
54
- break;
55
- case "POLICY_DECISION_PROMPT":
56
- case "POLICY_DECISION_PENDING":
57
- log("access pending approval - waiting...");
58
- break;
59
- default:
60
- log("ignoring unknown bind descision %s", bindResponse.status);
61
- break;
62
- }
63
- }
64
-
65
- return bindResponse.decision;
66
- });
29
+ // eslint-disable-next-line no-use-before-define
30
+ return unaryCall.call(this, "Bind", bindRequest).then((bindResponse) => {
31
+ log("got binding request response %j", bindResponse);
32
+ if (bindResponse.status?.code) {
33
+ log("error in bind response: %s", bindResponse.status.message);
34
+ return Promise.reject(new Error(bindResponse.status.message));
35
+ } else {
36
+ switch (bindResponse.decision) {
37
+ case "POLICY_DECISION_PERMIT": {
38
+ //
39
+ // The request status is permit => cache the bind response info.
40
+ //
41
+
42
+ // This is the certificate assigned to us by the volt.
43
+ this._credential.cache.cert = bindResponse.cert;
44
+
45
+ // This is the signing CA used by the volt (don't ov)
46
+ this._credential.cache.ca = bindResponse.chain;
47
+
48
+ // Resource id is assigned by the volt.
49
+ this._credential.cache.client_id = bindResponse.identity_id;
50
+ this._credential.saveCache();
51
+ break;
52
+ }
53
+ case "POLICY_DECISION_DENY": {
54
+ log(">>>>>>>>>>>>>>> access request is DENIED <<<<<<<<<<<<<<<<<<<");
55
+ break;
56
+ }
57
+ case "POLICY_DECISION_PROMPT":
58
+ case "POLICY_DECISION_PENDING": {
59
+ log("access pending approval - waiting...");
60
+ break;
61
+ }
62
+ default:
63
+ log("ignoring unknown bind descision %s", bindResponse.status);
64
+ break;
65
+ }
66
+ }
67
+
68
+ return bindResponse.decision;
69
+ });
67
70
  }
68
71
 
69
72
  function findDIDDocumentService(document, serviceType) {
70
- if (!document.service) {
71
- return [];
72
- }
73
+ if (!document.service) {
74
+ return [];
75
+ }
73
76
 
74
- const matches = filter(document.service, (svc) => svc.type === serviceType);
75
- return matches;
77
+ const matches = filter(document.service, (svc) => svc.type === serviceType);
78
+ return matches;
76
79
  }
77
80
 
78
81
  export async function bindInternal() {
79
- try {
80
- // Build grpc client info.
81
- if (this.isRemote) {
82
- const getJSON = bent("json");
83
- // @todo - currently Volt tunnel CA discovery is not secure.
84
- const protocol =
85
- this._config.tunnel_host?.startsWith("localhost:") || this._config.cloud_host?.startsWith("localhost:")
86
- ? "http"
87
- : "https";
88
- const tunnelURL = `${protocol}://${this._config.tunnel_host || this._config.cloud_host}/info`;
89
- log("attempting to retrieve tunnel information from %s", tunnelURL);
90
- const tunnelInfo = await getJSON(tunnelURL);
91
- if (!tunnelInfo.ca_pem) {
92
- throw new Error("Unable to fetch tunnel CA - cannot securely connect.");
93
- } else {
94
- log("Auto-fetched tunnel CA %s, remote address %s", tunnelInfo.ca_pem, tunnelInfo.local_address);
95
- this._crypto.cache.tunnel_ca_pem = tunnelInfo.ca_pem;
96
- this._crypto.cache.tunnel_address = tunnelInfo.local_address;
97
- }
98
- }
99
-
100
- if (!this._crypto.cache.ca) {
101
- this._crypto.cache.ca = this._options.ca_pem;
102
- }
103
-
104
- if (!this._crypto.cache.ca) {
105
- throw new Error("No certificate authority found in configuration for target Volt - check configuration");
106
- }
107
-
108
- const keyPair = this._crypto.getKey();
109
- const publicKeyPem = pki.publicKeyToPem(keyPair.publicKey);
110
-
111
- if (!this._crypto.cache.bindIp) {
112
- // Default the IP address if none is specified. This is used to set the SAN in the
113
- // certificate issued by the Volt.
114
- this._crypto.cache.bindIp = ip.address();
115
- }
116
-
117
- this._crypto.saveCache();
118
-
119
- // Form the request message.
120
- const bindRequest = {
121
- binding_name: this._config.client_name,
122
- public_key: publicKeyPem,
123
- host: this._crypto.cache.bindIp,
124
- x509_credential: [],
125
- };
126
-
127
- if (this._crypto.cache.cert) {
128
- bindRequest.x509_credential = [this._crypto.cache.cert + this._crypto.cache.ca];
129
- }
130
-
131
- if (this._options.challenge_code) {
132
- bindRequest.challenge = voltUtils.signBase64(keyPair.privateKey, this._options.challenge_code);
133
- } else {
134
- log("****no Volt challenge code available**** => not sending challenge signature");
135
- }
136
-
137
- // For remote connections, add our cloud-issued certificate as an additional credential.
138
- if (this._crypto.cache.tunnel_ca_pem && this._crypto.cache.cloud_cert) {
139
- bindRequest.x509_credential = bindRequest.x509_credential.concat(
140
- this._crypto.cache.cloud_cert + this._crypto.cache.tunnel_ca_pem
141
- );
142
- }
143
-
144
- log("sending %d x509 credentials", bindRequest.x509_credential.length);
145
- log("bind TTL is ", this._config.bindRequestTTL);
146
-
147
- // This will block while the request is pending.
148
- const pollInterval = 10000;
149
- let decision = "";
150
- do {
151
- if (decision) {
152
- // Wait a while before retrying.
153
- // eslint-disable-next-line no-await-in-loop
154
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
155
- }
156
- // eslint-disable-next-line no-await-in-loop
157
- decision = await issueBind.call(this, bindRequest, this._options.bindRequestTTL);
158
- log("binding decision: %s", decision);
159
- } while (decision === "POLICY_DECISION_PROMPT" || decision === "POLICY_DECISION_PENDING");
160
-
161
- return decision === "POLICY_DECISION_PERMIT";
162
- } catch (err) {
163
- log("failure binding to Volt [%s]", err.message);
164
- throw err;
165
- }
82
+ try {
83
+ // Check if we need to resolve a Relay volt.
84
+ if (
85
+ typeof this._voltConfig?.relay === "string" ||
86
+ this._voltConfig?.relay?.http_address
87
+ ) {
88
+ const relayURL =
89
+ this._voltConfig.relay?.http_address || this._voltConfig.relay;
90
+ log("attempting to retrieve Relay information from %s", relayURL);
91
+ this._voltConfig.relay = await fetchVoltConfig.call(
92
+ this,
93
+ `${relayURL}/discovery`,
94
+ );
95
+ if (this._voltConfig.relay.ca_pem) {
96
+ log(
97
+ "Auto-fetched Relay CA %s, remote address %s",
98
+ this._voltConfig.relay.ca_pem,
99
+ this._voltConfig.relay.address,
100
+ );
101
+ } else {
102
+ throw new Error("Unable to fetch Relay CA - cannot securely connect.");
103
+ }
104
+ }
105
+
106
+ if (!this._credential.cache.ca) {
107
+ this._credential.cache.ca = this._voltConfig.ca_pem;
108
+ }
109
+
110
+ if (!this._credential.cache.ca) {
111
+ throw new Error(
112
+ "No certificate authority found in configuration for target Volt - check configuration",
113
+ );
114
+ }
115
+
116
+ const keyPair = this._credential.getKey();
117
+ const publicKeyPem = pki.publicKeyToPem(keyPair.publicKey);
118
+
119
+ if (!this._credential.cache.bindIp) {
120
+ // Default the IP address if none is specified. This is used to set the SAN in the
121
+ // certificate issued by the Volt.
122
+ this._credential.cache.bindIp = ip.address();
123
+ }
124
+
125
+ this._credential.saveCache();
126
+
127
+ // Form the request message.
128
+ const bindRequest = {
129
+ binding_name: this._config.client_name,
130
+ public_key: publicKeyPem,
131
+ host: this._credential.cache.bindIp,
132
+ x509_credential: [],
133
+ };
134
+
135
+ if (this._credential.cache.cert) {
136
+ bindRequest.x509_credential = [
137
+ this._credential.cache.cert + this._credential.cache.ca,
138
+ ];
139
+ }
140
+
141
+ if (this._voltConfig.challenge_code) {
142
+ bindRequest.challenge = voltUtils.signBase64(
143
+ keyPair.privateKey,
144
+ this._voltConfig.challenge_code,
145
+ );
146
+ } else {
147
+ log(
148
+ "****no Volt challenge code available**** => not sending challenge signature",
149
+ );
150
+ }
151
+
152
+ // For remote connections, add our cloud-issued certificate as an additional credential.
153
+ if (this._config?.relay?.ca_pem && this._credential.cache.cloud_cert) {
154
+ bindRequest.x509_credential = bindRequest.x509_credential.concat(
155
+ this._credential.cache.cloud_cert + this._config.relay.ca_pem,
156
+ );
157
+ }
158
+
159
+ log("sending %d x509 credentials", bindRequest.x509_credential.length);
160
+ log("bind TTL is ", this._config.bindRequestTTL);
161
+
162
+ // This will block while the request is pending.
163
+ const pollInterval = 10000;
164
+ let decision = "";
165
+ do {
166
+ if (decision) {
167
+ // Wait a while before retrying.
168
+ // eslint-disable-next-line no-await-in-loop
169
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
170
+ }
171
+ // eslint-disable-next-line no-await-in-loop
172
+ decision = await issueBind.call(
173
+ this,
174
+ bindRequest,
175
+ this._voltConfig.bindRequestTTL,
176
+ );
177
+ log("binding decision: %s", decision);
178
+ } while (
179
+ decision === "POLICY_DECISION_PROMPT" ||
180
+ decision === "POLICY_DECISION_PENDING"
181
+ );
182
+
183
+ return decision === "POLICY_DECISION_PERMIT";
184
+ } catch (err) {
185
+ log("failure binding to Volt [%s]", err.message);
186
+ throw err;
187
+ }
166
188
  }
167
189
 
168
190
  export function connectInternal() {
169
- try {
170
- if (this._voltConnection) {
171
- log("connectInternal - Volt connection already exists");
172
- return Promise.resolve();
173
- }
174
-
175
- const onDisconnected = () => {
176
- this._connected = false;
177
- this._session = null;
178
-
179
- if (this._cachedClient) {
180
- this._grpc.closeClient(this._cachedClient);
181
- this._cachedClient = null;
182
- }
183
-
184
- if (this._cachedRemoteClient) {
185
- this._grpc.closeClient(this._cachedRemoteClient);
186
- this._cachedRemoteClient = null;
187
- }
188
- };
189
-
190
- this._voltConnection = new VoltConnection(this, this._grpc, this._options);
191
-
192
- this._voltConnection.on("connected", (session) => {
193
- this._session = session;
194
- this._connected = !!session;
195
- if (!this._connected) {
196
- onDisconnected();
197
- }
198
- this.emit("connected", !!session);
199
- });
200
-
201
- this._voltConnection.on("error", (err) => {
202
- // Should auto-reconnect.
203
- log("Volt connection error [%s]", err.message);
204
- if (this._connected) {
205
- onDisconnected();
206
- this.emit("connected", false);
207
- }
208
- });
209
-
210
- this._voltConnection.on("evt", (evt) => {
211
- this.emit("evt", evt);
212
- });
213
-
214
- return this._voltConnection.connect();
215
- } catch (err) {
216
- log("connect - error [%s]", err.message);
217
- throw err;
218
- }
191
+ try {
192
+ if (this._voltConnection) {
193
+ log("connectInternal - Volt connection already exists");
194
+ return Promise.resolve();
195
+ }
196
+
197
+ const onDisconnected = () => {
198
+ this._connected = false;
199
+ this._session = null;
200
+
201
+ if (this._cachedClient) {
202
+ this._grpc.closeClient(this._cachedClient);
203
+ this._cachedClient = null;
204
+ }
205
+
206
+ if (this._cachedRemoteClient) {
207
+ this._grpc.closeClient(this._cachedRemoteClient);
208
+ this._cachedRemoteClient = null;
209
+ }
210
+ };
211
+
212
+ this._voltConnection = new VoltConnection(this, this._grpc);
213
+
214
+ this._voltConnection.on("connected", (session) => {
215
+ this._session = session;
216
+ this._connected = !!session;
217
+ if (!this._connected) {
218
+ onDisconnected();
219
+ }
220
+ this.emit("connected", !!session);
221
+ });
222
+
223
+ this._voltConnection.on("error", (err) => {
224
+ // Should auto-reconnect.
225
+ log("Volt connection error [%s]", err.message);
226
+ if (this._connected) {
227
+ onDisconnected();
228
+ this.emit("connected", false);
229
+ }
230
+ });
231
+
232
+ this._voltConnection.on("evt", (evt) => {
233
+ this.emit("evt", evt);
234
+ });
235
+
236
+ return this._voltConnection.connect();
237
+ } catch (err) {
238
+ log("connect - error [%s]", err.message);
239
+ throw err;
240
+ }
219
241
  }
220
242
 
221
243
  export function getVoltAPIClientInternal() {
222
- if (!this._cachedClient) {
223
- const serviceAddress = this.isRemote ? this._crypto.cache.tunnel_address : this._options.local_address;
224
- log("creating cached VoltAPI service client on %s", serviceAddress);
225
- let serviceDescriptors = {};
226
- voltServices.forEach((pkg) => {
227
- const packageDescriptors = getServiceDescriptors(this._grpc, pkg);
228
- serviceDescriptors = {...serviceDescriptors, ...packageDescriptors};
229
- });
230
-
231
- this._cachedClient = createGrpcClient(
232
- this._grpc,
233
- serviceDescriptors,
234
- serviceAddress,
235
- this._crypto.cache,
236
- this.isRemote && !this.isVoltTunnel,
237
- this._config.cloud_host ? this._options.id : "",
238
- this._config.cloud_host ? this._options.id : ""
239
- );
240
- }
241
-
242
- return this._cachedClient;
244
+ if (!this._cachedClient) {
245
+ const serviceAddress = this.isRemote
246
+ ? this._config.relay.address
247
+ : this._voltConfig.address;
248
+ log("creating cached VoltAPI service client on %s", serviceAddress);
249
+ let serviceDescriptors = {};
250
+ voltServices.forEach((pkg) => {
251
+ const packageDescriptors = getServiceDescriptors(this._grpc, pkg);
252
+ serviceDescriptors = { ...serviceDescriptors, ...packageDescriptors };
253
+ });
254
+
255
+ this._cachedClient = createGrpcClient(
256
+ this._grpc,
257
+ serviceDescriptors,
258
+ serviceAddress,
259
+ this._credential,
260
+ this.isRemote && !this.isVoltRelay,
261
+ this._config?.relay?.cloud ? this._voltConfig.id : "",
262
+ this._config?.relay?.cloud ? this._voltConfig.id : "",
263
+ );
264
+ }
265
+
266
+ return this._cachedClient;
243
267
  }
244
268
 
245
269
  export function unaryCall(method, request) {
246
- const grpcClient = this.getVoltAPIClient();
270
+ return new Promise((resolve, reject) => {
271
+ const grpcClient = this.getVoltAPIClient();
247
272
 
248
- const call = new GRPCCall(this, method, "METHOD_TYPE_UNARY");
249
- call.start(grpcClient, request);
250
- return call.wait();
273
+ const call = new GRPCCall(this, method, "METHOD_TYPE_UNARY");
274
+
275
+ let response = null;
276
+
277
+ call.on("data", (payload) => {
278
+ // Cache the response and wait for `end`.
279
+ response = payload;
280
+ });
281
+
282
+ call.on("error", reject);
283
+
284
+ call.on("end", () => {
285
+ if (!response) {
286
+ return reject(new Error("no response received"));
287
+ }
288
+
289
+ // Convert non-OK status to a JS error.
290
+ if (response.status?.message) {
291
+ reject(new Error(response.status.message));
292
+ } else {
293
+ resolve(response);
294
+ }
295
+ });
296
+
297
+ call.start(grpcClient, request);
298
+ });
299
+ }
300
+
301
+ export async function fetchVoltConfig(discovery_url) {
302
+ try {
303
+ const getJSON = bent("json");
304
+ const fullVoltConfig = await getJSON(discovery_url);
305
+
306
+ if (!fullVoltConfig || typeof fullVoltConfig !== "object") {
307
+ throw new Error(`invalid config resolved from: ${discovery_url}`);
308
+ }
309
+
310
+ const voltConfig = pick(
311
+ fullVoltConfig,
312
+ "id",
313
+ "display_name",
314
+ "public_key",
315
+ "fingerprint",
316
+ "address",
317
+ "ca_pem",
318
+ "challenge_code",
319
+ "cloud",
320
+ "relay",
321
+ );
322
+
323
+ return voltConfig;
324
+ } catch (err) {
325
+ throw new Error(
326
+ `Failure loading config from ${discovery_url}: ${err.message}`,
327
+ );
328
+ }
251
329
  }
252
330
 
253
- export async function fetchVoltConfig(volt_did) {
254
- const didResolution = voltUtils.getDIDResolutionURL(volt_did);
255
- if (!didResolution) {
256
- throw new Error(`Invalid Volt DID: ${volt_did}`);
257
- }
258
-
259
- const getJSON = bent("json");
260
- const didDocument = await getJSON(didResolution);
261
- const voltConfigServices = findDIDDocumentService(didDocument, constants.didServiceType.voltConfig);
262
- if (voltConfigServices.length !== 1) {
263
- log(
264
- "Unexpected number of Volt configuration endpoints found in DID document for %s, services found: %d",
265
- volt_did,
266
- voltConfigServices.length
267
- );
268
- }
269
- const serviceEndpoint = voltConfigServices[0].serviceEndpoint;
270
- const resolvedConfig = await getJSON(serviceEndpoint);
271
-
272
- const voltConfig = pick(
273
- resolvedConfig,
274
- "id",
275
- "display_name",
276
- "public_key",
277
- "fingerprint",
278
- "local_address",
279
- "ca_pem",
280
- "challenge_code"
281
- );
282
-
283
- return {
284
- volt: voltConfig,
285
- tunnel_ca_pem: resolvedConfig.tunnel_ca_pem,
286
- tunnel_address: resolvedConfig.tunnel_address,
287
- cloud_host: resolvedConfig.tunnel_address.split(":")[0],
288
- };
331
+ export async function fetchVoltConfigFromDID(volt_did) {
332
+ try {
333
+ const didResolution = voltUtils.getDIDResolutionURL(volt_did);
334
+ if (!didResolution) {
335
+ throw new Error(`Invalid Volt DID: ${volt_did}`);
336
+ }
337
+
338
+ const getJSON = bent("json");
339
+ const didDocument = await getJSON(didResolution);
340
+ const voltConfigServices = findDIDDocumentService(
341
+ didDocument,
342
+ constants.didServiceType.voltConfig,
343
+ );
344
+ if (voltConfigServices.length !== 1) {
345
+ log(
346
+ "Unexpected number of Volt configuration endpoints found in DID document for %s, services found: %d",
347
+ volt_did,
348
+ voltConfigServices.length,
349
+ );
350
+ }
351
+
352
+ const serviceEndpoint = voltConfigServices[0].serviceEndpoint;
353
+ return await fetchVoltConfig.call(this, serviceEndpoint);
354
+ } catch (err) {
355
+ throw new Error(
356
+ `Failure fetching Volt config from DID document ${volt_did}: ${err.message}`,
357
+ );
358
+ }
289
359
  }