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
fix(oauth): stop panels collapsing, check unsaved values, gate the toggle
Ronald A. Richardson9e623cf88d36
diff --git a/console/app/components/configure/oauth.hbs b/console/app/components/configure/oauth.hbsindex 9f973451..14dfddd7 100644--- a/console/app/components/configure/oauth.hbs+++ b/console/app/components/configure/oauth.hbs@@ -1,7 +1,7 @@<ContentPanel @title="Sign-in with OAuth" @open={{true}} @wrapperClass="bordered-classic"><p class="text-sm text-gray-600 dark:text-gray-400 mb-4">- Let people sign in with an existing account from a provider. Provider credentials are stored encrypted and are never sent back to the- browser. Leave a secret field blank to keep the saved value.+ Let people sign in with an existing account from a provider. Provider credentials are stored encrypted and are never sent back to the browser. Leave a secret field blank to keep the+ saved value.</p><InputGroup><Toggle@@ -22,13 +22,19 @@</ContentPanel>{{#each this.providers as |provider|}}- <ContentPanel @title={{provider.label}} @open={{this.isProviderEnabled provider.id}} @wrapperClass="bordered-classic">+ <ContentPanel @title={{provider.label}} @open={{get this.panelOpen provider.id}} @wrapperClass="bordered-classic"><InputGroup><Toggle@isToggled={{this.isProviderEnabled provider.id}}@onToggle={{fn this.toggleProvider provider.id}}+ @disabled={{not (this.canToggleProvider provider.id)}}@label={{concat "Offer " provider.label " on the sign-in page"}}/>+ {{#let (this.toggleHelp provider) as |hint|}}+ {{#if hint}}+ <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{{hint}}</p>+ {{/if}}+ {{/let}}</InputGroup>{{#each (this.fieldsFor provider) as |field|}}@@ -66,11 +72,11 @@{{#if result}}<divclass="flex flex-row items-center rounded-lg border- {{if result.configured 'border-green-900 bg-green-800 text-green-100' 'border-red-900 bg-red-800 text-red-100'}}+ {{if result.verified 'border-green-900 bg-green-800 text-green-100' 'border-red-900 bg-red-800 text-red-100'}}shadow-sm my-2 px-4 py-2">- <FaIcon @icon={{if result.configured "circle-check" "triangle-exclamation"}} class="mr-1.5" />- <span class="text-xs">{{this.testMessage result}}</span>+ <FaIcon @icon={{if result.verified "circle-check" "triangle-exclamation"}} class="mr-1.5" />+ <span class="text-xs">{{result.message}}</span></div>{{/if}}{{/let}}@@ -81,4 +87,4 @@<EmberWormhole @to="next-view-section-subheader-actions"><Button @type="primary" @size="sm" @icon="save" @text="Save Changes" @onClick={{perform this.save}} @disabled={{this.save.isRunning}} @isLoading={{this.save.isRunning}} />-</EmberWormhole>+</EmberWormhole>\ No newline at end of filediff --git a/console/app/components/configure/oauth.js b/console/app/components/configure/oauth.jsindex 53982c5d..4b32cf4b 100644--- a/console/app/components/configure/oauth.js+++ b/console/app/components/configure/oauth.js@@ -45,8 +45,31 @@ export default class ConfigureOauthComponent extends Component {@tracked redirectUris = {};+ /**+ * The last check result per provider. Cleared when that provider's credentials+ * are edited, because it no longer describes what is in the form.+ *+ * @var {Object}+ */@tracked testResults = {};+ /**+ * Which providers are live on the server, as of the last load or save. A live+ * provider can always be switched off; switching one on takes a passing check.+ *+ * @var {Object}+ */+ @tracked savedEnabled = {};++ /**+ * Whether each provider's panel starts open. Set once, on load: binding @open to+ * anything that changes as the admin types makes ContentPanel reset its open state+ * on every keystroke.+ *+ * @var {Object}+ */+ @tracked panelOpen = {};+constructor() {super(...arguments);this.load.perform();@@ -84,6 +107,23 @@ export default class ConfigureOauthComponent extends Component {return this.values[providerId]?.enabled === true;}+ /**+ * Switching a provider off is always allowed. Switching one on needs the provider+ * to have accepted the credentials currently in the form — the server enforces the+ * same rule on save, this just says so before the admin gets that far.+ */+ @action canToggleProvider(providerId) {+ return this.isProviderEnabled(providerId) || this.testResults[providerId]?.verified === true;+ }++ @action toggleHelp(provider) {+ if (this.canToggleProvider(provider.id)) {+ return null;+ }++ return `Run "Check configuration" to confirm ${provider.label} accepts these credentials before offering it.`;+ }+@action updateField(providerId, field, event) {const value = event?.target ? event.target.value : event;@@ -91,6 +131,11 @@ export default class ConfigureOauthComponent extends Component {...this.values,[providerId]: { ...(this.values[providerId] ?? {}), [field]: value },};++ if (field !== 'enabled' && this.testResults[providerId]) {+ const { [providerId]: stale, ...rest } = this.testResults; // eslint-disable-line no-unused-vars+ this.testResults = rest;+ }}@action toggleProvider(providerId, enabled) {@@ -127,30 +172,38 @@ export default class ConfigureOauthComponent extends Component {this.values = values;this.secretStatus = secretStatus;+ this.savedEnabled = Object.fromEntries(this.providers.map((provider) => [provider.id, values[provider.id].enabled]));}/**- * The save payload. Secret fields left empty are omitted rather than sent blank,- * so the stored value is kept.+ * One provider's fields as they stand in the form. Secret fields left empty are+ * omitted rather than sent blank, so the stored value is kept.*/- serialize() {- const providers = {};+ serializeProvider(provider) {+ const current = this.values[provider.id] ?? {};+ const out = { enabled: current.enabled === true };- for (const provider of this.providers) {- const current = this.values[provider.id] ?? {};- const out = { enabled: current.enabled === true };+ for (const field of this.fieldsFor(provider)) {+ const value = current[field.key];- for (const field of this.fieldsFor(provider)) {- const value = current[field.key];+ if (field.secret && (value === undefined || value === null || String(value).trim() === '')) {+ continue;+ }- if (field.secret && (value === undefined || value === null || String(value).trim() === '')) {- continue;- }+ out[field.key] = value ?? '';+ }- out[field.key] = value ?? '';- }+ return out;+ }- providers[provider.id] = out;+ /**+ * The save payload.+ */+ serialize() {+ const providers = {};++ for (const provider of this.providers) {+ providers[provider.id] = this.serializeProvider(provider);}return {@@ -164,6 +217,7 @@ export default class ConfigureOauthComponent extends Component {try {const payload = yield this.fetch.get('settings/oauth-config');this.applyConfig(payload);+ this.panelOpen = { ...this.savedEnabled };} catch (error) {this.notifications.serverError(error);}@@ -180,32 +234,19 @@ export default class ConfigureOauthComponent extends Component {}}+ /**+ * Check the credentials currently in the form — saved or not — with the provider.+ */@task *test(providerId) {+ const provider = this.providers.find((candidate) => candidate.id === providerId);+ // eslint-disable-next-line no-unused-vars+ const { enabled, ...values } = this.serializeProvider(provider);+try {- const result = yield this.fetch.post('settings/test-oauth-config', { provider: providerId });+ const result = yield this.fetch.post('settings/test-oauth-config', { provider: providerId, values });this.testResults = { ...this.testResults, [providerId]: result };} catch (error) {this.notifications.serverError(error);}}-- @action testMessage(result) {- if (!result) {- return null;- }-- if (result.problem === 'invalid_signing_key') {- return 'The signing key could not be used to mint a client secret. Check that it is the full .p8 file for this Key ID.';- }-- if (result.problem === 'missing_credentials') {- return 'Some required credentials are missing. Fill in every required field and save before testing.';- }-- if (result.configured && !result.enabled) {- return 'Credentials look complete. Enable the provider and save to offer it on the sign-in page.';- }-- return 'Credentials look complete. Register the callback URL below with the provider if you have not already.';- }}diff --git a/console/tests/integration/components/configure/oauth-test.js b/console/tests/integration/components/configure/oauth-test.jsindex 27232d83..a5d54ea6 100644--- a/console/tests/integration/components/configure/oauth-test.js+++ b/console/tests/integration/components/configure/oauth-test.js@@ -72,6 +72,7 @@ module('Integration | Component | configure/oauth', function (hooks) {hooks.beforeEach(function () {this.posted = [];+ 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;class FetchStub extends Service {@@ -82,7 +83,7 @@ module('Integration | Component | configure/oauth', function (hooks) {self.posted.push({ path, payload });if (path === 'settings/test-oauth-config') {- return Promise.resolve({ provider: payload.provider, configured: false, enabled: false, problem: 'invalid_signing_key' });+ return Promise.resolve({ provider: payload.provider, ...self.checkResult });}return Promise.resolve(JSON.parse(JSON.stringify(CONFIG)));@@ -164,7 +165,7 @@ module('Integration | Component | configure/oauth', function (hooks) {assert.strictEqual(saved.providers.google.client_secret, 'a-brand-new-secret');});- test('checking a provider reports the problem in plain language', async function (assert) {+ test('checking a provider reports what the server found', async function (assert) {const captured = captureComponent(this.owner, 'configure/oauth', ConfigureOauthComponent);await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);await expandAll(this.element);@@ -173,16 +174,75 @@ module('Integration | Component | configure/oauth', function (hooks) {await settled();assert.strictEqual(this.posted.at(-1).path, 'settings/test-oauth-config');- assert.deepEqual(this.posted.at(-1).payload, { provider: 'apple' });+ assert.strictEqual(this.posted.at(-1).payload.provider, 'apple');assert.dom(this.element).containsText('signing key could not be used');});- test('it explains each check outcome', function (assert) {- const component = Object.create(ConfigureOauthComponent.prototype);+ test('checking sends what is in the form, before 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 />`);++ await fillIn('input[type="password"]', 'typed-not-saved');+ await captured.instance.test.perform('google');++ assert.deepEqual(this.posted.at(-1).payload, {+ provider: 'google',+ values: { client_id: 'google-client-id', client_secret: 'typed-not-saved', hosted_domain: '' },+ });+ assert.notOk(+ this.posted.some((p) => p.path === 'settings/oauth-config'),+ 'nothing was saved to run the check'+ );+ });++ test('a blank secret is left out of the check so the saved one is used', async function (assert) {+ const captured = captureComponent(this.owner, 'configure/oauth', ConfigureOauthComponent);+ await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);++ await captured.instance.test.perform('google');++ assert.notOk('client_secret' in this.posted.at(-1).payload.values);+ });++ test('typing into a provider field keeps its panel open', async function (assert) {+ await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);+ await expandAll(this.element);++ // Apple is disabled, so its panel only stays open if typing does not reset it.+ const teamId = [...this.element.querySelectorAll('.next-content-panel-wrapper')].find((panel) => panel.textContent.includes('Team ID')).querySelector('input[type="text"]');+ await fillIn(teamId, 'T');+ await fillIn(teamId, 'TE');++ assert.dom(this.element).containsText('Signing key (.p8)');+ assert.strictEqual(this.element.querySelectorAll('.next-content-panel-header.next-content-panel-is-closed').length, 0);+ });++ test('a provider can only be switched on after the provider accepts its credentials', async function (assert) {+ const captured = captureComponent(this.owner, 'configure/oauth', ConfigureOauthComponent);+ await render(hbs`<div id="next-view-section-subheader-actions"></div><Configure::Oauth />`);+ await expandAll(this.element);+ const component = captured.instance;++ assert.false(component.canToggleProvider('apple'), 'not before a check');+ assert.dom(this.element).containsText('to confirm Apple accepts these credentials');++ await component.test.perform('apple');+ assert.false(component.canToggleProvider('apple'), 'not after a failed check');++ this.checkResult = { configured: true, verified: true, problem: null, message: 'Apple accepted these credentials.' };+ await component.test.perform('apple');+ await settled();+ assert.true(component.canToggleProvider('apple'), 'after a passing check');+ assert.dom(this.element).doesNotContainText('to confirm Apple accepts these credentials');++ component.updateField('apple', 'key_id', 'CHANGED');+ assert.false(component.canToggleProvider('apple'), 'editing a credential invalidates the check');+ });++ test('a live provider can always be switched 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 />`);- assert.strictEqual(component.testMessage(null), null);- assert.true(component.testMessage({ problem: 'missing_credentials' }).includes('missing'));- assert.true(component.testMessage({ configured: true, enabled: false, problem: null }).includes('Enable the provider'));- assert.true(component.testMessage({ configured: true, enabled: true, problem: null }).includes('Register the callback URL'));+ assert.true(captured.instance.canToggleProvider('google'), 'google is enabled in the fixture');});});diff --git a/console/tests/unit/controllers/console/admin-test.js b/console/tests/unit/controllers/console/admin-test.jsindex ec30f622..8ad71512 100644--- a/console/tests/unit/controllers/console/admin-test.js+++ b/console/tests/unit/controllers/console/admin-test.js@@ -43,7 +43,7 @@ class IntlStub extends Service {'console.admin.menu.overview': 'Overview','console.admin.menu.organizations': 'Organizations','console.admin.menu.branding': 'Branding',- 'console.admin.menu.2fa-config': '2FA Config',+ 'console.admin.menu.2fa-config': 'Two-Factor Auth','console.admin.menu.platform-api-token': 'Platform API Token','console.admin.schedule-monitor.schedule-monitor': 'Schedule Monitor','console.admin.menu.services': 'Services',@@ -222,7 +222,7 @@ module('Unit | Controller | console/admin', function (hooks) {assert.ok(authConfig, 'the group exists');assert.deepEqual(authConfig.children.map((item) => item.label),- ['OAuth Sign-in', '2FA Config'],+ ['OAuth Sign-in', 'Two-Factor Auth'],'sign-in first, then the second factor');// Grouping is sidebar-only: 2FA keeps its route, so existing links still work.@@ -232,7 +232,7 @@ module('Unit | Controller | console/admin', function (hooks) {);assert.strictEqual(labels.indexOf('Auth Config') + 1, labels.indexOf('System Config'), 'auth config sits just before system config');assert.notOk(- controller.navigationItems.some((item) => item.label === '2FA Config'),+ controller.navigationItems.some((item) => item.label === 'Two-Factor Auth'),'2FA is no longer a top-level item');});diff --git a/console/translations/en-us.yaml b/console/translations/en-us.yamlindex 6d3a647f..3e4e1102 100644--- a/console/translations/en-us.yaml+++ b/console/translations/en-us.yaml@@ -702,7 +702,7 @@ console:overview: Overvieworganizations: Organizationsbranding: Branding- 2fa-config: 2FA Config+ 2fa-config: Two-Factor Authplatform-api-token: Platform API Tokenschedule-monitor: Schedule Monitorservices: Services