@webex/webex-core 3.13.0-next.1 → 3.13.0-next.10

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 (51) hide show
  1. package/.repo-context.json +1 -1
  2. package/.sdd/manifest.json +14 -4
  3. package/AGENTS.md +2 -2
  4. package/README.md +1 -1
  5. package/dist/config.js +1 -1
  6. package/dist/config.js.map +1 -1
  7. package/dist/credentials-config.js +9 -1
  8. package/dist/credentials-config.js.map +1 -1
  9. package/dist/interceptors/auth.js +10 -1
  10. package/dist/interceptors/auth.js.map +1 -1
  11. package/dist/lib/batcher.js +1 -1
  12. package/dist/lib/credentials/credentials.js +15 -2
  13. package/dist/lib/credentials/credentials.js.map +1 -1
  14. package/dist/lib/credentials/token.js +23 -9
  15. package/dist/lib/credentials/token.js.map +1 -1
  16. package/dist/lib/interceptors/service.js +5 -1
  17. package/dist/lib/interceptors/service.js.map +1 -1
  18. package/dist/lib/services/catalog-auth.js +114 -0
  19. package/dist/lib/services/catalog-auth.js.map +1 -0
  20. package/dist/lib/services/services.js +46 -3
  21. package/dist/lib/services/services.js.map +1 -1
  22. package/dist/lib/services-v2/services-v2.js +40 -3
  23. package/dist/lib/services-v2/services-v2.js.map +1 -1
  24. package/dist/plugins/logger.js +1 -1
  25. package/dist/webex-core.js +2 -2
  26. package/dist/webex-core.js.map +1 -1
  27. package/docs/getting-started.md +2 -2
  28. package/package.json +13 -13
  29. package/src/config.js +1 -1
  30. package/src/credentials-config.js +9 -0
  31. package/src/interceptors/auth.js +14 -1
  32. package/src/lib/credentials/credentials.js +13 -1
  33. package/src/lib/credentials/docs/README.md +18 -17
  34. package/src/lib/credentials/token.js +15 -8
  35. package/src/lib/interceptors/service.js +11 -3
  36. package/src/lib/services/catalog-auth.js +112 -0
  37. package/src/lib/services/docs/README.md +4 -4
  38. package/src/lib/services/services.js +54 -2
  39. package/src/lib/services-v2/docs/README.md +4 -4
  40. package/src/lib/services-v2/services-v2.ts +48 -2
  41. package/test/fixtures/activation-email.ts +1 -1
  42. package/test/integration/spec/credentials/credentials.js +3 -1
  43. package/test/integration/spec/credentials/token.js +8 -0
  44. package/test/integration/spec/services/service-catalog.js +5 -0
  45. package/test/integration/spec/unit-browser/token.js +7 -2
  46. package/test/unit/spec/credentials/credentials.js +79 -0
  47. package/test/unit/spec/credentials/token.js +259 -6
  48. package/test/unit/spec/interceptors/auth.js +36 -1
  49. package/test/unit/spec/services/interceptors/service.js +35 -1
  50. package/test/unit/spec/services/services.js +318 -9
  51. package/test/unit/spec/services-v2/services-v2.ts +240 -13
@@ -259,11 +259,11 @@ const Token = WebexPlugin.extend({
259
259
  return Promise.reject(new Error('cannot downscope access token'));
260
260
  }
261
261
 
262
- if (diffScopes(scope, this.config.scope) !== '') {
262
+ const availableScope = this.scope || this.config.scope;
263
+
264
+ if (diffScopes(scope, availableScope) !== '') {
263
265
  return Promise.reject(
264
- new Error(
265
- `new scope (${scope}) is not subset of the available scopes (${this.config.scope})`
266
- )
266
+ new Error(`new scope (${scope}) is not subset of the available scopes (${availableScope})`)
267
267
  );
268
268
  }
269
269
 
@@ -276,7 +276,7 @@ const Token = WebexPlugin.extend({
276
276
  // Ideally, we could depend on the service to communicate this error, but
277
277
  // all we get is "invalid scope", which, to the lay person, implies
278
278
  // something wrong with *one* of the scopes, not the whole thing.
279
- if (scope === sortScope(this.config.scope)) {
279
+ if (scope === sortScope(availableScope)) {
280
280
  return Promise.reject(new Error('token: scope reduction requires a reduced scope'));
281
281
  }
282
282
 
@@ -339,9 +339,12 @@ const Token = WebexPlugin.extend({
339
339
  * {@link config.credentials.refreshCallback()}
340
340
  * @instance
341
341
  * @memberof Token
342
+ * @param {Object} [options={}]
343
+ * @param {string} [options.scope] Scope to request on refresh, if same or narrower than existing scope
344
+ * @param {string} [options.upgradeScope] Scope to request on refresh, if broader than existing scope
342
345
  * @returns {Promise<Token>}
343
346
  */
344
- refresh() {
347
+ refresh({scope, upgradeScope} = {}) {
345
348
  if (!this.canRefresh) {
346
349
  throw new Error('Not enough information available to refresh this access token');
347
350
  }
@@ -353,7 +356,9 @@ const Token = WebexPlugin.extend({
353
356
  throw new Error('Cannot refresh access token without refreshCallback');
354
357
  }
355
358
 
356
- promise = Promise.resolve(this.config.refreshCallback(this.webex, this));
359
+ promise = Promise.resolve(
360
+ this.config.refreshCallback(this.webex, this, {scope, upgradeScope})
361
+ );
357
362
  }
358
363
 
359
364
  return (
@@ -366,6 +371,8 @@ const Token = WebexPlugin.extend({
366
371
  grant_type: 'refresh_token',
367
372
  redirect_uri: this.config.redirect_uri,
368
373
  refresh_token: this.refresh_token,
374
+ ...(scope && {scope}),
375
+ ...(upgradeScope && {upgrade_scope: upgradeScope}),
369
376
  },
370
377
  auth: {
371
378
  user: this.config.client_id,
@@ -409,7 +416,7 @@ const Token = WebexPlugin.extend({
409
416
  }
410
417
 
411
418
  obj.previousToken = this;
412
- obj.scope = this.scope;
419
+ obj.scope = obj.scope || scope || this.scope;
413
420
 
414
421
  return new Token(obj, {parent: this.parent});
415
422
  })
@@ -4,6 +4,8 @@
4
4
 
5
5
  import {Interceptor} from '@webex/http-core';
6
6
 
7
+ import {isCatalogAuthReason} from '../services/catalog-auth';
8
+
7
9
  const trailingSlashes = /(?:^\/)|(?:\/$)/;
8
10
 
9
11
  /**
@@ -47,9 +49,15 @@ export default class ServiceInterceptor extends Interceptor {
47
49
 
48
50
  return options;
49
51
  })
50
- .catch(() =>
51
- Promise.reject(new Error(`service-interceptor: '${service}' is not a known service`))
52
- );
52
+ .catch((error) => {
53
+ if (error && isCatalogAuthReason(error.reason)) {
54
+ return Promise.reject(error);
55
+ }
56
+
57
+ return Promise.reject(
58
+ new Error(`service-interceptor: '${service}' is not a known service`)
59
+ );
60
+ });
53
61
  }
54
62
 
55
63
  /* eslint-disable class-methods-use-this */
@@ -0,0 +1,112 @@
1
+ import {OAuthError} from '../credentials/grant-errors';
2
+
3
+ export const INVALID_ACCESS_TOKEN = 'invalid_access_token';
4
+ export const ACCESS_DENIED = 'access_denied';
5
+
6
+ const catalogAuthFailures = new WeakMap();
7
+ const catalogAuthReplayLimit = /^Failed after \d+ replay attempts$/;
8
+ const reasonByStatus = {
9
+ 401: INVALID_ACCESS_TOKEN,
10
+ 403: ACCESS_DENIED,
11
+ };
12
+
13
+ /**
14
+ * A catalog 401 can arrive as an OAuth refresh failure or the auth replay limit.
15
+ * @param {Error} error
16
+ * @returns {boolean}
17
+ */
18
+ export function isWrappedCatalogAuthFailure(error) {
19
+ return (
20
+ error instanceof OAuthError ||
21
+ (typeof error?.message === 'string' && catalogAuthReplayLimit.test(error.message))
22
+ );
23
+ }
24
+
25
+ /**
26
+ * @param {string} reason
27
+ * @returns {boolean}
28
+ */
29
+ export function isCatalogAuthReason(reason) {
30
+ return reason === INVALID_ACCESS_TOKEN || reason === ACCESS_DENIED;
31
+ }
32
+
33
+ /**
34
+ * Classify a postauth catalog failure.
35
+ * A result is stored. Null means any previously stored failure should be cleared.
36
+ * Network errors and HTTP 5xx stay null.
37
+ * @param {Error} error
38
+ * @returns {{status: number, reason: string}|null}
39
+ */
40
+ export function classifyCatalogAuthFailure(error) {
41
+ const status = error && (error.catalogAuthStatus || error.statusCode || error.status);
42
+ const reason = reasonByStatus[status];
43
+
44
+ if (reason) {
45
+ return {
46
+ status,
47
+ reason,
48
+ };
49
+ }
50
+
51
+ if (isWrappedCatalogAuthFailure(error)) {
52
+ return {
53
+ status: 401,
54
+ reason: INVALID_ACCESS_TOKEN,
55
+ };
56
+ }
57
+
58
+ return null;
59
+ }
60
+
61
+ /**
62
+ * @param {object} services
63
+ * @param {Error} error
64
+ * @returns {void}
65
+ */
66
+ export function recordCatalogAuthFailure(services, error) {
67
+ const authFailure = classifyCatalogAuthFailure(error);
68
+
69
+ if (authFailure) {
70
+ catalogAuthFailures.set(services, authFailure);
71
+
72
+ return;
73
+ }
74
+
75
+ catalogAuthFailures.delete(services);
76
+ }
77
+
78
+ /**
79
+ * @param {object} services
80
+ * @returns {void}
81
+ */
82
+ export function clearCatalogAuthFailure(services) {
83
+ catalogAuthFailures.delete(services);
84
+ }
85
+
86
+ /**
87
+ * @param {object} services
88
+ * @returns {{status: number, reason: string}|null}
89
+ */
90
+ export function getCatalogAuthFailure(services) {
91
+ return catalogAuthFailures.get(services) || null;
92
+ }
93
+
94
+ /**
95
+ * @param {object} services
96
+ * @param {string} fallbackMessage
97
+ * @returns {Error}
98
+ */
99
+ export function serviceLookupError(services, fallbackMessage) {
100
+ const authFailure = getCatalogAuthFailure(services);
101
+
102
+ if (authFailure && isCatalogAuthReason(authFailure.reason)) {
103
+ const authError = new Error(authFailure.reason);
104
+
105
+ authError.reason = authFailure.reason;
106
+ authError.statusCode = authFailure.status;
107
+
108
+ return authError;
109
+ }
110
+
111
+ return new Error(fallbackMessage);
112
+ }
@@ -187,7 +187,7 @@ Related context: [repository architecture](../../../../docs/architecture.md) ·
187
187
  | `SVC-010` | `updateCredentialsConfig` copies the highest-priority `idbroker` and `identity` URLs (trailing slash removed) into credentials config, and sets `authorizeUrl` from idbroker unless an authorization string is configured | The OAuth endpoints must follow the discovered region, not the build-time default | `src/lib/services/services.js` | `test/unit/spec/services/services.js` (idbroker, identity and authorize url cases) | Only one slash is stripped per string | Present |
188
188
  | `SVC-011` | `waitForCatalog('postauth')` with a supertoken present and the group neither collecting nor ready starts collection itself (full init when preauth is not ready, otherwise `updateServices`) instead of waiting | A caller racing the init sequence must not wait for an event that has not been requested | `src/lib/services/services.js` | `test/unit/spec/services/services.js` (initServiceCatalogs paths); `test/integration/spec/services/services.js` | The caller's timeout is ignored on this branch; no direct unit test of the branch | Weak |
189
189
  | `SVC-012` | `ServiceCatalog.waitForCatalog` resolves immediately if the group is ready, otherwise resolves on the group's event or rejects after `timeout` seconds (60 when not a non-negative number) with `services: timeout occured while waiting for '<group>' catalog to populate` | Callers need bounded waiting with a consistent failure | `src/lib/services/service-catalog.js` | `test/integration/spec/services/service-catalog.js` (promise, timeout rejection, resolved once ready) | When already ready, the timer and listener are still created (see Pitfalls) | Present |
190
- | `SVC-013` | `waitForService({name, url, timeout=5})` resolves in this order: the raw discovered link for names in `servicesNotNeedValidation`; the priority URL by name or by URL; when the catalog is ready, the given `url` as-is, else a rejection `services: service '<name>' was not found in any of the catalogs`; otherwise it waits on all three groups and resolves on the first hit, rejecting `services: service '<name>' was not found after waiting` only after all three settle; each not-found rejection reports a client metric | Request building must not fail merely because a catalog is still loading, yet unknown services must fail loudly | `src/lib/services/services.js` | `test/integration/spec/services/services.js` (name, url, name and url; existing, missing, becoming available) | Not unit tested; relies on live U2C | Present |
190
+ | `SVC-013` | `waitForService({name, url, timeout=5})` resolves in this order: the raw discovered link for names in `servicesNotNeedValidation`; the priority URL by name or by URL; when the catalog is ready, the given `url` as-is, else a rejection `services: service '<name>' was not found in any of the catalogs`; otherwise it waits on all three groups and resolves on the first hit, rejecting `services: service '<name>' was not found after waiting` only after all three settle; each not-found rejection reports a client metric. A stored postauth catalog auth failure replaces both not-found messages: `error.message` and `error.reason` are `invalid_access_token` with `error.statusCode` 401, or `access_denied` with `error.statusCode` 403. Every other missing service keeps the current text | Request building must not fail merely because a catalog is still loading, yet unknown services must fail loudly, and a catalog 401 or 403 must stay visible to the caller | `src/lib/services/services.js`, `src/lib/services/catalog-auth.js` | `test/unit/spec/services/services.js` (catalog auth failure), `test/integration/spec/services/services.js` (name, url, name and url; existing, missing, becoming available) | Generic not-found paths rely on live U2C | Present |
191
191
  | `SVC-014` | `getServiceFromUrl` and `isServiceUrl` match a URL to a service when its origin (scheme, host, port) equals the service's default URL origin or an alternate-host URL, and its path equals or extends the service path at a `/` boundary; unparsable input matches nothing; groups are scanned discovery first, override last | A hostname that merely begins with a trusted host, a different port, scheme or path prefix must not be treated as a Webex service, because the result decides whether credentials are attached | `src/lib/services/service-catalog.js` | `test/unit/spec/services/service-catalog.js` (origin and path validation, SECURITY cases), `test/unit/spec/services/services.js`, `test/integration/spec/services/service-catalog.js` | Match result precedence differs from name precedence | Present |
192
192
  | `SVC-015` | `isAllowedDomainUrl` is true only when the URL's hostname is an allowed domain or a subdomain of one, as decided by the domains helper; `hasAllowedDomains` reports whether any entry exists; `setAllowedDomains` and `addAllowedDomains` store canonicalized, de-duplicated entries | Allowed-domain checks gate whether the auth header is attached, so substring or parser-differential matches must not pass | `src/lib/services/service-catalog.js`, `src/lib/domains.ts`, `src/lib/services/services.js` | `test/unit/spec/services/service-catalog.js` (parametrized allowed-domain matching, set/add/get), `test/unit/spec/services/services.js` (isAllowedDomainUrl) | Matching rules themselves are owned by the helper in `src/lib/domains.ts` | Present |
193
193
  | `SVC-016` | `get(name, true)` returns the URL of the best host: hosts with non-positive priority are ignored; without a cluster id only home-cluster hosts qualify; non-failed hosts are preferred; the lowest priority number wins; if every candidate has failed their `failed` flags are cleared and selection restarts; with no usable host the default URL is returned | Failover must degrade gracefully to the default URL and must never get stuck with every host disabled | `src/lib/services/service-url.js` | `test/unit/spec/services/service-url.js` (negative, zero, mixed priorities; reset when all failed; cluster id cases) | None | Present |
@@ -197,7 +197,7 @@ Related context: [repository architecture](../../../../docs/architecture.md) ·
197
197
  | `SVC-020` | `replaceHostFromHostmap` replaces the host of a URI with the first host catalog entry of its host key, and returns the URI unchanged when the host catalog is unset or has no entry | Requests that already carry absolute URLs must still use the discovered host | `src/lib/services/services.js` | `test/unit/spec/services/services.js` (four cases) | None | Present |
198
198
  | `SVC-021` | `HostMapInterceptor.onRequest` rewrites `options.uri` through `replaceHostFromHostmap` when a URI exists and swallows any error, leaving the URI untouched | A malformed or relative URI must not abort the request | `src/lib/interceptors/hostmap.js` | `test/unit/spec/services/interceptors/hostmap.js` | None | Present |
199
199
  | `SVC-022` | `ServiceInterceptor.onRequest` returns options unchanged when `uri` is set; otherwise it maps `api` to `service` (without overriding an explicit `service`), requires both `resource` and `service` (throwing `a \`resource\` parameter is required` or `a valid 'service' parameter is required`), waits for the service honoring `waitForServiceTimeout`, and sets `uri` to the service URL joined with the resource | Callers address services by logical name so that region, override and failover are applied centrally | `src/lib/interceptors/service.js` | `test/unit/spec/services/interceptors/service.js` | None | Present |
200
- | `SVC-023` | When the service cannot be resolved `ServiceInterceptor` rejects with `service-interceptor: '<service>' is not a known service`, discarding the underlying cause | Gives request callers a single recognizable failure | `src/lib/interceptors/service.js` | `test/unit/spec/services/interceptors/service.js` (rejected promise case) | The underlying wait failure (timeout versus not found) is not surfaced | Present |
200
+ | `SVC-023` | When the service cannot be resolved `ServiceInterceptor` rethrows the error unchanged when `error.reason` is `invalid_access_token` or `access_denied`. Every other failure is rejected as `service-interceptor: '<service>' is not a known service`, discarding the underlying cause | A catalog 401 or 403 must reach the request caller; other missing services stay a single recognizable failure | `src/lib/interceptors/service.js`, `src/lib/services/catalog-auth.js` | `test/unit/spec/services/interceptors/service.js` (rejected promise case, catalog auth reasons) | The underlying wait failure (timeout versus not found) is not surfaced | Present |
201
201
  | `SVC-024` | `ServerErrorInterceptor.onResponseError` reacts only to `InternalServerError`, `BadGateway` and `ServiceUnavailable` with a URI and only when developer feature `web-high-availability` is present and truthy; it then submits a `web-ha` client metric, calls `markFailedUrl` and still rejects with the original error; every other case rejects with the original error unchanged | Subsequent retries should use the next host, but only for orgs that enabled high availability, and the error must still reach the caller | `src/lib/interceptors/server-error.js` | `test/unit/spec/services/interceptors/server-error.js` | The retry itself is not performed here; it belongs to the caller or another interceptor | Present |
202
202
  | `SVC-025` | `initServiceCatalogs` resolves the org id, collects the preauth catalog for it, and, when `canAuthorize`, collects the postauth catalog then sets `catalog.isReady`; a postauth failure sets `initFailed` and is swallowed; a failed `getOrgId` or preauth collection rejects | Authenticated users need the full catalog; a failed postauth fetch must not break login | `src/lib/services/services.js` | `test/unit/spec/services/services.js` (initServiceCatalogs, initFailed), `test/integration/spec/services/services.js` | None | Present |
203
203
  | `SVC-026` | By default (`waitForCatalogInit` not true) `services.ready` is set true immediately, and catalog collection starts on the first webex `ready` event: load from cache and finish if warm; with a supertoken run `initServiceCatalogs`; otherwise collect preauth by configured email or by proximity unless `skipPreauthCatalogOnUnauthenticated` is true; failures set `initFailed` and are logged | The historical behavior must not block `webex.ready` on the network | `src/lib/services/services.js` | `test/unit/spec/services/services.js` (initialize ungated cases, skip preauth) | None | Present |
@@ -635,8 +635,8 @@ and never becomes true for an unauthenticated user whose cache is cold.
635
635
  | `validateUser` without email, or without client credentials | Rejection with the message | Fix input or config | Retry | `src/lib/services/services.js` |
636
636
  | U2C request fails | Rejection with the request error; `collecting` cleared | Inspect error | Call again | `src/lib/services/services.js` |
637
637
  | Catalog wait times out | Rejection `services: timeout occured while waiting for '<group>' catalog to populate` | Treat the service as unavailable | Retry later | `src/lib/services/service-catalog.js` |
638
- | Service not found | Rejection `services: service '<name>' was not found in any of the catalogs` or `... after waiting` | Treat as unknown service | Retry after the catalog loads | `src/lib/services/services.js` |
639
- | `ServiceInterceptor` cannot resolve | Rejection `service-interceptor: '<service>' is not a known service` | Check the service name | Retry later | `src/lib/interceptors/service.js` |
638
+ | Service not found | Rejection `services: service '<name>' was not found in any of the catalogs` or `... after waiting`. A stored postauth catalog auth failure instead rejects with `error.message` and `error.reason` `invalid_access_token` and `error.statusCode` 401, or `access_denied` and `error.statusCode` 403 | Treat a catalog 401 or 403 as an authorization failure; treat every other rejection as an unknown service | Retry after the catalog loads, or after the token is replaced | `src/lib/services/services.js`, `src/lib/services/catalog-auth.js` |
639
+ | `ServiceInterceptor` cannot resolve | Rejection `service-interceptor: '<service>' is not a known service`, unless `error.reason` is `invalid_access_token` or `access_denied`, which is rethrown with that message, reason, and statusCode | Check the service name, or handle the catalog auth reason | Retry later | `src/lib/interceptors/service.js`, `src/lib/services/catalog-auth.js` |
640
640
  | `ServiceInterceptor` option error | Synchronous throw of the `resource` or `service` message | Fix the call | None | `src/lib/interceptors/service.js` |
641
641
  | `convertUrlToPriorityHostUrl` or `getServiceUrlFromClusterId` on unknown input | Thrown error `No service associated with url: [...]` or `Could not find service for cluster [...]` | Guard with lookup methods | None | `src/lib/services/services.js` |
642
642
  | Gated init fails or times out | `ready` still true; `initFailed` true; error logged | Check `initFailed` | Call `updateServices` | `src/lib/services/services.js` |
@@ -4,6 +4,12 @@ import {union, forEach} from 'lodash';
4
4
  import WebexPlugin from '../webex-plugin';
5
5
 
6
6
  import METRICS from '../metrics';
7
+ import {
8
+ clearCatalogAuthFailure,
9
+ getCatalogAuthFailure,
10
+ recordCatalogAuthFailure,
11
+ serviceLookupError,
12
+ } from './catalog-auth';
7
13
  import ServiceCatalog from './service-catalog';
8
14
  import ServiceRegistry from './service-registry';
9
15
  import ServiceState from './service-state';
@@ -114,6 +120,42 @@ const Services = WebexPlugin.extend({
114
120
  return this._catalogs.get(this.webex);
115
121
  },
116
122
 
123
+ /**
124
+ * Remember a postauth catalog failure caused by HTTP 401 or 403.
125
+ * 401 means the access token was rejected. 403 means the token can be
126
+ * valid and the caller still has no access. A refresh or replay failure
127
+ * that replaced a catalog 401 is recorded as invalid_access_token.
128
+ * A refresh 403 keeps that original 401 on error.catalogAuthStatus.
129
+ * Other failures clear any previously stored auth failure.
130
+ *
131
+ * @private
132
+ * @param {Error} error
133
+ * @returns {void}
134
+ */
135
+ _recordCatalogAuthFailure(error) {
136
+ recordCatalogAuthFailure(this, error);
137
+ },
138
+
139
+ /**
140
+ * @private
141
+ * @returns {{status: number, reason: string}|null}
142
+ */
143
+ _getCatalogAuthFailure() {
144
+ return getCatalogAuthFailure(this);
145
+ },
146
+
147
+ /**
148
+ * Build the rejection for a service that could not be resolved.
149
+ * A stored catalog auth failure replaces the generic not-found text.
150
+ *
151
+ * @private
152
+ * @param {string} fallbackMessage
153
+ * @returns {Error}
154
+ */
155
+ _serviceLookupError(fallbackMessage) {
156
+ return serviceLookupError(this, fallbackMessage);
157
+ },
158
+
117
159
  /**
118
160
  * Safely access localStorage if available; returns the Storage or null.
119
161
  * @returns {Storage|null}
@@ -401,10 +443,20 @@ const Services = WebexPlugin.extend({
401
443
  catalog.updateServiceUrls(serviceGroup, formattedServiceHostMap);
402
444
  this.updateCredentialsConfig();
403
445
  catalog.status[serviceGroup].collecting = false;
446
+
447
+ // A successful postauth catalog replaces any remembered 401/403.
448
+ // Preauth and signin updates leave that marker alone.
449
+ if (serviceGroup === 'postauth') {
450
+ clearCatalogAuthFailure(this);
451
+ }
404
452
  })
405
453
  .catch((error) => {
406
454
  catalog.status[serviceGroup].collecting = false;
407
455
 
456
+ if (serviceGroup === 'postauth') {
457
+ this._recordCatalogAuthFailure(error);
458
+ }
459
+
408
460
  return Promise.reject(error);
409
461
  });
410
462
  },
@@ -820,7 +872,7 @@ const Services = WebexPlugin.extend({
820
872
  });
821
873
 
822
874
  return Promise.reject(
823
- new Error(`services: service '${name}' was not found in any of the catalogs`)
875
+ this._serviceLookupError(`services: service '${name}' was not found in any of the catalogs`)
824
876
  );
825
877
  }
826
878
 
@@ -843,7 +895,7 @@ const Services = WebexPlugin.extend({
843
895
  this.webex.internal.metrics.submitClientMetrics(METRICS.JS_SDK_SERVICE_NOT_FOUND, {
844
896
  fields: {service_name: name},
845
897
  });
846
- reject(new Error(`services: service '${name}' was not found after waiting`));
898
+ reject(this._serviceLookupError(`services: service '${name}' was not found after waiting`));
847
899
  });
848
900
  });
849
901
  },
@@ -393,7 +393,7 @@ sequenceDiagram
393
393
  Plugin-->>Caller: url unchanged
394
394
  else
395
395
  Plugin->>Metrics: submitClientMetrics(JS_SDK_SERVICE_NOT_FOUND)
396
- Plugin-->>Caller: reject "service '<name>' was not found in any of the catalogs"
396
+ Plugin-->>Caller: reject stored catalog auth reason, else "service '<name>' was not found in any of the catalogs"
397
397
  end
398
398
  else not ready
399
399
  par each of preauth, signin, postauth
@@ -404,7 +404,7 @@ sequenceDiagram
404
404
  Plugin-->>Caller: resolve priority url
405
405
  else all waits settled without a match
406
406
  Plugin->>Metrics: submitClientMetrics(JS_SDK_SERVICE_NOT_FOUND)
407
- Plugin-->>Caller: reject "service '<name>' was not found after waiting"
407
+ Plugin-->>Caller: reject stored catalog auth reason, else "service '<name>' was not found after waiting"
408
408
  end
409
409
  end
410
410
  ```
@@ -539,7 +539,7 @@ classDiagram
539
539
  | `UC-001` Opt in to v2 | Integrator or test | Register `ServicesV2` as the `services` plugin with `replace: true` and the two interceptors, then construct the webex instance; `webex.internal.services` is v2 | Without `replace` the second registration is refused and v1 stays; without the interceptors, requests that use `service` are not resolved | `src/lib/webex-internal-core-plugin-mixin.js`, `test/integration/spec/services-v2/services-v2.js` |
540
540
  | `UC-002` Start up with a token | SDK | Config change seeds discovery; on `ready` (or `loaded` when gated) warm from cache or fetch preauth by org then postauth; `isReady` becomes true; `ready` flips | Postauth failure sets `initFailed`; timeout (gated) finalizes anyway | `src/lib/services-v2/services-v2.ts`, `test/unit/spec/services-v2/services-v2.ts` |
541
541
  | `UC-003` Start up unauthenticated | SDK | Preauth catalog by configured email hash or proximity mode; later sign-in triggers postauth | `skipPreauthCatalogOnUnauthenticated` skips the fetch; failure sets `initFailed` | `src/lib/services-v2/services-v2.ts`, `test/unit/spec/services-v2/services-v2.ts` |
542
- | `UC-004` Send a request by service name | `ServiceInterceptor` | `waitForService` returns the priority URL; the interceptor appends the resource | Not found rejects; the interceptor re-wraps as "is not a known service" | `src/lib/interceptors/service.js`, `src/lib/services-v2/services-v2.ts` |
542
+ | `UC-004` Send a request by service name | `ServiceInterceptor` | `waitForService` returns the priority URL; the interceptor appends the resource | A stored postauth catalog auth failure rejects with `error.message` and `error.reason` `invalid_access_token` and `error.statusCode` 401, or `access_denied` and `error.statusCode` 403, and the interceptor rethrows that error. Every other missing service rejects with the not-found text, which the interceptor re-wraps as "is not a known service" | `src/lib/interceptors/service.js`, `src/lib/services/catalog-auth.js`, `src/lib/services-v2/services-v2.ts` |
543
543
  | `UC-005` Decide whether to send a token to a URL | Auth interceptor | `getServiceFromUrl` match, else allowed-domain match when `validateDomains` is on | Similar-looking hosts and prefix paths are rejected by the matcher | `src/interceptors/auth.js`, `test/unit/spec/interceptors/auth.js`, `test/unit/spec/services-v2/service-catalog.ts` |
544
544
  | `UC-006` Fail over after a server error | Error interceptor | `markFailedUrl` marks the host and returns the next base URL | Unknown URL returns `undefined`; reset behavior is in the Failover state diagram | `src/lib/interceptors/server-error.js`, `test/unit/spec/services-v2/service-detail.ts`, `test/integration/spec/services-v2/services-v2.js` |
545
545
  | `UC-007` React to a cluster move | Mercury | `switchActiveClusterIds` or `invalidateCache` updates the active map or refetches | Missing cluster refetches; older timestamp is ignored | `src/lib/services-v2/services-v2.ts`, `test/unit/spec/services-v2/services-v2.ts` |
@@ -663,7 +663,7 @@ stateDiagram-v2
663
663
  | `validateUser` without email or without client credentials | Rejection with the message | Fix input or config | Retry | `src/lib/services-v2/services-v2.ts` |
664
664
  | U2C request fails | Rejection with the request error; `collecting` cleared | Inspect error | Call again | `src/lib/services-v2/services-v2.ts` |
665
665
  | Catalog wait times out | Rejection `services: timeout occured while waiting for '<group>' catalog to populate` | Treat as unavailable | Retry later | `src/lib/services-v2/service-catalog.ts` |
666
- | Service not found | Rejection `services: service '<name>' was not found in any of the catalogs` or `... after waiting`, plus a `JS_SDK_SERVICE_NOT_FOUND` metric | Treat as unknown | Retry after the catalog loads | `src/lib/services-v2/services-v2.ts` |
666
+ | Service not found | Rejection `services: service '<name>' was not found in any of the catalogs` or `... after waiting`, plus a `JS_SDK_SERVICE_NOT_FOUND` metric. A stored postauth catalog auth failure instead rejects with `error.message` and `error.reason` `invalid_access_token` and `error.statusCode` 401, or `access_denied` and `error.statusCode` 403 | Treat a catalog 401 or 403 as an authorization failure; treat every other rejection as an unknown service | Retry after the catalog loads, or after the token is replaced | `src/lib/services-v2/services-v2.ts`, `src/lib/services/catalog-auth.js` |
667
667
  | `convertUrlToPriorityHostUrl` or `getServiceUrlFromClusterId` on unknown input | Thrown `No service associated with url: [...]` or `Could not find service for cluster [...]` | Guard with lookups; `replaceHostFromHostmap` already swallows | None | `src/lib/services-v2/services-v2.ts` |
668
668
  | `markFailedUrl` with an unparsable URL | Thrown `TypeError` from `new URL` | Pass a full URL | None | `src/lib/services-v2/service-detail.ts` |
669
669
  | Gated init fails or times out | `ready` still true; `initFailed` true; error logged | Check `initFailed` | Call `updateServices` | `src/lib/services-v2/services-v2.ts` |
@@ -7,6 +7,12 @@ import METRICS from '../metrics';
7
7
  import ServiceCatalog from './service-catalog';
8
8
  import fedRampServices from './service-fed-ramp';
9
9
  import {COMMERCIAL_ALLOWED_DOMAINS} from '../constants';
10
+ import {
11
+ clearCatalogAuthFailure,
12
+ getCatalogAuthFailure,
13
+ recordCatalogAuthFailure,
14
+ serviceLookupError,
15
+ } from '../services/catalog-auth';
10
16
  import {matchesCatalogUrl} from '../services/service-catalog';
11
17
  import {
12
18
  ActiveServices,
@@ -78,6 +84,36 @@ const Services = WebexPlugin.extend({
78
84
  return this._catalogs.get(this.webex);
79
85
  },
80
86
 
87
+ /**
88
+ * Remember a postauth catalog failure caused by HTTP 401 or 403.
89
+ * Other failures clear any previously stored auth failure.
90
+ * @private
91
+ * @param {Error} error
92
+ * @returns {void}
93
+ */
94
+ _recordCatalogAuthFailure(error) {
95
+ recordCatalogAuthFailure(this, error);
96
+ },
97
+
98
+ /**
99
+ * @private
100
+ * @returns {{status: number, reason: string}|null}
101
+ */
102
+ _getCatalogAuthFailure() {
103
+ return getCatalogAuthFailure(this);
104
+ },
105
+
106
+ /**
107
+ * Build the rejection for a service that could not be resolved.
108
+ * A stored catalog auth failure replaces the generic not-found text.
109
+ * @private
110
+ * @param {string} fallbackMessage
111
+ * @returns {Error}
112
+ */
113
+ _serviceLookupError(fallbackMessage: string) {
114
+ return serviceLookupError(this, fallbackMessage);
115
+ },
116
+
81
117
  /**
82
118
  * Safely access localStorage if available; returns the Storage or null.
83
119
  * @returns {Storage | null}
@@ -357,10 +393,20 @@ const Services = WebexPlugin.extend({
357
393
  this._cacheCatalog(serviceGroup, serviceHostMap, selectionMeta);
358
394
  this.updateCredentialsConfig();
359
395
  catalog.status[serviceGroup].collecting = false;
396
+
397
+ // A successful postauth catalog replaces any remembered 401/403.
398
+ // Preauth and signin updates leave that marker alone.
399
+ if (serviceGroup === 'postauth') {
400
+ clearCatalogAuthFailure(this);
401
+ }
360
402
  })
361
403
  .catch((error) => {
362
404
  catalog.status[serviceGroup].collecting = false;
363
405
 
406
+ if (serviceGroup === 'postauth') {
407
+ this._recordCatalogAuthFailure(error);
408
+ }
409
+
364
410
  return Promise.reject(error);
365
411
  });
366
412
  },
@@ -842,7 +888,7 @@ const Services = WebexPlugin.extend({
842
888
  });
843
889
 
844
890
  return Promise.reject(
845
- new Error(`services: service '${name}' was not found in any of the catalogs`)
891
+ this._serviceLookupError(`services: service '${name}' was not found in any of the catalogs`)
846
892
  );
847
893
  }
848
894
 
@@ -865,7 +911,7 @@ const Services = WebexPlugin.extend({
865
911
  this.webex.internal.metrics.submitClientMetrics(METRICS.JS_SDK_SERVICE_NOT_FOUND, {
866
912
  fields: {service_name: name},
867
913
  });
868
- reject(new Error(`services: service '${name}' was not found after waiting`));
914
+ reject(this._serviceLookupError(`services: service '${name}' was not found after waiting`));
869
915
  });
870
916
  });
871
917
  },
@@ -16,7 +16,7 @@ import uuid from 'uuid';
16
16
  * @returns {string} e.g. `Collabctg+webex-js-sdk-1a2b3c4d5e6f7a8b9c0d@gmail.com`
17
17
  */
18
18
  export function createActivationEmail(): string {
19
- return `Collabctg+webex-js-sdk-${uuid.v4().replace(/-/g, '').slice(0, 20)}@gmail.com`;
19
+ return `collabctg+webex-js-sdk-${uuid.v4().replace(/-/g, '').slice(0, 20)}@gmail.com`;
20
20
  }
21
21
 
22
22
  export default createActivationEmail;
@@ -110,7 +110,9 @@ describe('webex-core', () => {
110
110
  });
111
111
  });
112
112
 
113
- browserOnly(it)('throws without a refresh callback', async () => {
113
+ // FIXME: this test can never pass (both branches assert(false)) and, in browsers,
114
+ // refresh() now resolves without a refreshCallback, so the expectation needs revisiting.
115
+ browserOnly(it.skip)('throws without a refresh callback', async () => {
114
116
  const webex = new WebexCore({
115
117
  credentials: user.token,
116
118
  });
@@ -7,6 +7,7 @@ import {assert} from '@webex/test-helper-chai';
7
7
  import testUsers from '@webex/test-helper-test-users';
8
8
  import WebexCore, {filterScope} from '@webex/webex-core';
9
9
  import refreshCallback from '@webex/test-helper-refresh-callback';
10
+ import sinon from 'sinon';
10
11
 
11
12
  /* eslint camelcase: [0] */
12
13
 
@@ -89,6 +90,13 @@ describe('webex-core', () => {
89
90
  describe('#revoke()', () => {
90
91
  it('revokes the token', () => {
91
92
  webex = new WebexCore({credentials: user.token});
93
+ // Once revoked, every metrics POST fails to downscope the token and submits a
94
+ // JS_SDK_CREDENTIALS_DOWNSCOPE_FAILED metric, which is itself POSTed, looping forever
95
+ // and keeping the node process alive after the suite finishes. The metrics plugin is
96
+ // only registered when another spec file (e.g. via internal-plugin-device) imports it.
97
+ if (webex.internal.metrics) {
98
+ sinon.stub(webex.internal.metrics, 'submitClientMetrics');
99
+ }
92
100
 
93
101
  return webex.credentials.supertoken.revoke().then(() => {
94
102
  assert.isUndefined(webex.credentials.supertoken.access_token);
@@ -26,6 +26,11 @@ describe('webex-core', () => {
26
26
  setTimeout(() => {
27
27
  webexUser = user;
28
28
  webex = new WebexCore({credentials: user.token});
29
+ // Tests below replace the postauth catalog with fixtures that lack `metrics`.
30
+ // Any client metric from this instance then fails waitForService('metrics'),
31
+ // which submits JS_SDK_SERVICE_NOT_FOUND, which is POSTed in turn - forever,
32
+ // keeping the node process alive after the suite finishes.
33
+ sinon.stub(webex.internal.metrics, 'submitClientMetrics');
29
34
  services = webex.internal.services;
30
35
  catalog = services._getCatalog();
31
36
  resolve();
@@ -57,12 +57,13 @@ describe('webex-core', () => {
57
57
 
58
58
  describe('#refresh()', () => {
59
59
  browserOnly(it)('refreshes the access_token', () => {
60
- const token = makeToken();
60
+ const token = makeToken({scope: 'scope1'});
61
61
 
62
62
  webex.config.credentials.refreshCallback = sinon.stub().returns(
63
63
  Promise.resolve({
64
64
  access_token: 'AT2',
65
65
  expires_in: 10000,
66
+ scope: 'scope1',
66
67
  token_type: 'Fake',
67
68
  })
68
69
  );
@@ -73,10 +74,14 @@ describe('webex-core', () => {
73
74
 
74
75
  return token.refresh().then((token2) => {
75
76
  assert.equal(token2.access_token, 'AT2');
77
+ assert.equal(token2.scope, 'scope1');
78
+ assert.calledOnceWithExactly(webex.config.credentials.refreshCallback, webex, token, {
79
+ scope: undefined,
80
+ upgradeScope: undefined,
81
+ });
76
82
  });
77
83
  });
78
84
 
79
-
80
85
  browserOnly(it)('revokes the previous token when set', () => {
81
86
  const token = makeToken();
82
87
 
@@ -1078,6 +1078,85 @@ describe('webex-core', () => {
1078
1078
  });
1079
1079
 
1080
1080
  describe('#refresh()', () => {
1081
+ [
1082
+ {
1083
+ description: 'requests configured scopes missing from the supertoken',
1084
+ canUpgradeScope: true,
1085
+ configuredScope: 'scope1 scope2',
1086
+ tokenScope: 'scope1',
1087
+ expectedOptions: {scope: undefined, upgradeScope: 'scope1 scope2'},
1088
+ },
1089
+ {
1090
+ description: 'narrows a broader supertoken to the configured scope',
1091
+ canUpgradeScope: true,
1092
+ configuredScope: 'scope1',
1093
+ tokenScope: 'scope1 scope2',
1094
+ expectedOptions: {scope: 'scope1', upgradeScope: undefined},
1095
+ },
1096
+ {
1097
+ description:
1098
+ 'sends scope when the configured and granted scopes match in a different order',
1099
+ canUpgradeScope: true,
1100
+ configuredScope: 'scope2 scope1',
1101
+ tokenScope: 'scope1 scope2',
1102
+ expectedOptions: {scope: 'scope2 scope1', upgradeScope: undefined},
1103
+ },
1104
+ {
1105
+ description: 'omits scope and upgrade scope when scope upgrading is disabled',
1106
+ canUpgradeScope: false,
1107
+ configuredScope: 'scope1 scope2',
1108
+ tokenScope: 'scope1',
1109
+ expectedOptions: {scope: undefined, upgradeScope: undefined},
1110
+ },
1111
+ {
1112
+ description: 'does not narrow scope when scope upgrading is disabled',
1113
+ canUpgradeScope: false,
1114
+ configuredScope: 'scope1',
1115
+ tokenScope: 'scope1 scope2',
1116
+ expectedOptions: {scope: undefined, upgradeScope: undefined},
1117
+ },
1118
+ {
1119
+ description: 'omits scope and upgrade scope when no scope is configured',
1120
+ canUpgradeScope: true,
1121
+ configuredScope: undefined,
1122
+ tokenScope: 'scope1 scope2',
1123
+ expectedOptions: {scope: undefined, upgradeScope: undefined},
1124
+ },
1125
+ ].forEach(({description, canUpgradeScope, configuredScope, tokenScope, expectedOptions}) => {
1126
+ it(description, () => {
1127
+ const webex = new MockWebex({
1128
+ children: {
1129
+ metrics: Metrics,
1130
+ },
1131
+ });
1132
+ const credentials = new Credentials(undefined, {parent: webex});
1133
+
1134
+ webex.trigger('change:config');
1135
+ credentials.config.canUpgradeScope = canUpgradeScope;
1136
+ credentials.config.scope = configuredScope;
1137
+
1138
+ const st = makeToken(webex, {
1139
+ access_token: 'ST',
1140
+ refresh_token: 'RT',
1141
+ scope: tokenScope,
1142
+ });
1143
+ const st2 = makeToken(webex, {
1144
+ access_token: 'ST2',
1145
+ refresh_token: 'RT2',
1146
+ scope: configuredScope || tokenScope,
1147
+ });
1148
+
1149
+ sinon.stub(st, 'refresh').resolves(st2);
1150
+ sinon.stub(credentials, 'scheduleRefresh');
1151
+ sinon.stub(webex.internal.metrics, 'submitClientMetrics');
1152
+ credentials.supertoken = st;
1153
+
1154
+ return credentials.refresh().then(() => {
1155
+ assert.calledOnceWithExactly(st.refresh, expectedOptions);
1156
+ });
1157
+ });
1158
+ });
1159
+
1081
1160
  it('refreshes and downscopes the supertoken, and revokes previous tokens', () => {
1082
1161
  const webex = new MockWebex({
1083
1162
  children: {