@reportportal/client-javascript 5.4.2 → 5.4.3

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`. |
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`. |
64
122
  | 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. |
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
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 5.4.3-SNAPSHOT
1
+ 5.4.4-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,205 @@
1
+ const axios = require('axios');
2
+
3
+ const TOKEN_REFRESH_THRESHOLD_MS = 60000;
4
+ const DEFAULT_TOKEN_EXPIRATION_MS = 3600000; // 1 hour in milliseconds
5
+ const SECOND_IN_MS = 1000;
6
+ const GRANT_TYPE_PASSWORD = 'password';
7
+ const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
8
+
9
+ class OAuthInterceptor {
10
+ /**
11
+ * OAuth 2.0 Password Grant Flow Interceptor
12
+ * @param {Object} config - OAuth configuration
13
+ * @param {string} config.tokenEndpoint - OAuth token endpoint URL
14
+ * @param {string} config.username - Username for password grant
15
+ * @param {string} config.password - Password for password grant
16
+ * @param {string} config.clientId - OAuth client ID
17
+ * @param {string} [config.clientSecret] - OAuth client secret (optional)
18
+ * @param {string} [config.scope] - OAuth scope (optional)
19
+ * @param {boolean} [config.debug] - Enable debug logging
20
+ */
21
+ constructor(config) {
22
+ this.tokenEndpoint = config.tokenEndpoint;
23
+ this.username = config.username;
24
+ this.password = config.password;
25
+ this.clientId = config.clientId;
26
+ this.clientSecret = config.clientSecret;
27
+ this.scope = config.scope;
28
+ this.debug = config.debug || false;
29
+
30
+ this.accessToken = null;
31
+ this.refreshToken = null;
32
+ this.tokenExpiresAt = null;
33
+ this.tokenRenewPromise = null;
34
+ }
35
+
36
+ logDebug(message, data = '') {
37
+ if (this.debug) {
38
+ console.log(`[OAuth] ${message}`, data);
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Obtains or refreshes the access token
44
+ * @returns {Promise<string>} Access token
45
+ */
46
+ async getAccessToken() {
47
+ if (this.tokenRenewPromise) {
48
+ this.logDebug('Waiting for ongoing token refresh');
49
+ return this.tokenRenewPromise;
50
+ }
51
+
52
+ if (this.accessToken && this.tokenExpiresAt) {
53
+ const now = Date.now();
54
+ const timeUntilExpiry = this.tokenExpiresAt - now;
55
+
56
+ if (timeUntilExpiry > TOKEN_REFRESH_THRESHOLD_MS) {
57
+ this.logDebug('Using existing valid token');
58
+ return this.accessToken;
59
+ }
60
+
61
+ this.logDebug('Token expiring soon, refreshing');
62
+ }
63
+
64
+ this.tokenRenewPromise = this.renewToken();
65
+
66
+ try {
67
+ const token = await this.tokenRenewPromise;
68
+ return token;
69
+ } catch (error) {
70
+ this.logDebug('Error during token refresh', error);
71
+ throw error;
72
+ } finally {
73
+ this.tokenRenewPromise = null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Refreshes the access token using password grant or refresh token grant
79
+ * @returns {Promise<string>} Access token
80
+ */
81
+ async renewToken() {
82
+ try {
83
+ return await this.requestToken(
84
+ this.refreshToken ? GRANT_TYPE_REFRESH_TOKEN : GRANT_TYPE_PASSWORD,
85
+ );
86
+ } catch (error) {
87
+ // If refresh token grant failed, try password grant as fallback
88
+ if (this.refreshToken) {
89
+ this.logDebug('Refresh token failed, falling back to password grant');
90
+ console.warn(
91
+ '[OAuth] Refresh token expired or invalid, re-authenticating with password grant',
92
+ );
93
+ this.refreshToken = null; // Clear invalid refresh token
94
+
95
+ try {
96
+ return await this.requestToken(GRANT_TYPE_PASSWORD);
97
+ } catch (fallbackError) {
98
+ const errorMessage = fallbackError.response
99
+ ? `OAuth password grant fallback failed: ${
100
+ fallbackError.response.status
101
+ } - ${JSON.stringify(fallbackError.response.data)}`
102
+ : `OAuth password grant fallback failed: ${fallbackError.message}`;
103
+
104
+ console.error(`[OAuth] ${errorMessage}`);
105
+ throw new Error(errorMessage);
106
+ }
107
+ }
108
+
109
+ // No fallback available, rethrow original error
110
+ const errorMessage = error.response
111
+ ? `OAuth token request failed: ${error.response.status} - ${JSON.stringify(
112
+ error.response.data,
113
+ )}`
114
+ : `OAuth token request failed: ${error.message}`;
115
+
116
+ console.error(`[OAuth] ${errorMessage}`);
117
+ throw new Error(errorMessage);
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Requests a token using the specified grant type
123
+ * @param {string} grantType - Either 'password' or 'refresh_token'
124
+ * @returns {Promise<string>} Access token
125
+ * @private
126
+ */
127
+ async requestToken(grantType) {
128
+ const params = new URLSearchParams();
129
+ params.append('client_id', this.clientId);
130
+ params.append('grant_type', grantType);
131
+
132
+ if (grantType === GRANT_TYPE_REFRESH_TOKEN) {
133
+ this.logDebug('Requesting new access token using refresh_token');
134
+ params.append('refresh_token', this.refreshToken);
135
+ } else {
136
+ this.logDebug('Requesting access token using username and password');
137
+ params.append('username', this.username);
138
+ params.append('password', this.password);
139
+ }
140
+
141
+ if (this.clientSecret) {
142
+ params.append('client_secret', this.clientSecret);
143
+ }
144
+ if (this.scope) {
145
+ params.append('scope', this.scope);
146
+ }
147
+
148
+ const response = await axios.post(this.tokenEndpoint, params, {
149
+ headers: {
150
+ 'Content-Type': 'application/x-www-form-urlencoded',
151
+ },
152
+ });
153
+
154
+ const {
155
+ access_token: accessToken,
156
+ refresh_token: refreshToken,
157
+ expires_in: expiresIn,
158
+ } = response.data;
159
+
160
+ if (!accessToken) {
161
+ throw new Error('No access token received from OAuth server');
162
+ }
163
+
164
+ this.accessToken = accessToken;
165
+
166
+ if (refreshToken) {
167
+ this.refreshToken = refreshToken;
168
+ this.logDebug('Refresh token stored for future use');
169
+ }
170
+
171
+ if (expiresIn) {
172
+ this.tokenExpiresAt = Date.now() + expiresIn * SECOND_IN_MS;
173
+ this.logDebug(`Token obtained, expires in ${expiresIn} seconds`);
174
+ } else {
175
+ this.tokenExpiresAt = Date.now() + DEFAULT_TOKEN_EXPIRATION_MS;
176
+ this.logDebug('Token obtained, no expiration provided, assuming 1 hour');
177
+ }
178
+
179
+ return this.accessToken;
180
+ }
181
+
182
+ /**
183
+ * Attaches the interceptor to an axios instance
184
+ * @param {Object} axiosInstance - Axios instance to attach interceptor to
185
+ */
186
+ attach(axiosInstance) {
187
+ axiosInstance.interceptors.request.use(
188
+ async (config) => {
189
+ try {
190
+ const token = await this.getAccessToken();
191
+ // eslint-disable-next-line no-param-reassign
192
+ config.headers.Authorization = `Bearer ${token}`;
193
+ this.logDebug(`Request to ${config.url} with OAuth token`);
194
+ return config;
195
+ } catch (error) {
196
+ console.error('[OAuth] Failed to obtain access token, request may fail:', error.message);
197
+ return config;
198
+ }
199
+ },
200
+ (error) => Promise.reject(error),
201
+ );
202
+ }
203
+ }
204
+
205
+ module.exports = OAuthInterceptor;
@@ -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,7 @@ 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');
6
7
 
7
8
  const DEFAULT_MAX_CONNECTION_TIME_MS = 30000;
8
9
  const DEFAULT_RETRY_ATTEMPTS = 6;
@@ -22,6 +23,8 @@ class RestClient {
22
23
  this.baseURL = options.baseURL;
23
24
  this.headers = options.headers;
24
25
  this.restClientConfig = options.restClientConfig;
26
+ this.oauthConfig = options.oauthConfig;
27
+ this.debug = options.debug;
25
28
 
26
29
  this.axiosInstance = axios.create({
27
30
  timeout: DEFAULT_MAX_CONNECTION_TIME_MS,
@@ -29,6 +32,20 @@ class RestClient {
29
32
  ...this.getRestConfig(this.restClientConfig),
30
33
  });
31
34
 
35
+ // Create and attach OAuth interceptor if OAuth config is provided
36
+ // Must be before retry to ensure token is fresh on each retry
37
+ if (this.oauthConfig) {
38
+ try {
39
+ const oauthInterceptor = new OAuthInterceptor({
40
+ ...this.oauthConfig,
41
+ debug: this.debug,
42
+ });
43
+ oauthInterceptor.attach(this.axiosInstance);
44
+ } catch (error) {
45
+ console.error('[RestClient] Failed to initialize OAuth interceptor:', error.message);
46
+ }
47
+ }
48
+
32
49
  axiosRetry(this.axiosInstance, this.getRetryConfig());
33
50
 
34
51
  if (this.restClientConfig?.debug) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reportportal/client-javascript",
3
- "version": "5.4.2",
3
+ "version": "5.4.3",
4
4
  "description": "ReportPortal client for Node.js",
5
5
  "author": "ReportPortal.io",
6
6
  "scripts": {