@reportportal/client-javascript 5.4.2 → 5.5.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.
package/README.md CHANGED
@@ -50,21 +50,79 @@ rpClient.checkConnect().then(() => {
50
50
 
51
51
  ## Configuration
52
52
 
53
- When creating a client instance, you need to specify the following options:
53
+ When creating a client instance, you need to specify the following options.
54
54
 
55
- | Option | Necessity | Default | Description |
55
+ ### Authentication options
56
+
57
+ The client supports two authentication methods:
58
+ 1. **API Key Authentication** (default)
59
+ 2. **OAuth 2.0 Password Grant** (recommended for enhanced security)
60
+
61
+ **Note:**\
62
+ If both authentication methods are provided, OAuth 2.0 will be used.\
63
+ Either API key or complete OAuth 2.0 configuration is required to connect to ReportPortal.
64
+
65
+ | Option | Necessity | Default | Description |
66
+ |--------|-------------|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|
67
+ | apiKey | Conditional | | User's ReportPortal API key from which you want to send requests. It can be found on the profile page of this user. *Required only if OAuth is not configured. |
68
+ | oauth | Conditional | | OAuth 2.0 configuration object. When provided, OAuth authentication will be used instead of API key. See OAuth Configuration below. |
69
+
70
+ #### OAuth configuration
71
+
72
+ The `oauth` object supports the following properties:
73
+
74
+ | Property | Necessity | Default | Description |
56
75
  |-----------------------|------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
57
- | apiKey | Required | | User's reportportal token from which you want to send requests. It can be found on the profile page of this user. |
58
- | endpoint | Required | | URL of your server. For example, if you visit the page at 'https://server:8080/ui', then endpoint will be equal to 'https://server:8080/api/v1'. |
59
- | launch | Required | | Name of the launch at creation. |
60
- | project | Required | | The name of the project in which the launches will be created. |
61
- | headers | Optional | {} | The object with custom headers for internal http client. |
62
- | debug | Optional | false | This flag allows seeing the logs of the client. Useful for debugging. |
63
- | isLaunchMergeRequired | Optional | false | Allows client to merge launches into one at the end of the run via saving their UUIDs to the temp files at filesystem. At the end of the run launches can be merged using `mergeLaunches` method. Temp file format: `rplaunch-${launch_uuid}.tmp`. |
64
- | restClientConfig | Optional | Not set | `axios` like http client [config](https://github.com/axios/axios#request-config). May contain `agent` property for configure [http(s)](https://nodejs.org/api/https.html#https_https_request_url_options_callback) client, and other client options eg. `timeout`. For debugging and displaying logs you can set `debug: true`. Use the `retry` property (number or [`axios-retry`](https://github.com/softonic/axios-retry#options) config) to customise automatic retries. |
65
- | launchUuidPrint | Optional | false | Whether to print the current launch UUID. |
66
- | launchUuidPrintOutput | Optional | 'STDOUT' | Launch UUID printing output. Possible values: 'STDOUT', 'STDERR', 'FILE', 'ENVIRONMENT'. Works only if `launchUuidPrint` set to `true`. File format: `rp-launch-uuid-${launch_uuid}.tmp`. Env variable: `RP_LAUNCH_UUID`. |
67
- | token | Deprecated | Not set | Use `apiKey` instead. |
76
+ | tokenEndpoint | Required | | OAuth 2.0 token endpoint URL for password grant flow. |
77
+ | username | Required | | Username for OAuth 2.0 password grant. |
78
+ | password | Required | | Password for OAuth 2.0 password grant. |
79
+ | clientId | Required | | OAuth 2.0 client ID. |
80
+ | clientSecret | Optional | | OAuth 2.0 client secret (optional, depending on your OAuth server configuration). |
81
+ | scope | Optional | | OAuth 2.0 scope (optional, space-separated list of scopes). |
82
+
83
+ **Note:** The OAuth interceptor automatically handles token refresh when the token is about to expire (1 minute before expiration).
84
+
85
+ ##### OAuth 2.0 configuration example
86
+
87
+ ```javascript
88
+ const RPClient = require('@reportportal/client-javascript');
89
+
90
+ const rpClient = new RPClient({
91
+ endpoint: 'http://your-instance.com:8080/api/v1',
92
+ launch: 'LAUNCH_NAME',
93
+ project: 'PROJECT_NAME',
94
+ oauth: {
95
+ tokenEndpoint: 'https://your-oauth-server.com/oauth/token',
96
+ username: 'your-username',
97
+ password: 'your-password',
98
+ clientId: 'your-client-id',
99
+ clientSecret: 'your-client-secret', // optional
100
+ scope: 'reportportal', // optional
101
+ }
102
+ });
103
+
104
+ rpClient.checkConnect().then(() => {
105
+ console.log('You have successfully connected to the server.');
106
+ }, (error) => {
107
+ console.log('Error connection to server');
108
+ console.dir(error);
109
+ });
110
+ ```
111
+
112
+ ### General options
113
+
114
+ | Option | Necessity | Default | Description |
115
+ |-----------------------|------------|----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
116
+ | endpoint | Required | | URL of your server. For example, if you visit the page at 'https://server:8080/ui', then endpoint will be equal to 'https://server:8080/api/v1'. |
117
+ | launch | Required | | Name of the launch at creation. |
118
+ | project | Required | | The name of the project in which the launches will be created. |
119
+ | headers | Optional | {} | The object with custom headers for internal http client. |
120
+ | debug | Optional | false | This flag allows seeing the logs of the client. Useful for debugging. |
121
+ | isLaunchMergeRequired | Optional | false | Allows client to merge launches into one at the end of the run via saving their UUIDs to the temp files at filesystem. At the end of the run launches can be merged using `mergeLaunches` method. Temp file format: `rplaunch-${launch_uuid}.tmp`. |
122
+ | restClientConfig | Optional | Not set | `axios` like http client [config](https://github.com/axios/axios#request-config). Supports `proxy` and `noProxy` for proxy configuration (see [Proxy configuration](#proxy-configuration)), `agent` property for [http(s)](https://nodejs.org/api/https.html#https_https_request_url_options_callback) client options, `timeout`, `debug: true` for debugging, and `retry` property (number or [`axios-retry`](https://github.com/softonic/axios-retry#options) config) for automatic retries. |
123
+ | launchUuidPrint | Optional | false | Whether to print the current launch UUID. |
124
+ | launchUuidPrintOutput | Optional | 'STDOUT' | Launch UUID printing output. Possible values: 'STDOUT', 'STDERR', 'FILE', 'ENVIRONMENT'. Works only if `launchUuidPrint` set to `true`. File format: `rp-launch-uuid-${launch_uuid}.tmp`. Env variable: `RP_LAUNCH_UUID`. |
125
+ | token | Deprecated | Not set | Use `apiKey` or `oauth` instead. |
68
126
 
69
127
  ## Asynchronous reporting
70
128
 
@@ -108,6 +166,169 @@ const client = new RPClient({
108
166
 
109
167
  Setting `retry: 0` disables automatic retries.
110
168
 
169
+ ### Proxy configuration
170
+
171
+ The client supports comprehensive proxy configuration for both HTTP and HTTPS requests, including ReportPortal API calls and OAuth token requests. Proxy settings can be configured via `restClientConfig` or environment variables.
172
+
173
+ #### Basic proxy configuration
174
+
175
+ ##### Via configuration object
176
+
177
+ ```javascript
178
+ const RPClient = require('@reportportal/client-javascript');
179
+
180
+ const rpClient = new RPClient({
181
+ apiKey: 'your_api_key',
182
+ endpoint: 'http://your-instance.com:8080/api/v1',
183
+ launch: 'LAUNCH_NAME',
184
+ project: 'PROJECT_NAME',
185
+ restClientConfig: {
186
+ proxy: {
187
+ protocol: 'https', // 'http' or 'https'
188
+ host: '127.0.0.1',
189
+ port: 8080,
190
+ // Optional authentication
191
+ auth: {
192
+ username: 'proxy-user',
193
+ password: 'proxy-password'
194
+ }
195
+ }
196
+ }
197
+ });
198
+ ```
199
+
200
+ ##### Via proxy URL string
201
+
202
+ ```javascript
203
+ const rpClient = new RPClient({
204
+ // ... other options
205
+ restClientConfig: {
206
+ proxy: 'https://127.0.0.1:8080'
207
+ }
208
+ });
209
+ ```
210
+
211
+ ##### Via environment variables
212
+
213
+ The client automatically detects and uses proxy environment variables:
214
+
215
+ ```bash
216
+ export HTTPS_PROXY=https://127.0.0.1:8080
217
+ export HTTP_PROXY=http://127.0.0.1:8080
218
+ export NO_PROXY=localhost,127.0.0.1,.local
219
+ ```
220
+
221
+ #### Bypassing proxy for specific domains (noProxy)
222
+
223
+ Use the `noProxy` option to exclude specific domains from being proxied. This is useful when some services are accessible directly while others require a proxy.
224
+
225
+ ```javascript
226
+ const rpClient = new RPClient({
227
+ // ... other options
228
+ restClientConfig: {
229
+ proxy: {
230
+ protocol: 'https',
231
+ host: '127.0.0.1',
232
+ port: 8080
233
+ },
234
+ // Bypass proxy for these domains
235
+ noProxy: 'localhost,127.0.0.1,internal.company.com,.local.domain'
236
+ }
237
+ });
238
+ ```
239
+
240
+ **noProxy format:**
241
+ - Exact hostname: `example.com` - matches `example.com` and `sub.example.com`
242
+ - Leading dot: `.example.com` - matches only subdomains like `sub.example.com` (not `example.com` itself)
243
+ - Wildcard: `*` - bypass proxy for all requests
244
+ - Multiple entries: Comma-separated list
245
+
246
+ **Priority:** Configuration `noProxy` takes precedence over `NO_PROXY` environment variable.
247
+
248
+ #### Proxy with OAuth authentication
249
+
250
+ When using OAuth authentication, the proxy configuration is automatically applied to both:
251
+ - OAuth token endpoint requests
252
+ - ReportPortal API requests
253
+
254
+ ```javascript
255
+ const rpClient = new RPClient({
256
+ endpoint: 'http://your-instance.com:8080/api/v1',
257
+ project: 'PROJECT_NAME',
258
+ oauth: {
259
+ tokenEndpoint: 'https://login.microsoftonline.com/.../oauth2/v2.0/token',
260
+ username: 'your-username',
261
+ password: 'your-password',
262
+ clientId: 'your-client-id'
263
+ },
264
+ restClientConfig: {
265
+ proxy: {
266
+ protocol: 'https',
267
+ host: '127.0.0.1',
268
+ port: 8080
269
+ },
270
+ // Example: Use proxy for OAuth, bypass for ReportPortal
271
+ noProxy: 'your-instance.com'
272
+ }
273
+ });
274
+ ```
275
+
276
+ #### Advanced proxy scenarios
277
+
278
+ ##### Disable proxy explicitly
279
+
280
+ ```javascript
281
+ restClientConfig: {
282
+ proxy: false // Disable proxy even if environment variables are set
283
+ }
284
+ ```
285
+
286
+ ##### Debug proxy configuration
287
+
288
+ Enable debug mode to see detailed proxy decision logs:
289
+
290
+ ```javascript
291
+ restClientConfig: {
292
+ proxy: { /* ... */ },
293
+ noProxy: 'localhost,.local',
294
+ debug: true // See proxy-related logs
295
+ }
296
+ ```
297
+
298
+ Debug output example:
299
+ ```
300
+ [ProxyHelper] getProxyConfig called:
301
+ URL: https://login.microsoftonline.com/oauth2/v2.0/token
302
+ Hostname: login.microsoftonline.com
303
+ noProxy from config: localhost,.local
304
+ Should bypass proxy: false
305
+ [ProxyHelper] Creating proxy agent:
306
+ URL: https://login.microsoftonline.com/oauth2/v2.0/token
307
+ Protocol: https:
308
+ Proxy URL: https://127.0.0.1:8080
309
+ ```
310
+
311
+ #### Proxy configuration options
312
+
313
+ | Option | Type | Description |
314
+ |---------------------|------------------------------|-------------------------------------------------------------------------------------------------|
315
+ | `proxy` | `false \| string \| object` | Proxy configuration. Can be `false` (disable), URL string, or configuration object (see below) |
316
+ | `proxy.protocol` | `string` | Proxy protocol: `'http'` or `'https'` |
317
+ | `proxy.host` | `string` | Proxy host address |
318
+ | `proxy.port` | `number` | Proxy port number |
319
+ | `proxy.auth` | `object` | Optional proxy authentication |
320
+ | `proxy.auth.username` | `string` | Proxy username |
321
+ | `proxy.auth.password` | `string` | Proxy password |
322
+ | `noProxy` | `string` | Comma-separated list of domains to bypass proxy |
323
+
324
+ #### How proxy handling works
325
+
326
+ 1. **Per-request proxy decision:** Each request (API or OAuth) determines its proxy configuration based on the target URL
327
+ 2. **noProxy checking:** URLs matching `noProxy` patterns bypass the proxy and connect directly
328
+ 3. **Default agents for bypassed URLs:** When a URL bypasses proxy, a default HTTP/HTTPS agent is used to prevent automatic proxy detection
329
+ 4. **Environment variable support:** `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` are automatically detected and used if no explicit configuration is provided
330
+ 5. **Priority:** Explicit configuration takes precedence over environment variables
331
+
111
332
  ### checkConnect
112
333
 
113
334
  `checkConnect` - asynchronous method for verifying the correctness of the client connection
package/VERSION CHANGED
@@ -1 +1 @@
1
- 5.4.3-SNAPSHOT
1
+ 5.5.1-SNAPSHOT
@@ -31,13 +31,62 @@ const getApiKey = ({ apiKey, token }) => {
31
31
  return calculatedApiKey;
32
32
  };
33
33
 
34
+ const getOAuthConfig = (options) => {
35
+ const oauthParams = options.oauth || {};
36
+
37
+ const { tokenEndpoint, username, password, clientId, clientSecret, scope } = oauthParams;
38
+
39
+ if (!tokenEndpoint && !username && !password && !clientId) {
40
+ return null;
41
+ }
42
+
43
+ if (!tokenEndpoint) {
44
+ throw new ReportPortalRequiredOptionError('oauth.tokenEndpoint');
45
+ }
46
+ if (!username) {
47
+ throw new ReportPortalRequiredOptionError('oauth.username');
48
+ }
49
+ if (!password) {
50
+ throw new ReportPortalRequiredOptionError('oauth.password');
51
+ }
52
+ if (!clientId) {
53
+ throw new ReportPortalRequiredOptionError('oauth.clientId');
54
+ }
55
+
56
+ return {
57
+ tokenEndpoint,
58
+ username,
59
+ password,
60
+ clientId,
61
+ clientSecret,
62
+ scope,
63
+ };
64
+ };
65
+
34
66
  const getClientConfig = (options) => {
35
67
  let calculatedOptions = options;
36
68
  try {
37
69
  if (typeof options !== 'object') {
38
70
  throw new ReportPortalValidationError('`options` must be an object.');
39
71
  }
40
- const apiKey = getApiKey(options);
72
+
73
+ // Try to get OAuth config first
74
+ const oauthConfig = getOAuthConfig(options);
75
+
76
+ // If OAuth is not configured, apiKey is required
77
+ let apiKey;
78
+ if (!oauthConfig) {
79
+ apiKey = getApiKey(options);
80
+ } else {
81
+ // If OAuth is configured, apiKey is optional (use it if provided)
82
+ try {
83
+ apiKey = getApiKey(options);
84
+ } catch (error) {
85
+ // Ignore error if OAuth is configured
86
+ apiKey = null;
87
+ }
88
+ }
89
+
41
90
  const project = getRequiredOption(options, 'project');
42
91
  const endpoint = getRequiredOption(options, 'endpoint');
43
92
 
@@ -52,6 +101,7 @@ const getClientConfig = (options) => {
52
101
 
53
102
  calculatedOptions = {
54
103
  apiKey,
104
+ oauth: oauthConfig,
55
105
  project,
56
106
  endpoint,
57
107
  launch: options.launch,
@@ -78,4 +128,5 @@ module.exports = {
78
128
  getClientConfig,
79
129
  getRequiredOption,
80
130
  getApiKey,
131
+ getOAuthConfig,
81
132
  };
package/lib/oauth.js ADDED
@@ -0,0 +1,223 @@
1
+ const axios = require('axios');
2
+ const { getProxyAgentForUrl } = require('./proxyHelper');
3
+
4
+ const TOKEN_REFRESH_THRESHOLD_MS = 60000;
5
+ const DEFAULT_TOKEN_EXPIRATION_MS = 3600000; // 1 hour in milliseconds
6
+ const SECOND_IN_MS = 1000;
7
+ const GRANT_TYPE_PASSWORD = 'password';
8
+ const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
9
+
10
+ class OAuthInterceptor {
11
+ /**
12
+ * OAuth 2.0 Password Grant Flow Interceptor
13
+ * @param {Object} config - OAuth configuration
14
+ * @param {string} config.tokenEndpoint - OAuth token endpoint URL
15
+ * @param {string} config.username - Username for password grant
16
+ * @param {string} config.password - Password for password grant
17
+ * @param {string} config.clientId - OAuth client ID
18
+ * @param {string} [config.clientSecret] - OAuth client secret (optional)
19
+ * @param {string} [config.scope] - OAuth scope (optional)
20
+ * @param {boolean} [config.debug] - Enable debug logging
21
+ * @param {Object} [config.restClientConfig] - REST client configuration for proxy support
22
+ */
23
+ constructor(config) {
24
+ this.tokenEndpoint = config.tokenEndpoint;
25
+ this.username = config.username;
26
+ this.password = config.password;
27
+ this.clientId = config.clientId;
28
+ this.clientSecret = config.clientSecret;
29
+ this.scope = config.scope;
30
+ this.restClientConfig = config.restClientConfig || {};
31
+ this.debug = this.restClientConfig.debug || false;
32
+
33
+ this.accessToken = null;
34
+ this.refreshToken = null;
35
+ this.tokenExpiresAt = null;
36
+ this.tokenRenewPromise = null;
37
+ }
38
+
39
+ logDebug(message, data = '') {
40
+ if (this.debug) {
41
+ console.log(`[OAuth] ${message}`, data);
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Obtains or refreshes the access token
47
+ * @returns {Promise<string>} Access token
48
+ */
49
+ async getAccessToken() {
50
+ if (this.tokenRenewPromise) {
51
+ this.logDebug('Waiting for ongoing token refresh');
52
+ return this.tokenRenewPromise;
53
+ }
54
+
55
+ if (this.accessToken && this.tokenExpiresAt) {
56
+ const now = Date.now();
57
+ const timeUntilExpiry = this.tokenExpiresAt - now;
58
+
59
+ if (timeUntilExpiry > TOKEN_REFRESH_THRESHOLD_MS) {
60
+ this.logDebug('Using existing valid token');
61
+ return this.accessToken;
62
+ }
63
+
64
+ this.logDebug('Token expiring soon, refreshing');
65
+ }
66
+
67
+ this.tokenRenewPromise = this.renewToken();
68
+
69
+ try {
70
+ const token = await this.tokenRenewPromise;
71
+ return token;
72
+ } catch (error) {
73
+ this.logDebug('Error during token refresh', error);
74
+ throw error;
75
+ } finally {
76
+ this.tokenRenewPromise = null;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Refreshes the access token using password grant or refresh token grant
82
+ * @returns {Promise<string>} Access token
83
+ */
84
+ async renewToken() {
85
+ try {
86
+ return await this.requestToken(
87
+ this.refreshToken ? GRANT_TYPE_REFRESH_TOKEN : GRANT_TYPE_PASSWORD,
88
+ );
89
+ } catch (error) {
90
+ // If refresh token grant failed, try password grant as fallback
91
+ if (this.refreshToken) {
92
+ this.logDebug('Refresh token failed, falling back to password grant');
93
+ console.warn(
94
+ '[OAuth] Refresh token expired or invalid, re-authenticating with password grant',
95
+ );
96
+ this.refreshToken = null; // Clear invalid refresh token
97
+
98
+ try {
99
+ return await this.requestToken(GRANT_TYPE_PASSWORD);
100
+ } catch (fallbackError) {
101
+ const errorMessage = fallbackError.response
102
+ ? `OAuth password grant fallback failed: ${
103
+ fallbackError.response.status
104
+ } - ${JSON.stringify(fallbackError.response.data)}`
105
+ : `OAuth password grant fallback failed: ${fallbackError.message}`;
106
+
107
+ console.error(`[OAuth] ${errorMessage}`);
108
+ throw new Error(errorMessage);
109
+ }
110
+ }
111
+
112
+ // No fallback available, rethrow original error
113
+ const errorMessage = error.response
114
+ ? `OAuth token request failed: ${error.response.status} - ${JSON.stringify(
115
+ error.response.data,
116
+ )}`
117
+ : `OAuth token request failed: ${error.message}`;
118
+
119
+ console.error(`[OAuth] ${errorMessage}`);
120
+ throw new Error(errorMessage);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Requests a token using the specified grant type
126
+ * @param {string} grantType - Either 'password' or 'refresh_token'
127
+ * @returns {Promise<string>} Access token
128
+ * @private
129
+ */
130
+ async requestToken(grantType) {
131
+ const params = new URLSearchParams();
132
+ params.append('client_id', this.clientId);
133
+ params.append('grant_type', grantType);
134
+
135
+ if (grantType === GRANT_TYPE_REFRESH_TOKEN) {
136
+ this.logDebug('Requesting new access token using refresh_token');
137
+ params.append('refresh_token', this.refreshToken);
138
+ } else {
139
+ this.logDebug('Requesting access token using username and password');
140
+ params.append('username', this.username);
141
+ params.append('password', this.password);
142
+ }
143
+
144
+ if (this.clientSecret) {
145
+ params.append('client_secret', this.clientSecret);
146
+ }
147
+ if (this.scope) {
148
+ params.append('scope', this.scope);
149
+ }
150
+
151
+ // Get proxy agent for token endpoint
152
+ // Only apply if custom agents are not explicitly provided
153
+ const hasCustomAgents = this.restClientConfig.httpsAgent || this.restClientConfig.httpAgent;
154
+ const proxyAgents = hasCustomAgents
155
+ ? {}
156
+ : getProxyAgentForUrl(this.tokenEndpoint, this.restClientConfig);
157
+
158
+ if (this.debug && Object.keys(proxyAgents).length > 0) {
159
+ this.logDebug(`Making token request to ${this.tokenEndpoint} with proxy agent`);
160
+ }
161
+
162
+ const response = await axios.post(this.tokenEndpoint, params, {
163
+ headers: {
164
+ 'Content-Type': 'application/x-www-form-urlencoded',
165
+ },
166
+ ...proxyAgents,
167
+ // Custom agents from restClientConfig (if provided) take precedence
168
+ ...(this.restClientConfig.httpsAgent && { httpsAgent: this.restClientConfig.httpsAgent }),
169
+ ...(this.restClientConfig.httpAgent && { httpAgent: this.restClientConfig.httpAgent }),
170
+ });
171
+
172
+ const {
173
+ access_token: accessToken,
174
+ refresh_token: refreshToken,
175
+ expires_in: expiresIn,
176
+ } = response.data;
177
+
178
+ if (!accessToken) {
179
+ throw new Error('No access token received from OAuth server');
180
+ }
181
+
182
+ this.accessToken = accessToken;
183
+
184
+ if (refreshToken) {
185
+ this.refreshToken = refreshToken;
186
+ this.logDebug('Refresh token stored for future use');
187
+ }
188
+
189
+ if (expiresIn) {
190
+ this.tokenExpiresAt = Date.now() + expiresIn * SECOND_IN_MS;
191
+ this.logDebug(`Token obtained, expires in ${expiresIn} seconds`);
192
+ } else {
193
+ this.tokenExpiresAt = Date.now() + DEFAULT_TOKEN_EXPIRATION_MS;
194
+ this.logDebug('Token obtained, no expiration provided, assuming 1 hour');
195
+ }
196
+
197
+ return this.accessToken;
198
+ }
199
+
200
+ /**
201
+ * Attaches the interceptor to an axios instance
202
+ * @param {Object} axiosInstance - Axios instance to attach interceptor to
203
+ */
204
+ attach(axiosInstance) {
205
+ axiosInstance.interceptors.request.use(
206
+ async (config) => {
207
+ try {
208
+ const token = await this.getAccessToken();
209
+ // eslint-disable-next-line no-param-reassign
210
+ config.headers.Authorization = `Bearer ${token}`;
211
+ this.logDebug(`Request to ${config.url} with OAuth token`);
212
+ return config;
213
+ } catch (error) {
214
+ console.error('[OAuth] Failed to obtain access token, request may fail:', error.message);
215
+ return config;
216
+ }
217
+ },
218
+ (error) => Promise.reject(error),
219
+ );
220
+ }
221
+ }
222
+
223
+ module.exports = OAuthInterceptor;
@@ -0,0 +1,205 @@
1
+ const { getProxyForUrl } = require('proxy-from-env');
2
+ const { HttpsProxyAgent } = require('https-proxy-agent');
3
+ const { HttpProxyAgent } = require('http-proxy-agent');
4
+ const http = require('http');
5
+ const https = require('https');
6
+
7
+ /**
8
+ * Sanitizes a URL by removing credentials (username/password) for safe logging
9
+ * @param {string} urlString - The URL to sanitize
10
+ * @returns {string} - Sanitized URL with credentials replaced by [REDACTED]
11
+ */
12
+ function sanitizeUrlForLogging(urlString) {
13
+ try {
14
+ const urlObj = new URL(urlString);
15
+ if (urlObj.username || urlObj.password) {
16
+ // Replace credentials with [REDACTED]
17
+ urlObj.username = '[REDACTED]';
18
+ urlObj.password = '';
19
+ return urlObj.toString();
20
+ }
21
+ return urlString;
22
+ } catch (error) {
23
+ // If URL parsing fails, return as-is (likely not a URL)
24
+ return urlString;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Checks if a URL should bypass proxy based on NO_PROXY patterns
30
+ * @param {string} url - The URL to check
31
+ * @param {string} noProxy - Comma-separated list of domains/patterns to bypass
32
+ * @returns {boolean} - True if proxy should be bypassed
33
+ */
34
+ function shouldBypassProxy(url, noProxy) {
35
+ if (!noProxy) return false;
36
+
37
+ try {
38
+ const urlObj = new URL(url);
39
+ const hostname = urlObj.hostname.toLowerCase();
40
+
41
+ // Split NO_PROXY entries and clean them
42
+ const patterns = noProxy
43
+ .split(',')
44
+ .map((entry) => entry.trim().toLowerCase())
45
+ .filter(Boolean);
46
+
47
+ return patterns.some((pattern) => {
48
+ // Special case: * means bypass all
49
+ if (pattern === '*') return true;
50
+
51
+ // Pattern with leading dot (.example.com) - only matches subdomains
52
+ if (pattern.startsWith('.')) {
53
+ const cleanPattern = pattern.slice(1);
54
+ // Should match sub.example.com but NOT example.com
55
+ return hostname.endsWith(`.${cleanPattern}`);
56
+ }
57
+
58
+ // Pattern without leading dot (example.com) - matches domain and subdomains
59
+ // Exact match
60
+ if (hostname === pattern) return true;
61
+
62
+ // Suffix match (example.com matches sub.example.com)
63
+ if (hostname.endsWith(`.${pattern}`)) return true;
64
+
65
+ return false;
66
+ });
67
+ } catch (error) {
68
+ // If URL parsing fails, don't bypass proxy
69
+ return false;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Gets proxy configuration for a given URL
75
+ * Checks both environment variables and explicit config
76
+ * @param {string} url - The target URL
77
+ * @param {object} proxyConfig - Explicit proxy configuration from restClientConfig
78
+ * @returns {object|null} - Proxy URL and bypass info, or null if no proxy
79
+ */
80
+ function getProxyConfig(url, proxyConfig = {}) {
81
+ const urlObj = new URL(url);
82
+
83
+ // Check NO_PROXY from config or environment
84
+ const noProxyFromConfig = proxyConfig.noProxy;
85
+ const noProxyFromEnv = process.env.NO_PROXY || process.env.no_proxy || '';
86
+ const noProxy = noProxyFromConfig || noProxyFromEnv;
87
+
88
+ if (proxyConfig.debug) {
89
+ console.log('[ProxyHelper] getProxyConfig called:');
90
+ console.log(' URL:', url);
91
+ console.log(' Hostname:', urlObj.hostname);
92
+ console.log(' noProxy from config:', noProxyFromConfig);
93
+ console.log(' noProxy from env:', noProxyFromEnv);
94
+ console.log(' Final noProxy:', noProxy);
95
+ }
96
+
97
+ // Check if URL should bypass proxy
98
+ const shouldBypass = shouldBypassProxy(url, noProxy);
99
+ if (proxyConfig.debug) {
100
+ console.log(' Should bypass proxy:', shouldBypass);
101
+ }
102
+
103
+ if (shouldBypass) {
104
+ return null;
105
+ }
106
+
107
+ // If proxy is explicitly disabled
108
+ if (proxyConfig.proxy === false) {
109
+ return null;
110
+ }
111
+
112
+ // Priority 1: Explicit proxy configuration object
113
+ if (proxyConfig.proxy && typeof proxyConfig.proxy === 'object') {
114
+ const { protocol: proxyProtocol, host, port, auth } = proxyConfig.proxy;
115
+ if (host && port) {
116
+ let proxyUrl = `${proxyProtocol || 'http'}://${host}:${port}`;
117
+ if (auth) {
118
+ const { username, password } = auth;
119
+ proxyUrl = `${proxyProtocol || 'http'}://${username}:${password}@${host}:${port}`;
120
+ }
121
+ return { proxyUrl };
122
+ }
123
+ }
124
+
125
+ // Priority 2: Explicit proxy URL string
126
+ if (typeof proxyConfig.proxy === 'string') {
127
+ return { proxyUrl: proxyConfig.proxy };
128
+ }
129
+
130
+ // Priority 3: Environment variables (with NO_PROXY support via proxy-from-env)
131
+ const proxyUrlFromEnv = getProxyForUrl(url);
132
+ if (proxyUrlFromEnv) {
133
+ return { proxyUrl: proxyUrlFromEnv };
134
+ }
135
+
136
+ return null;
137
+ }
138
+
139
+ /**
140
+ * Creates an HTTP/HTTPS agent with proxy configuration for a specific URL
141
+ * @param {string} url - The target URL for the request
142
+ * @param {object} restClientConfig - The rest client configuration
143
+ * @returns {object} - Object with httpAgent and/or httpsAgent
144
+ */
145
+ function createProxyAgents(url, restClientConfig = {}) {
146
+ const urlObj = new URL(url);
147
+ const isHttps = urlObj.protocol === 'https:';
148
+ const proxyConfig = getProxyConfig(url, restClientConfig);
149
+
150
+ if (!proxyConfig) {
151
+ if (restClientConfig.debug) {
152
+ console.log('[ProxyHelper] No proxy for URL (bypassed or not configured):', url);
153
+ console.log(' Using default agent to prevent axios from using env proxy');
154
+ }
155
+ // Return a default agent to prevent axios from using HTTP_PROXY/HTTPS_PROXY env vars
156
+ // This ensures that URLs in noProxy truly bypass the proxy
157
+ if (isHttps) {
158
+ return {
159
+ httpsAgent: new https.Agent(),
160
+ };
161
+ } else {
162
+ return {
163
+ httpAgent: new http.Agent(),
164
+ };
165
+ }
166
+ }
167
+
168
+ const { proxyUrl } = proxyConfig;
169
+
170
+ if (restClientConfig.debug) {
171
+ console.log('[ProxyHelper] Creating proxy agent:');
172
+ console.log(' URL:', url);
173
+ console.log(' Protocol:', urlObj.protocol);
174
+ console.log(' Proxy URL:', sanitizeUrlForLogging(proxyUrl));
175
+ }
176
+
177
+ // Create appropriate agent based on target protocol
178
+ if (isHttps) {
179
+ return {
180
+ httpsAgent: new HttpsProxyAgent(proxyUrl),
181
+ };
182
+ } else {
183
+ return {
184
+ httpAgent: new HttpProxyAgent(proxyUrl),
185
+ };
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Gets proxy agent for a specific request URL
191
+ * This is the main function to be used in axios requests
192
+ * @param {string} url - The target URL for the request
193
+ * @param {object} restClientConfig - The rest client configuration
194
+ * @returns {object} - Object with agent configuration for axios
195
+ */
196
+ function getProxyAgentForUrl(url, restClientConfig = {}) {
197
+ return createProxyAgents(url, restClientConfig);
198
+ }
199
+
200
+ module.exports = {
201
+ shouldBypassProxy,
202
+ getProxyConfig,
203
+ createProxyAgents,
204
+ getProxyAgentForUrl,
205
+ };
@@ -39,17 +39,27 @@ class RPClient {
39
39
 
40
40
  this.map = {};
41
41
  this.baseURL = [this.config.endpoint, this.config.project].join('/');
42
- this.headers = {
42
+
43
+ const headers = {
43
44
  'User-Agent': 'NodeJS',
44
45
  'Content-Type': 'application/json; charset=UTF-8',
45
- Authorization: `Bearer ${this.apiKey}`,
46
46
  ...(this.config.headers || {}),
47
47
  };
48
+
49
+ // Only set API key header if OAuth is not configured
50
+ // OAuth interceptor will handle Authorization header when configured
51
+ if (!this.config.oauth && this.apiKey) {
52
+ headers.Authorization = `Bearer ${this.apiKey}`;
53
+ }
54
+
55
+ this.headers = headers;
48
56
  this.helpers = helpers;
49
57
  this.restClient = new RestClient({
50
58
  baseURL: this.baseURL,
51
59
  headers: this.headers,
52
60
  restClientConfig: this.config.restClientConfig,
61
+ oauthConfig: this.config.oauth,
62
+ debug: this.debug,
53
63
  });
54
64
  this.statistics = new Statistics(EVENT_NAME, agentParams);
55
65
  this.launchUuid = '';
package/lib/rest.js CHANGED
@@ -3,6 +3,8 @@ const axiosRetry = require('axios-retry').default;
3
3
  const http = require('http');
4
4
  const https = require('https');
5
5
  const logger = require('./logger');
6
+ const OAuthInterceptor = require('./oauth');
7
+ const { getProxyAgentForUrl } = require('./proxyHelper');
6
8
 
7
9
  const DEFAULT_MAX_CONNECTION_TIME_MS = 30000;
8
10
  const DEFAULT_RETRY_ATTEMPTS = 6;
@@ -15,13 +17,15 @@ const DEFAULT_RETRY_CONFIG = {
15
17
  retryCondition: axiosRetry.isRetryableError,
16
18
  shouldResetTimeout: true,
17
19
  };
18
- const SKIPPED_REST_CONFIG_KEYS = ['agent', 'retry'];
20
+ const SKIPPED_REST_CONFIG_KEYS = ['agent', 'retry', 'proxy', 'noProxy'];
19
21
 
20
22
  class RestClient {
21
23
  constructor(options) {
22
24
  this.baseURL = options.baseURL;
23
25
  this.headers = options.headers;
24
26
  this.restClientConfig = options.restClientConfig;
27
+ this.oauthConfig = options.oauthConfig;
28
+ this.debug = options.debug;
25
29
 
26
30
  this.axiosInstance = axios.create({
27
31
  timeout: DEFAULT_MAX_CONNECTION_TIME_MS,
@@ -29,6 +33,21 @@ class RestClient {
29
33
  ...this.getRestConfig(this.restClientConfig),
30
34
  });
31
35
 
36
+ // Create and attach OAuth interceptor if OAuth config is provided
37
+ // Must be before retry to ensure token is fresh on each retry
38
+ if (this.oauthConfig) {
39
+ try {
40
+ const oauthInterceptor = new OAuthInterceptor({
41
+ ...this.oauthConfig,
42
+ debug: this.debug,
43
+ restClientConfig: this.restClientConfig,
44
+ });
45
+ oauthInterceptor.attach(this.axiosInstance);
46
+ } catch (error) {
47
+ console.error('[RestClient] Failed to initialize OAuth interceptor:', error.message);
48
+ }
49
+ }
50
+
32
51
  axiosRetry(this.axiosInstance, this.getRetryConfig());
33
52
 
34
53
  if (this.restClientConfig?.debug) {
@@ -45,12 +64,19 @@ class RestClient {
45
64
  }
46
65
 
47
66
  request(method, url, data, options = {}) {
67
+ // Only apply proxy agents if custom agents are not explicitly provided
68
+ // Priority: explicit httpsAgent/httpAgent > proxy config > default
69
+ const hasCustomAgents =
70
+ 'httpsAgent' in this.restClientConfig || 'httpAgent' in this.restClientConfig;
71
+ const proxyAgents = hasCustomAgents ? {} : getProxyAgentForUrl(url, this.restClientConfig);
72
+
48
73
  return this.axiosInstance
49
74
  .request({
50
75
  method,
51
76
  url,
52
77
  data,
53
78
  ...options,
79
+ ...proxyAgents,
54
80
  headers: {
55
81
  HOST: new URL(url).host,
56
82
  ...options.headers,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reportportal/client-javascript",
3
- "version": "5.4.2",
3
+ "version": "5.5.0",
4
4
  "description": "ReportPortal client for Node.js",
5
5
  "author": "ReportPortal.io",
6
6
  "scripts": {
@@ -28,7 +28,10 @@
28
28
  "axios": "^1.12.2",
29
29
  "axios-retry": "^4.5.0",
30
30
  "glob": "^8.1.0",
31
+ "http-proxy-agent": "^7.0.2",
32
+ "https-proxy-agent": "^7.0.6",
31
33
  "ini": "^2.0.0",
34
+ "proxy-from-env": "^1.1.0",
32
35
  "uniqid": "^5.4.0",
33
36
  "uuid": "^9.0.1"
34
37
  },