@opensearch-project/opensearch 2.0.0 → 2.2.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 (92) hide show
  1. package/.eslintrc.json +13 -5
  2. package/ADMINS.md +13 -38
  3. package/CHANGELOG.md +54 -0
  4. package/COMPATIBILITY.md +4 -1
  5. package/MAINTAINERS.md +11 -73
  6. package/Makefile +2 -12
  7. package/README.md +4 -107
  8. package/RELEASING.md +7 -1
  9. package/USER_GUIDE.md +248 -0
  10. package/api/api/bulk.js +24 -2
  11. package/api/api/cat.js +320 -2
  12. package/api/api/clear_scroll.js +15 -2
  13. package/api/api/cluster.js +238 -2
  14. package/api/api/count.js +29 -2
  15. package/api/api/create.js +27 -2
  16. package/api/api/create_pit.js +88 -0
  17. package/api/api/dangling_indices.js +46 -2
  18. package/api/api/delete.js +24 -2
  19. package/api/api/delete_all_pits.js +53 -0
  20. package/api/api/delete_by_query.js +49 -2
  21. package/api/api/delete_by_query_rethrottle.js +15 -2
  22. package/api/api/delete_pit.js +61 -0
  23. package/api/api/delete_script.js +15 -2
  24. package/api/api/exists.js +26 -2
  25. package/api/api/exists_source.js +26 -2
  26. package/api/api/explain.js +28 -2
  27. package/api/api/features.js +25 -2
  28. package/api/api/field_caps.js +20 -2
  29. package/api/api/get.js +26 -2
  30. package/api/api/get_all_pits.js +53 -0
  31. package/api/api/get_script.js +17 -2
  32. package/api/api/get_script_context.js +12 -2
  33. package/api/api/get_script_languages.js +12 -2
  34. package/api/api/get_source.js +26 -2
  35. package/api/api/index.js +30 -2
  36. package/api/api/indices.js +816 -2
  37. package/api/api/info.js +12 -2
  38. package/api/api/ingest.js +90 -2
  39. package/api/api/mget.js +25 -2
  40. package/api/api/msearch.js +23 -2
  41. package/api/api/msearch_template.js +20 -2
  42. package/api/api/mtermvectors.js +1 -2
  43. package/api/api/nodes.js +92 -2
  44. package/api/api/ping.js +12 -2
  45. package/api/api/put_script.js +18 -2
  46. package/api/api/rank_eval.js +20 -2
  47. package/api/api/reindex.js +23 -2
  48. package/api/api/reindex_rethrottle.js +15 -2
  49. package/api/api/render_search_template.js +15 -2
  50. package/api/api/scripts_painless_execute.js +14 -2
  51. package/api/api/scroll.js +18 -2
  52. package/api/api/search.js +61 -2
  53. package/api/api/search_shards.js +20 -2
  54. package/api/api/search_template.js +28 -2
  55. package/api/api/shutdown.js +4 -2
  56. package/api/api/snapshot.js +211 -2
  57. package/api/api/tasks.js +57 -2
  58. package/api/api/terms_enum.js +2 -2
  59. package/api/api/termvectors.js +27 -2
  60. package/api/api/update.js +29 -2
  61. package/api/api/update_by_query.js +51 -2
  62. package/api/api/update_by_query_rethrottle.js +15 -2
  63. package/api/index.js +29 -2
  64. package/api/new.d.ts +65 -2
  65. package/api/opensearch_dashboards.d.ts +5 -2
  66. package/api/requestParams.d.ts +17 -2
  67. package/api/types.d.ts +48 -2
  68. package/api/utils.js +1 -2
  69. package/index.d.ts +605 -120
  70. package/index.js +2 -3
  71. package/index.mjs +1 -2
  72. package/jenkins/release.JenkinsFile +11 -0
  73. package/lib/Connection.d.ts +1 -2
  74. package/lib/Connection.js +5 -4
  75. package/lib/Helpers.d.ts +5 -4
  76. package/lib/Helpers.js +13 -17
  77. package/lib/Serializer.d.ts +1 -2
  78. package/lib/Serializer.js +2 -3
  79. package/lib/Transport.d.ts +10 -4
  80. package/lib/Transport.js +34 -7
  81. package/lib/aws/AwsSigv4Signer.js +176 -0
  82. package/lib/aws/errors.js +24 -0
  83. package/lib/aws/index.d.ts +39 -0
  84. package/lib/aws/index.js +19 -0
  85. package/lib/errors.d.ts +1 -2
  86. package/lib/errors.js +1 -2
  87. package/lib/pool/BaseConnectionPool.js +1 -2
  88. package/lib/pool/CloudConnectionPool.js +1 -2
  89. package/lib/pool/ConnectionPool.js +1 -2
  90. package/lib/pool/index.d.ts +1 -2
  91. package/lib/pool/index.js +1 -2
  92. package/package.json +36 -18
package/index.js CHANGED
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
@@ -286,7 +285,7 @@ class Client extends OpenSearchAPI {
286
285
 
287
286
  close(callback) {
288
287
  if (callback == null) {
289
- return new Promise((resolve, reject) => {
288
+ return new Promise((resolve) => {
290
289
  this.close(resolve);
291
290
  });
292
291
  }
package/index.mjs CHANGED
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
@@ -0,0 +1,11 @@
1
+ lib = library(identifier: 'jenkins@1.1.1', retriever: modernSCM([
2
+ $class: 'GitSCMSource',
3
+ remote: 'https://github.com/opensearch-project/opensearch-build-libraries.git',
4
+ ]))
5
+
6
+ standardReleasePipelineWithGenericTrigger(
7
+ tokenIdCredential: 'jenkins-opensearch-js-generic-webhook-token',
8
+ causeString: 'A tag was cut on opensearch-project/opensearch-js repository causing this workflow to run',
9
+ publishRelease: true) {
10
+ publishToNpm(repository: 'https://github.com/opensearch-project/opensearch-js', tag: "$tag")
11
+ }
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
package/lib/Connection.js CHANGED
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
@@ -218,7 +217,7 @@ class Connection {
218
217
  origin: url.origin,
219
218
  // https://github.com/elastic/elasticsearch-js/issues/843
220
219
  port: url.port !== '' ? url.port : undefined,
221
- headers: this.headers,
220
+ headers: Object.assign({}, this.headers),
222
221
  agent: this.agent,
223
222
  };
224
223
 
@@ -249,7 +248,8 @@ class Connection {
249
248
  // We want to hide `auth`, `agent` and `ssl` since they made
250
249
  // the logs very hard to read. The user can still
251
250
  // access them with `instance.agent` and `instance.ssl`.
252
- [inspect.custom](depth, options) {
251
+ [inspect.custom]() {
252
+ // eslint-disable-next-line no-unused-vars
253
253
  const { authorization, ...headers } = this.headers;
254
254
 
255
255
  return {
@@ -265,6 +265,7 @@ class Connection {
265
265
  }
266
266
 
267
267
  toJSON() {
268
+ // eslint-disable-next-line no-unused-vars
268
269
  const { authorization, ...headers } = this.headers;
269
270
 
270
271
  return {
package/lib/Helpers.d.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
@@ -82,14 +81,14 @@ export interface BulkStats {
82
81
  aborted: boolean;
83
82
  }
84
83
 
85
- interface IndexAction {
84
+ interface IndexActionOperation {
86
85
  index: {
87
86
  _index: string;
88
87
  [key: string]: any;
89
88
  };
90
89
  }
91
90
 
92
- interface CreateAction {
91
+ interface CreateActionOperation {
93
92
  create: {
94
93
  _index: string;
95
94
  [key: string]: any;
@@ -110,6 +109,8 @@ interface DeleteAction {
110
109
  };
111
110
  }
112
111
 
112
+ type CreateAction = CreateActionOperation | [CreateActionOperation, unknown];
113
+ type IndexAction = IndexActionOperation | [IndexActionOperation, unknown];
113
114
  type UpdateAction = [UpdateActionOperation, Record<string, any>];
114
115
  type Action = IndexAction | CreateAction | UpdateAction | DeleteAction;
115
116
  type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
package/lib/Helpers.js CHANGED
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
@@ -97,7 +96,6 @@ class Helpers {
97
96
  }
98
97
  params.scroll = params.scroll || '1m';
99
98
  appendFilterPath('_scroll_id', params, false);
100
- const { method, body, index, ...querystring } = params;
101
99
 
102
100
  let response = null;
103
101
  for (let i = 0; i <= maxRetries; i++) {
@@ -132,9 +130,8 @@ class Helpers {
132
130
  for (let i = 0; i <= maxRetries; i++) {
133
131
  response = await this[kClient].scroll(
134
132
  {
135
- scroll: querystring.scroll,
136
- rest_total_hits_as_int:
137
- querystring.rest_total_hits_as_int || querystring.restTotalHitsAsInt,
133
+ scroll: params.scroll,
134
+ rest_total_hits_as_int: params.rest_total_hits_as_int || params.restTotalHitsAsInt,
138
135
  body: { scroll_id },
139
136
  },
140
137
  options
@@ -199,7 +196,7 @@ class Helpers {
199
196
  let timeoutRef = null;
200
197
  const operationsStream = new Readable({
201
198
  objectMode: true,
202
- read(size) {},
199
+ read() {},
203
200
  });
204
201
 
205
202
  const p = iterate();
@@ -332,7 +329,7 @@ class Helpers {
332
329
  return { semaphore, finish };
333
330
 
334
331
  function finish() {
335
- return new Promise((resolve, reject) => {
332
+ return new Promise((resolve) => {
336
333
  if (running === 0) {
337
334
  resolve();
338
335
  } else {
@@ -346,7 +343,7 @@ class Helpers {
346
343
  running += 1;
347
344
  return pImmediate(send);
348
345
  } else {
349
- return new Promise((resolve, reject) => {
346
+ return new Promise((resolve) => {
350
347
  resolveSemaphore = resolve;
351
348
  });
352
349
  }
@@ -532,21 +529,20 @@ class Helpers {
532
529
  for await (const chunk of datasource) {
533
530
  if (shouldAbort === true) break;
534
531
  timeoutRef.refresh();
535
- const action = onDocument(chunk);
536
- const operation = Array.isArray(action)
537
- ? Object.keys(action[0])[0]
538
- : Object.keys(action)[0];
532
+ const result = onDocument(chunk);
533
+ const [action, payload] = Array.isArray(result) ? result : [result, chunk];
534
+ const operation = Object.keys(action)[0];
539
535
  if (operation === 'index' || operation === 'create') {
540
536
  actionBody = serializer.serialize(action);
541
- payloadBody = typeof chunk === 'string' ? chunk : serializer.serialize(chunk);
537
+ payloadBody = typeof payload === 'string' ? payload : serializer.serialize(payload);
542
538
  chunkBytes += Buffer.byteLength(actionBody) + Buffer.byteLength(payloadBody);
543
539
  bulkBody.push(actionBody, payloadBody);
544
540
  } else if (operation === 'update') {
545
- actionBody = serializer.serialize(action[0]);
541
+ actionBody = serializer.serialize(action);
546
542
  payloadBody =
547
543
  typeof chunk === 'string'
548
544
  ? `{"doc":${chunk}}`
549
- : serializer.serialize({ doc: chunk, ...action[1] });
545
+ : serializer.serialize({ doc: chunk, ...payload });
550
546
  chunkBytes += Buffer.byteLength(actionBody) + Buffer.byteLength(payloadBody);
551
547
  bulkBody.push(actionBody, payloadBody);
552
548
  } else if (operation === 'delete') {
@@ -649,7 +645,7 @@ class Helpers {
649
645
  running += 1;
650
646
  return pImmediate(send);
651
647
  } else {
652
- return new Promise((resolve, reject) => {
648
+ return new Promise((resolve) => {
653
649
  resolveSemaphore = resolve;
654
650
  });
655
651
  }
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
package/lib/Serializer.js CHANGED
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
@@ -91,7 +90,7 @@ class Serializer {
91
90
  const keys = Object.keys(object);
92
91
  for (let i = 0, len = keys.length; i < len; i++) {
93
92
  const key = keys[i];
94
- // OpenSearch will complain for keys without a value
93
+ // OpenSearch will complain about keys without a value
95
94
  if (object[key] === undefined) {
96
95
  delete object[key];
97
96
  } else if (Array.isArray(object[key]) === true) {
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
@@ -29,10 +28,10 @@
29
28
  */
30
29
 
31
30
  import { Readable as ReadableStream } from 'stream';
32
- import { ConnectionPool, CloudConnectionPool } from './pool';
33
31
  import Connection from './Connection';
34
- import Serializer from './Serializer';
35
32
  import * as errors from './errors';
33
+ import { CloudConnectionPool, ConnectionPool } from './pool';
34
+ import Serializer from './Serializer';
36
35
 
37
36
  export type ApiError =
38
37
  | errors.ConfigurationError
@@ -59,6 +58,11 @@ export interface generateRequestIdFn {
59
58
  (params: TransportRequestParams, options: TransportRequestOptions): any;
60
59
  }
61
60
 
61
+ export interface MemoryCircuitBreakerOptions {
62
+ enabled: boolean;
63
+ maxPercentage: number;
64
+ }
65
+
62
66
  interface TransportOptions {
63
67
  emit: (event: string | symbol, ...args: any[]) => boolean;
64
68
  connectionPool: ConnectionPool | CloudConnectionPool;
@@ -77,6 +81,7 @@ interface TransportOptions {
77
81
  generateRequestId?: generateRequestIdFn;
78
82
  name?: string;
79
83
  opaqueIdPrefix?: string;
84
+ memoryCircuitBreaker?: MemoryCircuitBreakerOptions;
80
85
  }
81
86
 
82
87
  export interface RequestEvent<TResponse = Record<string, any>, TContext = Context> {
@@ -172,6 +177,7 @@ export default class Transport {
172
177
  sniffInterval: number;
173
178
  sniffOnConnectionFault: boolean;
174
179
  opaqueIdPrefix: string | null;
180
+ memoryCircuitBreaker: MemoryCircuitBreakerOptions | undefined;
175
181
  sniffEndpoint: string;
176
182
  _sniffEnabled: boolean;
177
183
  _nextSniff: number;
package/lib/Transport.js CHANGED
@@ -1,12 +1,11 @@
1
1
  /*
2
+ * Copyright OpenSearch Contributors
2
3
  * SPDX-License-Identifier: Apache-2.0
3
4
  *
4
5
  * The OpenSearch Contributors require contributions made to
5
6
  * this file be licensed under the Apache-2.0 license or a
6
7
  * compatible open source license.
7
8
  *
8
- * Modifications Copyright OpenSearch Contributors. See
9
- * GitHub history for details.
10
9
  */
11
10
 
12
11
  /*
@@ -57,6 +56,7 @@ const HEAP_SIZE_LIMIT = require('v8').getHeapStatistics().heap_size_limit;
57
56
  const kCompatibleCheck = Symbol('compatible check');
58
57
  const kApiVersioning = Symbol('api versioning');
59
58
 
59
+ /** Default Transport Layer */
60
60
  class Transport {
61
61
  constructor(opts) {
62
62
  if (typeof opts.compression === 'string' && opts.compression !== 'gzip') {
@@ -111,6 +111,27 @@ class Transport {
111
111
  }
112
112
  }
113
113
 
114
+ /**
115
+ * @param {Object} params
116
+ * @param {string} params.method - HTTP Method (e.g. HEAD, GET, POST...)
117
+ * @param {string} params.path - Relative URL path
118
+ * @param {Object | string} [params.body] - Body of a standard request.
119
+ * @param {Object[] | string} [params.bulkBody] - Body of a bulk request.
120
+ * @param {Object[] | string} [params.querystring] - Querystring params.
121
+ *
122
+ * @param {Object} options
123
+ * @param {number} [options.id] - Request ID
124
+ * @param {Object} [options.context] - Object used for observability
125
+ * @param {number} [options.maxRetries] - Max number of retries
126
+ * @param {false | 'gzip'} [options.compression] - Request body compression, if any
127
+ * @param {boolean} [options.asStream] - Whether to emit the response as stream
128
+ * @param {number[]} [options.ignore] - Response's Error Status Codes to ignore
129
+ * @param {Object} [options.headers] - Request headers
130
+ * @param {Object | string} [options.querystring] - Request's query string
131
+ * @param {number} [options.requestTimeout] - Max request timeout in milliseconds
132
+ *
133
+ * @param {function} callback - Callback that handles errors and response
134
+ */
114
135
  request(params, options, callback) {
115
136
  options = options || {};
116
137
  if (typeof options === 'function') {
@@ -182,10 +203,14 @@ class Transport {
182
203
  let request = { abort: noop };
183
204
  const transportReturn = {
184
205
  then(onFulfilled, onRejected) {
185
- return p.then(onFulfilled, onRejected);
206
+ if (p != null) {
207
+ return p.then(onFulfilled, onRejected);
208
+ }
186
209
  },
187
210
  catch(onRejected) {
188
- return p.catch(onRejected);
211
+ if (p != null) {
212
+ return p.catch(onRejected);
213
+ }
189
214
  },
190
215
  abort() {
191
216
  meta.aborted = true;
@@ -194,7 +219,9 @@ class Transport {
194
219
  return this;
195
220
  },
196
221
  finally(onFinally) {
197
- return p.finally(onFinally);
222
+ if (p != null) {
223
+ return p.finally(onFinally);
224
+ }
198
225
  },
199
226
  };
200
227
 
@@ -381,7 +408,7 @@ class Transport {
381
408
  // if the statusCode is 502/3/4 we should run our retry strategy
382
409
  // and mark the connection as dead
383
410
  this.connectionPool.markDead(meta.connection);
384
- // retry logic (we shoukd not retry on "429 - Too Many Requests")
411
+ // retry logic (we should not retry on "429 - Too Many Requests")
385
412
  if (meta.attempts < maxRetries && result.statusCode !== 429) {
386
413
  meta.attempts++;
387
414
  debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params);
@@ -676,7 +703,7 @@ function randomSelector(connections) {
676
703
  function generateRequestId() {
677
704
  const maxInt = 2147483647;
678
705
  let nextReqId = 0;
679
- return function genReqId(params, options) {
706
+ return function genReqId() {
680
707
  return (nextReqId = (nextReqId + 1) & maxInt);
681
708
  };
682
709
  }
@@ -0,0 +1,176 @@
1
+ /*
2
+ * Copyright OpenSearch Contributors
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ *
5
+ * The OpenSearch Contributors require contributions made to
6
+ * this file be licensed under the Apache-2.0 license or a
7
+ * compatible open source license.
8
+ *
9
+ */
10
+
11
+ 'use strict';
12
+ const Connection = require('../Connection');
13
+ const Transport = require('../Transport');
14
+ const aws4 = require('aws4');
15
+ const AwsSigv4SignerError = require('./errors');
16
+ const crypto = require('crypto');
17
+
18
+ const getAwsSDKCredentialsProvider = async () => {
19
+ // First try V3
20
+ try {
21
+ const awsV3 = await import('@aws-sdk/credential-provider-node');
22
+ if (typeof awsV3.defaultProvider === 'function') {
23
+ return awsV3.defaultProvider();
24
+ }
25
+ } catch (err) {
26
+ // Ignore
27
+ }
28
+ try {
29
+ const awsV2 = await import('aws-sdk');
30
+ if (awsV2.default && typeof awsV2.default.config.getCredentials === 'function') {
31
+ return () =>
32
+ new Promise((resolve, reject) => {
33
+ awsV2.default.config.getCredentials((err, credentials) => {
34
+ if (err) {
35
+ reject(err);
36
+ } else {
37
+ resolve(credentials);
38
+ }
39
+ });
40
+ });
41
+ }
42
+ } catch (err) {
43
+ // Ignore
44
+ }
45
+
46
+ throw new AwsSigv4SignerError(
47
+ 'Unable to find a valid AWS SDK, please provide a valid getCredentials function to AwsSigv4Signer options.'
48
+ );
49
+ };
50
+
51
+ const awsDefaultCredentialsProvider = () =>
52
+ new Promise((resolve, reject) => {
53
+ getAwsSDKCredentialsProvider()
54
+ .then((provider) => {
55
+ provider().then(resolve).catch(reject);
56
+ })
57
+ .catch((err) => {
58
+ reject(err);
59
+ });
60
+ });
61
+
62
+ function AwsSigv4Signer(opts = {}) {
63
+ const credentialsState = {
64
+ credentials: null,
65
+ };
66
+ if (!opts.region) {
67
+ throw new AwsSigv4SignerError('Region cannot be empty');
68
+ }
69
+ if (!opts.service) {
70
+ opts.service = 'es';
71
+ }
72
+ if (typeof opts.getCredentials !== 'function') {
73
+ opts.getCredentials = awsDefaultCredentialsProvider;
74
+ }
75
+
76
+ function buildSignedRequestObject(request = {}) {
77
+ request.service = opts.service;
78
+ request.region = opts.region;
79
+ request.headers = request.headers || {};
80
+ request.headers['host'] = request.hostname;
81
+ const signed = aws4.sign(request, credentialsState.credentials);
82
+ signed.headers['x-amz-content-sha256'] = crypto
83
+ .createHash('sha256')
84
+ .update(request.body || '', 'utf8')
85
+ .digest('hex');
86
+ return signed;
87
+ }
88
+
89
+ class AwsSigv4SignerConnection extends Connection {
90
+ buildRequestObject(params) {
91
+ const request = super.buildRequestObject(params);
92
+ return buildSignedRequestObject(request);
93
+ }
94
+ }
95
+
96
+ class AwsSigv4SignerTransport extends Transport {
97
+ request(params, options = {}, callback = undefined) {
98
+ // options is optional so if options is a function, it's the callback.
99
+ if (typeof options === 'function') {
100
+ callback = options;
101
+ options = {};
102
+ }
103
+
104
+ const currentCredentials = credentialsState.credentials;
105
+ let expired = false;
106
+ if (!currentCredentials) {
107
+ // Credentials haven't been acquired yet.
108
+ expired = true;
109
+ }
110
+ // AWS SDK V2, needsRefresh should be available.
111
+ else if (typeof currentCredentials.needsRefresh === 'function') {
112
+ expired = currentCredentials.needsRefresh();
113
+ }
114
+ // AWS SDK V2, alternative to needsRefresh.
115
+ else if (currentCredentials.expired === true) {
116
+ expired = true;
117
+ }
118
+ // AWS SDK V2, alternative to needsRefresh and expired.
119
+ else if (currentCredentials.expireTime && currentCredentials.expireTime < new Date()) {
120
+ expired = true;
121
+ }
122
+ // AWS SDK V3, Credentials.expiration is a Date object
123
+ else if (currentCredentials.expiration && currentCredentials.expiration < new Date()) {
124
+ expired = true;
125
+ }
126
+
127
+ if (!expired) {
128
+ if (typeof callback === 'undefined') {
129
+ return super.request(params, options);
130
+ }
131
+ super.request(params, options, callback);
132
+ return;
133
+ }
134
+
135
+ // In AWS SDK V2 Credentials.refreshPromise should be available.
136
+ if (currentCredentials && typeof currentCredentials.refreshPromise === 'function') {
137
+ if (typeof callback === 'undefined') {
138
+ return currentCredentials.refreshPromise().then(() => {
139
+ return super.request(params, options);
140
+ });
141
+ } else {
142
+ currentCredentials
143
+ .refreshPromise()
144
+ .then(() => {
145
+ super.request(params, options, callback);
146
+ })
147
+ .catch(callback);
148
+ return;
149
+ }
150
+ }
151
+
152
+ // For AWS SDK V3 or when the client has not acquired credentials yet.
153
+ if (typeof callback === 'undefined') {
154
+ return opts.getCredentials().then((credentials) => {
155
+ credentialsState.credentials = credentials;
156
+ return super.request(params, options);
157
+ });
158
+ } else {
159
+ opts
160
+ .getCredentials()
161
+ .then((credentials) => {
162
+ credentialsState.credentials = credentials;
163
+ super.request(params, options, callback);
164
+ })
165
+ .catch(callback);
166
+ }
167
+ }
168
+ }
169
+
170
+ return {
171
+ Transport: AwsSigv4SignerTransport,
172
+ Connection: AwsSigv4SignerConnection,
173
+ buildSignedRequestObject,
174
+ };
175
+ }
176
+ module.exports = AwsSigv4Signer;
@@ -0,0 +1,24 @@
1
+ /*
2
+ * Copyright OpenSearch Contributors
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ *
5
+ * The OpenSearch Contributors require contributions made to
6
+ * this file be licensed under the Apache-2.0 license or a
7
+ * compatible open source license.
8
+ *
9
+ */
10
+
11
+ 'use strict';
12
+ const { OpenSearchClientError } = require('../errors');
13
+
14
+ class AwsSigv4SignerError extends OpenSearchClientError {
15
+ constructor(message, data) {
16
+ super(message, data);
17
+ Error.captureStackTrace(this, AwsSigv4SignerError);
18
+ this.name = 'AwsSigv4SignerError';
19
+ this.message = message || 'AwsSigv4Signer Error';
20
+ this.data = data;
21
+ }
22
+ }
23
+
24
+ module.exports = AwsSigv4SignerError;
@@ -0,0 +1,39 @@
1
+ /*
2
+ * Copyright OpenSearch Contributors
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ *
5
+ * The OpenSearch Contributors require contributions made to
6
+ * this file be licensed under the Apache-2.0 license or a
7
+ * compatible open source license.
8
+ *
9
+ */
10
+
11
+ /// <reference types="node" />
12
+
13
+ import { Credentials } from '@aws-sdk/types';
14
+ import Connection from '../Connection';
15
+ import Transport from '../Transport';
16
+ import * as http from 'http';
17
+ import { OpenSearchClientError } from '../errors';
18
+
19
+ interface AwsSigv4SignerOptions {
20
+ getCredentials?: () => Promise<Credentials>;
21
+ region: string;
22
+ }
23
+
24
+ interface AwsSigv4SignerResponse {
25
+ Connection: typeof Connection;
26
+ Transport: typeof Transport;
27
+ buildSignedRequestObject(request: any): http.ClientRequestArgs;
28
+ }
29
+
30
+ declare function AwsSigv4Signer (opts: AwsSigv4SignerOptions): AwsSigv4SignerResponse;
31
+
32
+ declare class AwsSigv4SignerError extends OpenSearchClientError {
33
+ name: string;
34
+ message: string;
35
+ data: any;
36
+ constructor(message: string, data: any);
37
+ }
38
+
39
+ export { AwsSigv4Signer, AwsSigv4SignerOptions, AwsSigv4SignerResponse, AwsSigv4SignerError };
@@ -0,0 +1,19 @@
1
+ /*
2
+ * Copyright OpenSearch Contributors
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ *
5
+ * The OpenSearch Contributors require contributions made to
6
+ * this file be licensed under the Apache-2.0 license or a
7
+ * compatible open source license.
8
+ *
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ const AwsSigv4Signer = require('./AwsSigv4Signer');
14
+ const AwsSigv4SignerError = require('./errors');
15
+
16
+ module.exports = {
17
+ AwsSigv4Signer,
18
+ AwsSigv4SignerError,
19
+ };