Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
test(oauth): cover the OAuth console code to 100%
Ronald A. Richardson1ab29ecc3891
diff --git a/console/tests/integration/components/account/connected-accounts-test.js b/console/tests/integration/components/account/connected-accounts-test.jsindex d80e8ed6..75028e42 100644--- a/console/tests/integration/components/account/connected-accounts-test.js+++ b/console/tests/integration/components/account/connected-accounts-test.js@@ -156,4 +156,42 @@ module('Integration | Component | account/connected-accounts', function (hooks)assert.strictEqual(captured.instance.messageFor({ code: 'something-else' }), 'auth.login.oauth.errors.generic');assert.strictEqual(this.errors.length, 1);});++ test('a link the API refuses is explained in plain language', async function (assert) {+ const captured = captureComponent(this.owner, 'account/connected-accounts', ConnectedAccountsComponent);+ await render(hbs`<Account::ConnectedAccounts />`);+ const oauth = this.owner.lookup('service:oauth');++ oauth.startLink = () => Promise.reject({ payload: { code: 'already_linked' } });+ await captured.instance.link.perform({ id: 'github' });++ oauth.startLink = () => Promise.reject(new Error('something unexpected'));+ await captured.instance.link.perform({ id: 'github' });++ assert.deepEqual(this.errors, ['That provider is already linked to your account.', 'We could not complete that sign-in. Please try again.']);+ });++ test('an empty response leaves an empty panel that assumes a password is set', async function (assert) {+ const captured = captureComponent(this.owner, 'account/connected-accounts', ConnectedAccountsComponent);+ await render(hbs`<Account::ConnectedAccounts />`);+ const component = captured.instance;++ component.apply();++ assert.deepEqual(component.identities, []);+ assert.deepEqual(component.available, []);+ assert.true(component.hasPassword);+ assert.false(component.isVisible, 'nothing to show');+ });++ test('it starts empty, unloaded, and assuming a password is set', function (assert) {+ // Tracked defaults run lazily on first read. Each of these is assigned before it is+ // ever read in normal use, so read them fresh here to pin the defaults.+ const component = Object.create(ConnectedAccountsComponent.prototype);++ assert.deepEqual(component.identities, []);+ assert.deepEqual(component.available, []);+ assert.true(component.hasPassword);+ assert.false(component.isLoaded);+ });});diff --git a/console/tests/integration/components/configure/oauth-test.js b/console/tests/integration/components/configure/oauth-test.jsindex ec3b9dc6..fd2b7561 100644--- a/console/tests/integration/components/configure/oauth-test.js+++ b/console/tests/integration/components/configure/oauth-test.js@@ -76,13 +76,23 @@ module('Integration | Component | configure/oauth', function (hooks) {this.checkResult = { configured: false, verified: false, problem: 'invalid_signing_key', message: 'The signing key could not be used to mint a client secret.' };const self = this;+ this.serverErrors = [];+ this.failures = {};+class FetchStub extends Service {- get() {+ get(path) {+ if (self.failures[path]) {+ return Promise.reject(self.failures[path]);+ }return Promise.resolve(JSON.parse(JSON.stringify(CONFIG)));}post(path, payload) {self.posted.push({ path, payload });+ if (self.failures[path]) {+ return Promise.reject(self.failures[path]);+ }+if (path === 'settings/test-oauth-config') {return Promise.resolve({ provider: payload.provider, ...self.checkResult });}@@ -93,7 +103,9 @@ module('Integration | Component | configure/oauth', function (hooks) {class NotificationsStub extends Service {success() {}error() {}- serverError() {}+ serverError(error) {+ self.serverErrors.push(error);+ }}this.owner.register('service:fetch', FetchStub);@@ -278,4 +290,86 @@ module('Integration | Component | configure/oauth', function (hooks) {assert.true(captured.instance.canToggleProvider('google'), 'google is enabled in the fixture');});++ test('a configuration that fails to load is reported', async function (assert) {+ const failure = new Error('settings unavailable');+ this.failures['settings/oauth-config'] = failure;++ await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);++ assert.deepEqual(this.serverErrors, [failure]);+ });++ test('a save the server refuses is reported and leaves the form as it was', async function (assert) {+ const captured = captureComponent(this.owner, 'configure/oauth', ConfigureOauthComponent);+ await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);+ const failure = { code: 'oauth_provider_check_failed', message: 'Google rejected these credentials.' };+ this.failures['settings/oauth-config'] = failure;++ await captured.instance.save.perform();++ assert.deepEqual(this.serverErrors, [failure]);+ assert.strictEqual(captured.instance.values.google.client_id, 'google-client-id', 'nothing was reset');+ });++ test('a check that cannot reach the server is reported', async function (assert) {+ const captured = captureComponent(this.owner, 'configure/oauth', ConfigureOauthComponent);+ await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);+ const failure = new Error('network down');+ this.failures['settings/test-oauth-config'] = failure;++ await captured.instance.test.perform('google');++ assert.deepEqual(this.serverErrors, [failure]);+ assert.notOk(captured.instance.testResults.google, 'no result is recorded');+ });++ test('the offer toggle switches a provider on and off', async function (assert) {+ const captured = captureComponent(this.owner, 'configure/oauth', ConfigureOauthComponent);+ await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);+ const component = captured.instance;++ component.toggleProvider('google', false);+ assert.false(component.isProviderEnabled('google'));++ component.toggleProvider('google', true);+ assert.true(component.isProviderEnabled('google'));+ });++ test('fields fall back to their key, no placeholder and no help, and a provider may have no schema', function (assert) {+ const component = Object.create(ConfigureOauthComponent.prototype);++ assert.deepEqual(component.fieldsFor({ id: 'okta', schema: { domain: {} } }), [+ { key: 'domain', label: 'domain', placeholder: '', help: null, secret: false, required: false, multiline: false },+ ]);+ assert.deepEqual(component.fieldsFor({ id: 'okta' }), []);+ assert.deepEqual(component.fieldsFor(undefined), []);+ });++ test('a saved secret with no hint still says it is saved', async function (assert) {+ const captured = captureComponent(this.owner, 'configure/oauth', ConfigureOauthComponent);+ await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);+ const component = captured.instance;+ component.secretStatus = { google: { client_secret: { configured: true, hint: null } } };++ assert.strictEqual(component.placeholderFor('google', { key: 'client_secret', secret: true, placeholder: 'GOCSPX-…' }), 'Saved (••••) — leave blank to keep');+ assert.strictEqual(component.placeholderFor('apple', { key: 'private_key', secret: true, placeholder: '-----BEGIN' }), '-----BEGIN', 'nothing saved: the example');+ });++ test('it starts from empty settings with sign-in, sign-ups and automatic linking on', function (assert) {+ // Tracked defaults run lazily on first read. Each of these is assigned before it is+ // ever read in normal use, so read them fresh here to pin the defaults.+ const component = Object.create(ConfigureOauthComponent.prototype);++ assert.true(component.enabled);+ assert.true(component.allowRegistration);+ assert.true(component.autoLink);+ assert.deepEqual(component.providers, []);+ assert.deepEqual(component.values, {});+ assert.deepEqual(component.secretStatus, {});+ assert.deepEqual(component.redirectUris, {});+ assert.deepEqual(component.testResults, {});+ assert.deepEqual(component.savedEnabled, {});+ assert.deepEqual(component.panelOpen, {});+ });});diff --git a/console/tests/integration/components/onboarding/form-test.js b/console/tests/integration/components/onboarding/form-test.jsindex 43fb2530..18875169 100644--- a/console/tests/integration/components/onboarding/form-test.js+++ b/console/tests/integration/components/onboarding/form-test.js@@ -406,4 +406,14 @@ module('Integration | Component | onboarding/form | onboard', function (hooks) {assert.deepEqual(started, ['google']);});++ test('a sign-up starts with no provider intent, nothing started and no verified email', function (assert) {+ // Tracked defaults run lazily on first read. Each of these is assigned before it is+ // ever read in normal use, so read them fresh here to pin the defaults.+ const component = Object.create(OnboardingFormComponent.prototype);++ assert.strictEqual(component.oauthIntent, null);+ assert.false(component.isStartingProvider);+ assert.false(component.emailVerifiedByProvider);+ });});diff --git a/console/tests/unit/controllers/auth/oauth-callback-test.js b/console/tests/unit/controllers/auth/oauth-callback-test.jsindex 09099608..24a955b1 100644--- a/console/tests/unit/controllers/auth/oauth-callback-test.js+++ b/console/tests/unit/controllers/auth/oauth-callback-test.js@@ -1,6 +1,7 @@import { module, test } from 'qunit';import { setupTest } from '@fleetbase/console/tests/helpers';import Service from '@ember/service';+import AuthOauthCallbackController from '@fleetbase/console/controllers/auth/oauth-callback';module('Unit | Controller | auth/oauth-callback', function (hooks) {setupTest(hooks);@@ -269,4 +270,24 @@ module('Unit | Controller | auth/oauth-callback', function (hooks) {assert.deepEqual(this.notified.errors, ['auth.login.oauth.errors.access-denied']);assert.deepEqual(this.transitions, [['console.account.auth']]);});++ test('it reads the error code from wherever the rejection carries it', function (assert) {+ const controller = this.controller;++ assert.strictEqual(controller.codeFrom(null), 'exchange_failed', 'no error at all');+ assert.strictEqual(controller.codeFrom({ code: 'link_required' }), 'link_required', 'a raw error body');+ assert.strictEqual(controller.codeFrom({ payload: { code: 'provider_disabled' } }), 'provider_disabled', 'an adapter-style error');+ assert.strictEqual(controller.codeFrom({ json: { code: 'rate_limited' } }), 'rate_limited', 'a fetch-style error');+ assert.strictEqual(controller.codeFrom({ code: 42 }), 'exchange_failed', 'a code that is not a string');+ assert.strictEqual(controller.codeFrom(new Error('Network down')), 'exchange_failed', 'a plain error with no code');+ });++ test('it starts exchanging, with no error', function (assert) {+ // Tracked defaults run lazily on first read. Each of these is assigned before it is+ // ever read in normal use, so read them fresh here to pin the defaults.+ const controller = Object.create(AuthOauthCallbackController.prototype);++ assert.strictEqual(controller.error, null);+ assert.true(controller.isExchanging);+ });});diff --git a/console/tests/unit/routes/auth/oauth-callback-test.js b/console/tests/unit/routes/auth/oauth-callback-test.jsindex f64ca88f..45be39f1 100644--- a/console/tests/unit/routes/auth/oauth-callback-test.js+++ b/console/tests/unit/routes/auth/oauth-callback-test.js@@ -52,4 +52,31 @@ module('Unit | Route | auth/oauth-callback', function (hooks) {assert.strictEqual(route.model().intent, 'link');});++ test('it takes down the boot loader on entry', function (assert) {+ const element = document.createElement('div');+ element.id = 'boot-loader';+ document.body.appendChild(element);+ const route = this.owner.lookup('route:auth/oauth-callback');++ try {+ route.beforeModel();++ assert.strictEqual(document.getElementById('boot-loader'), null, 'the boot loader is gone');+ } finally {+ document.getElementById('boot-loader')?.remove();+ }+ });++ test('it hands the fragment payload to the controller to redeem', function (assert) {+ const route = this.owner.lookup('route:auth/oauth-callback');+ const started = [];+ const controller = { start: (payload) => started.push(payload) };+ const payload = { handoff: 'abc123', error: null, returnTo: null, intent: null };++ route.setupController(controller, payload);++ assert.deepEqual(started, [payload]);+ assert.strictEqual(controller.model, payload, 'the model is still set on the controller');+ });});diff --git a/console/tests/unit/services/oauth-test.js b/console/tests/unit/services/oauth-test.jsindex 61dbf517..9992613e 100644--- a/console/tests/unit/services/oauth-test.js+++ b/console/tests/unit/services/oauth-test.js@@ -3,6 +3,7 @@ import { setupTest } from '@fleetbase/console/tests/helpers';import Service from '@ember/service';import window from 'ember-window-mock';import config from '@fleetbase/console/config/environment';+import OauthService from '@fleetbase/console/services/oauth';module('Unit | Service | oauth', function (hooks) {setupTest(hooks);@@ -12,11 +13,21 @@ module('Unit | Service | oauth', function (hooks) {this.getCalls = [];this.getResult = () => Promise.resolve({ providers: [{ id: 'google', label: 'Google', icon: 'google' }] });+ this.requests = [];+class FetchStub extends Service {get(path) {self.getCalls.push(path);return self.getResult();}+ post(path, body, options) {+ self.requests.push(['post', path, body, options]);+ return Promise.resolve(path.endsWith('/link') ? { redirect_url: 'https://accounts.google.com/o/oauth2/auth?state=abc' } : { identities: [] });+ }+ delete(path, body, options) {+ self.requests.push(['delete', path, body, options]);+ return Promise.resolve({ identities: [] });+ }}this.owner.register('service:fetch', FetchStub);@@ -125,4 +136,76 @@ module('Unit | Service | oauth', function (hooks) {service.clearRegistration();assert.strictEqual(service.registration, null);});++ test('a second load while one is in flight reuses it instead of fetching again', async function (assert) {+ let release;+ this.getResult = () => new Promise((resolve) => (release = () => resolve({ providers: [{ id: 'google' }], allow_registration: true })));+ const service = this.owner.lookup('service:oauth');++ const first = service.loadProviders();+ const second = await service.loadProviders();++ assert.deepEqual(second, [], 'the second call returns what is loaded so far');+ release();+ await first;+ assert.deepEqual(this.getCalls, ['auth/oauth/providers'], 'only one request was made');+ assert.deepEqual(service.providers, [{ id: 'google' }]);+ });++ test('with no configured API host it uses the page origin', function (assert) {+ const service = this.owner.lookup('service:oauth');+ const host = config.API.host;++ try {+ config.API.host = '';+ assert.strictEqual(service.apiHost, `${window.location.protocol}//${window.location.host}`);+ } finally {+ config.API.host = host;+ }+ });++ test('it loads the signed-in user identities', async function (assert) {+ this.getResult = () => Promise.resolve({ identities: [], available: [], has_password: true });+ const service = this.owner.lookup('service:oauth');++ assert.deepEqual(await service.loadIdentities(), { identities: [], available: [], has_password: true });+ assert.deepEqual(this.getCalls, ['auth/oauth/identities']);+ });++ test('starting a link asks the API for the provider URL and navigates to it', async function (assert) {+ const service = this.owner.lookup('service:oauth');++ await service.startLink('google');++ // The endpoint needs the bearer token, so it is fetched rather than navigated to.+ assert.deepEqual(this.requests, [['post', 'auth/oauth/google/link', {}, { rawError: true }]]);+ assert.strictEqual(String(window.location.href), 'https://accounts.google.com/o/oauth2/auth?state=abc');+ });++ test('completing a link sends the handoff code to the protected endpoint', async function (assert) {+ const service = this.owner.lookup('service:oauth');++ await service.completeLink('handoff-code');++ assert.deepEqual(this.requests, [['post', 'auth/oauth/link/complete', { code: 'handoff-code' }, { rawError: true }]]);+ });++ test('unlinking deletes the provider, with its id escaped', async function (assert) {+ const service = this.owner.lookup('service:oauth');++ await service.unlink('../evil');++ assert.deepEqual(this.requests, [['delete', 'auth/oauth/..%2Fevil/unlink', {}, { rawError: true }]]);+ });++ test('it starts with no providers, sign-ups closed and nothing in flight', function (assert) {+ // Tracked defaults run lazily on first read. Each of these is assigned before it is+ // ever read in normal use, so read them fresh here to pin the defaults.+ const service = Object.create(OauthService.prototype);++ assert.deepEqual(service.providers, []);+ assert.false(service.allowsRegistration);+ assert.false(service.isLoading);+ assert.strictEqual(service.registration, null);+ });});