diff --git a/.gitignore b/.gitignore index 54c57c36fe..b0d0e0bcfa 100644 --- a/.gitignore +++ b/.gitignore @@ -149,3 +149,6 @@ use_dev_supervisor.txt /tools/docker-compose/overrides/ /awx/ui_next/.ui-built /Dockerfile +/_build/ +/_build_kube_dev/ +/Dockerfile.kube-dev diff --git a/CHANGELOG.md b/CHANGELOG.md index 6394b4f6d7..6237a9f54a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ This is a list of high-level changes for each release of AWX. A full list of commits can be found at `https://github.com/ansible/awx/releases/tag/`. +# 17.0.1 (January 26, 2021) +- Fixed pgdocker directory permissions issue with Local Docker installer: https://github.com/ansible/awx/pull/9152 +- Fixed a bug in the UI which caused toggle settings to not be changed when clicked: https://github.com/ansible/awx/pull/9093 + # 17.0.0 (January 22, 2021) - AWX now requires PostgreSQL 12 by default: https://github.com/ansible/awx/pull/8943 **Note:** users who encounter permissions errors at upgrade time should `chown -R ~/.awx/pgdocker` to ensure it's owned by the user running the install playbook diff --git a/Makefile b/Makefile index 9c7ccd028b..9cf77e597e 100644 --- a/Makefile +++ b/Makefile @@ -267,11 +267,27 @@ collectstatic: fi; \ mkdir -p awx/public/static && $(PYTHON) manage.py collectstatic --clear --noinput > /dev/null 2>&1 +UWSGI_DEV_RELOAD_COMMAND ?= supervisorctl restart tower-processes:awx-dispatcher tower-processes:awx-receiver + uwsgi: collectstatic @if [ "$(VENV_BASE)" ]; then \ . $(VENV_BASE)/awx/bin/activate; \ fi; \ - uwsgi -b 32768 --socket 127.0.0.1:8050 --module=awx.wsgi:application --home=/var/lib/awx/venv/awx --chdir=/awx_devel/ --vacuum --processes=5 --harakiri=120 --master --no-orphans --py-autoreload 1 --max-requests=1000 --stats /tmp/stats.socket --lazy-apps --logformat "%(addr) %(method) %(uri) - %(proto) %(status)" --hook-accepting1="exec:supervisorctl restart tower-processes:awx-dispatcher tower-processes:awx-receiver" + uwsgi -b 32768 \ + --socket 127.0.0.1:8050 \ + --module=awx.wsgi:application \ + --home=/var/lib/awx/venv/awx \ + --chdir=/awx_devel/ \ + --vacuum \ + --processes=5 \ + --harakiri=120 --master \ + --no-orphans \ + --py-autoreload 1 \ + --max-requests=1000 \ + --stats /tmp/stats.socket \ + --lazy-apps \ + --logformat "%(addr) %(method) %(uri) - %(proto) %(status)" \ + --hook-accepting1="exec: $(UWSGI_DEV_RELOAD_COMMAND)" daphne: @if [ "$(VENV_BASE)" ]; then \ @@ -579,15 +595,18 @@ docker-compose-clean: awx/projects # Base development image build docker-compose-build: - ansible localhost -m template -a "src=installer/roles/image_build/templates/Dockerfile.j2 dest=tools/docker-compose/Dockerfile" -e build_dev=True - docker build -t ansible/awx_devel -f tools/docker-compose/Dockerfile \ - --cache-from=$(DEV_DOCKER_TAG_BASE)/awx_devel:$(COMPOSE_TAG) . + ansible-playbook installer/dockerfile.yml -e build_dev=True + docker build -t ansible/awx_devel \ + --build-arg BUILDKIT_INLINE_CACHE=1 \ + --cache-from=$(DEV_DOCKER_TAG_BASE)/awx_devel:$(COMPOSE_TAG) . docker tag ansible/awx_devel $(DEV_DOCKER_TAG_BASE)/awx_devel:$(COMPOSE_TAG) #docker push $(DEV_DOCKER_TAG_BASE)/awx_devel:$(COMPOSE_TAG) # For use when developing on "isolated" AWX deployments docker-compose-isolated-build: docker-compose-build - docker build -t ansible/awx_isolated -f tools/docker-isolated/Dockerfile . + docker build -t ansible/awx_isolated \ + --build-arg BUILDKIT_INLINE_CACHE=1 \ + -f tools/docker-isolated/Dockerfile . docker tag ansible/awx_isolated $(DEV_DOCKER_TAG_BASE)/awx_isolated:$(COMPOSE_TAG) #docker push $(DEV_DOCKER_TAG_BASE)/awx_isolated:$(COMPOSE_TAG) @@ -624,5 +643,16 @@ psql-container: VERSION: @echo "awx: $(VERSION)" -Dockerfile: installer/roles/image_build/templates/Dockerfile.j2 - ansible localhost -m template -a "src=installer/roles/image_build/templates/Dockerfile.j2 dest=Dockerfile" +Dockerfile: installer/roles/dockerfile/templates/Dockerfile.j2 + ansible-playbook installer/dockerfile.yml + +Dockerfile.kube-dev: installer/roles/dockerfile/templates/Dockerfile.j2 + ansible-playbook installer/dockerfile.yml \ + -e dockerfile_name=Dockerfile.kube-dev \ + -e kube_dev=True \ + -e template_dest=_build_kube_dev + +awx-kube-dev-build: Dockerfile.kube-dev + docker build -f Dockerfile.kube-dev \ + --build-arg BUILDKIT_INLINE_CACHE=1 \ + -t $(DEV_DOCKER_TAG_BASE)/awx_kube_devel:$(COMPOSE_TAG) . diff --git a/VERSION b/VERSION index aac58983e6..3e17df0287 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -17.0.0 +17.0.1 diff --git a/awx/main/models/notifications.py b/awx/main/models/notifications.py index 33562e7fca..74a9896385 100644 --- a/awx/main/models/notifications.py +++ b/awx/main/models/notifications.py @@ -357,7 +357,7 @@ class JobNotificationMixin(object): 'url': 'https://towerhost/#/jobs/playbook/1010', 'approval_status': 'approved', 'approval_node_name': 'Approve Me', - 'workflow_url': 'https://towerhost/#/workflows/1010', + 'workflow_url': 'https://towerhost/#/jobs/workflow/1010', 'job_metadata': """{'url': 'https://towerhost/$/jobs/playbook/13', 'traceback': '', 'status': 'running', diff --git a/awx/main/models/workflow.py b/awx/main/models/workflow.py index dd8bc3e894..d9ac8afcf9 100644 --- a/awx/main/models/workflow.py +++ b/awx/main/models/workflow.py @@ -620,7 +620,7 @@ class WorkflowJob(UnifiedJob, WorkflowJobOptions, SurveyJobMixin, JobNotificatio return reverse('api:workflow_job_detail', kwargs={'pk': self.pk}, request=request) def get_ui_url(self): - return urljoin(settings.TOWER_URL_BASE, '/#/workflows/{}'.format(self.pk)) + return urljoin(settings.TOWER_URL_BASE, '/#/jobs/workflow/{}'.format(self.pk)) def notification_data(self): result = super(WorkflowJob, self).notification_data() @@ -752,7 +752,7 @@ class WorkflowApproval(UnifiedJob, JobNotificationMixin): return None def get_ui_url(self): - return urljoin(settings.TOWER_URL_BASE, '/#/workflows/{}'.format(self.workflow_job.id)) + return urljoin(settings.TOWER_URL_BASE, '/#/jobs/workflow/{}'.format(self.workflow_job.id)) def _get_parent_field_name(self): return 'workflow_approval_template' @@ -840,7 +840,7 @@ class WorkflowApproval(UnifiedJob, JobNotificationMixin): return (msg, body) def context(self, approval_status): - workflow_url = urljoin(settings.TOWER_URL_BASE, '/#/workflows/{}'.format(self.workflow_job.id)) + workflow_url = urljoin(settings.TOWER_URL_BASE, '/#/jobs/workflow/{}'.format(self.workflow_job.id)) return {'approval_status': approval_status, 'approval_node_name': self.workflow_approval_template.name, 'workflow_url': workflow_url, diff --git a/awx/settings/development.py b/awx/settings/development.py index 9846705fa5..6181d16ec6 100644 --- a/awx/settings/development.py +++ b/awx/settings/development.py @@ -158,7 +158,10 @@ AWX_VENV_PATH = os.path.join(BASE_VENV_PATH, "awx") # default settings for development. If not present, we can still run using # only the defaults. try: - include(optional('local_*.py'), scope=locals()) + if os.getenv('AWX_KUBE_DEVEL', False): + include(optional('minikube.py'), scope=locals()) + else: + include(optional('local_*.py'), scope=locals()) except ImportError: traceback.print_exc() sys.exit(1) diff --git a/awx/settings/minikube.py b/awx/settings/minikube.py new file mode 100644 index 0000000000..0ac81875bc --- /dev/null +++ b/awx/settings/minikube.py @@ -0,0 +1,4 @@ +BROADCAST_WEBSOCKET_SECRET = '🤖starscream🤖' +BROADCAST_WEBSOCKET_PORT = 8013 +BROADCAST_WEBSOCKET_VERIFY_CERT = False +BROADCAST_WEBSOCKET_PROTOCOL = 'http' diff --git a/awx/ui_next/src/screens/ActivityStream/ActivityStreamDescription.jsx b/awx/ui_next/src/screens/ActivityStream/ActivityStreamDescription.jsx index d933e0c259..517491797a 100644 --- a/awx/ui_next/src/screens/ActivityStream/ActivityStreamDescription.jsx +++ b/awx/ui_next/src/screens/ActivityStream/ActivityStreamDescription.jsx @@ -94,7 +94,7 @@ const buildAnchor = (obj, resource, activity) => { break; } case 'workflow_job': - url = `/workflows/${obj.id}/`; + url = `/jobs/workflow/${obj.id}/`; break; case 'label': url = null; diff --git a/awx/ui_next/src/screens/Job/JobDetail/JobDetail.jsx b/awx/ui_next/src/screens/Job/JobDetail/JobDetail.jsx index 9255b27af1..f239081f48 100644 --- a/awx/ui_next/src/screens/Job/JobDetail/JobDetail.jsx +++ b/awx/ui_next/src/screens/Job/JobDetail/JobDetail.jsx @@ -93,6 +93,7 @@ function JobDetail({ job, i18n }) { workflow_job_template: workflowJobTemplate, labels, project, + source_workflow_job, } = job.summary_fields; const [errorMsg, setErrorMsg] = useState(); const history = useHistory(); @@ -195,6 +196,16 @@ function JobDetail({ job, i18n }) { } /> )} + {source_workflow_job && ( + + {source_workflow_job.id} - {source_workflow_job.name} + + } + /> + )} ', () => { kubernetes: false, credential_type_id: 1, }, + source_workflow_job: { + id: 1234, + name: 'Test Source Workflow', + }, }, }} /> @@ -45,6 +49,7 @@ describe('', () => { assertDetail('Started', '8/8/2019, 7:24:18 PM'); assertDetail('Finished', '8/8/2019, 7:24:50 PM'); assertDetail('Job Template', mockJobData.summary_fields.job_template.name); + assertDetail('Source Workflow Job', `1234 - Test Source Workflow`); assertDetail('Job Type', 'Playbook Run'); assertDetail('Launched By', mockJobData.summary_fields.created_by.username); assertDetail('Inventory', mockJobData.summary_fields.inventory.name); diff --git a/awx/ui_next/src/screens/Setting/SAML/SAML.test.jsx b/awx/ui_next/src/screens/Setting/SAML/SAML.test.jsx index 0c662fd927..70d7ae5bb2 100644 --- a/awx/ui_next/src/screens/Setting/SAML/SAML.test.jsx +++ b/awx/ui_next/src/screens/Setting/SAML/SAML.test.jsx @@ -3,11 +3,31 @@ import { act } from 'react-dom/test-utils'; import { createMemoryHistory } from 'history'; import { mountWithContexts } from '../../../../testUtils/enzymeHelpers'; import { SettingsAPI } from '../../../api'; +import { SettingsProvider } from '../../../contexts/Settings'; +import mockAllOptions from '../shared/data.allSettingOptions.json'; import SAML from './SAML'; jest.mock('../../../api/models/Settings'); SettingsAPI.readCategory.mockResolvedValue({ - data: {}, + data: { + SOCIAL_AUTH_SAML_CALLBACK_URL: 'https://towerhost/sso/complete/saml/', + SOCIAL_AUTH_SAML_METADATA_URL: 'https://towerhost/sso/metadata/saml/', + SOCIAL_AUTH_SAML_SP_ENTITY_ID: '', + SOCIAL_AUTH_SAML_SP_PUBLIC_CERT: '', + SOCIAL_AUTH_SAML_SP_PRIVATE_KEY: '', + SOCIAL_AUTH_SAML_ORG_INFO: {}, + SOCIAL_AUTH_SAML_TECHNICAL_CONTACT: {}, + SOCIAL_AUTH_SAML_SUPPORT_CONTACT: {}, + SOCIAL_AUTH_SAML_ENABLED_IDPS: {}, + SOCIAL_AUTH_SAML_SECURITY_CONFIG: {}, + SOCIAL_AUTH_SAML_SP_EXTRA: {}, + SOCIAL_AUTH_SAML_EXTRA_DATA: [], + SOCIAL_AUTH_SAML_ORGANIZATION_MAP: {}, + SOCIAL_AUTH_SAML_TEAM_MAP: {}, + SOCIAL_AUTH_SAML_ORGANIZATION_ATTR: {}, + SOCIAL_AUTH_SAML_TEAM_ATTR: {}, + SAML_AUTO_CREATE_OBJECTS: false, + }, }); describe('', () => { @@ -23,9 +43,14 @@ describe('', () => { initialEntries: ['/settings/saml/details'], }); await act(async () => { - wrapper = mountWithContexts(, { - context: { router: { history } }, - }); + wrapper = mountWithContexts( + + + , + { + context: { router: { history } }, + } + ); }); expect(wrapper.find('SAMLDetail').length).toBe(1); }); @@ -35,9 +60,14 @@ describe('', () => { initialEntries: ['/settings/saml/edit'], }); await act(async () => { - wrapper = mountWithContexts(, { - context: { router: { history } }, - }); + wrapper = mountWithContexts( + + + , + { + context: { router: { history } }, + } + ); }); expect(wrapper.find('SAMLEdit').length).toBe(1); }); diff --git a/awx/ui_next/src/screens/Setting/SAML/SAMLDetail/SAMLDetail.jsx b/awx/ui_next/src/screens/Setting/SAML/SAMLDetail/SAMLDetail.jsx index 5d2e54497e..f8fb104ffb 100644 --- a/awx/ui_next/src/screens/Setting/SAML/SAMLDetail/SAMLDetail.jsx +++ b/awx/ui_next/src/screens/Setting/SAML/SAMLDetail/SAMLDetail.jsx @@ -18,6 +18,7 @@ import { SettingDetail } from '../../shared'; function SAMLDetail({ i18n }) { const { me } = useConfig(); const { GET: options } = useSettings(); + options.SOCIAL_AUTH_SAML_SP_PUBLIC_CERT.type = 'certificate'; const { isLoading, error, request, result: saml } = useRequest( useCallback(async () => { diff --git a/awx/ui_next/src/screens/Setting/SAML/SAMLDetail/SAMLDetail.test.jsx b/awx/ui_next/src/screens/Setting/SAML/SAMLDetail/SAMLDetail.test.jsx index 1afaee4e24..1c3015c9ca 100644 --- a/awx/ui_next/src/screens/Setting/SAML/SAMLDetail/SAMLDetail.test.jsx +++ b/awx/ui_next/src/screens/Setting/SAML/SAMLDetail/SAMLDetail.test.jsx @@ -32,6 +32,7 @@ SettingsAPI.readCategory.mockResolvedValue({ SOCIAL_AUTH_SAML_TEAM_MAP: {}, SOCIAL_AUTH_SAML_ORGANIZATION_ATTR: {}, SOCIAL_AUTH_SAML_TEAM_ATTR: {}, + SAML_AUTO_CREATE_OBJECTS: false, }, }); @@ -59,6 +60,11 @@ describe('', () => { }); test('should render expected details', () => { + assertDetail( + wrapper, + 'Automatically Create Organizations and Teams on SAML Login', + 'Off' + ); assertDetail( wrapper, 'SAML Assertion Consumer Service (ACS) URL', @@ -70,7 +76,7 @@ describe('', () => { 'https://towerhost/sso/metadata/saml/' ); assertDetail(wrapper, 'SAML Service Provider Entity ID', 'mock_id'); - assertDetail( + assertVariableDetail( wrapper, 'SAML Service Provider Public Certificate', 'mock_cert' diff --git a/awx/ui_next/src/screens/Setting/SAML/SAMLEdit/SAMLEdit.jsx b/awx/ui_next/src/screens/Setting/SAML/SAMLEdit/SAMLEdit.jsx index fc9740b16c..93010d1ee5 100644 --- a/awx/ui_next/src/screens/Setting/SAML/SAMLEdit/SAMLEdit.jsx +++ b/awx/ui_next/src/screens/Setting/SAML/SAMLEdit/SAMLEdit.jsx @@ -1,25 +1,208 @@ -import React from 'react'; -import { Link } from 'react-router-dom'; -import { withI18n } from '@lingui/react'; -import { t } from '@lingui/macro'; -import { Button } from '@patternfly/react-core'; -import { CardBody, CardActionsRow } from '../../../../components/Card'; +import React, { useCallback, useEffect } from 'react'; +import { useHistory } from 'react-router-dom'; +import { Formik } from 'formik'; +import { Form } from '@patternfly/react-core'; +import { CardBody } from '../../../../components/Card'; +import ContentError from '../../../../components/ContentError'; +import ContentLoading from '../../../../components/ContentLoading'; +import { FormSubmitError } from '../../../../components/FormField'; +import { FormColumnLayout } from '../../../../components/FormLayout'; +import { useSettings } from '../../../../contexts/Settings'; +import { RevertAllAlert, RevertFormActionGroup } from '../../shared'; +import { + BooleanField, + FileUploadField, + InputField, + ObjectField, +} from '../../shared/SharedFields'; +import { formatJson } from '../../shared/settingUtils'; +import useModal from '../../../../util/useModal'; +import useRequest from '../../../../util/useRequest'; +import { SettingsAPI } from '../../../../api'; + +function SAMLEdit() { + const history = useHistory(); + const { isModalOpen, toggleModal, closeModal } = useModal(); + const { PUT: options } = useSettings(); + + const { isLoading, error, request: fetchSAML, result: saml } = useRequest( + useCallback(async () => { + const { data } = await SettingsAPI.readCategory('saml'); + const mergedData = {}; + Object.keys(data).forEach(key => { + if (!options[key]) { + return; + } + mergedData[key] = options[key]; + mergedData[key].value = data[key]; + }); + return mergedData; + }, [options]), + null + ); + + useEffect(() => { + fetchSAML(); + }, [fetchSAML]); + + const { error: submitError, request: submitForm } = useRequest( + useCallback( + async values => { + await SettingsAPI.updateAll(values); + history.push('/settings/saml/details'); + }, + [history] + ), + null + ); + + const handleSubmit = async form => { + await submitForm({ + ...form, + SOCIAL_AUTH_SAML_ORG_INFO: formatJson(form.SOCIAL_AUTH_SAML_ORG_INFO), + SOCIAL_AUTH_SAML_TECHNICAL_CONTACT: formatJson( + form.SOCIAL_AUTH_SAML_TECHNICAL_CONTACT + ), + SOCIAL_AUTH_SAML_SUPPORT_CONTACT: formatJson( + form.SOCIAL_AUTH_SAML_SUPPORT_CONTACT + ), + SOCIAL_AUTH_SAML_ENABLED_IDPS: formatJson( + form.SOCIAL_AUTH_SAML_ENABLED_IDPS + ), + SOCIAL_AUTH_SAML_ORGANIZATION_MAP: formatJson( + form.SOCIAL_AUTH_SAML_ORGANIZATION_MAP + ), + SOCIAL_AUTH_SAML_ORGANIZATION_ATTR: formatJson( + form.SOCIAL_AUTH_SAML_ORGANIZATION_ATTR + ), + SOCIAL_AUTH_SAML_TEAM_MAP: formatJson(form.SOCIAL_AUTH_SAML_TEAM_MAP), + SOCIAL_AUTH_SAML_TEAM_ATTR: formatJson(form.SOCIAL_AUTH_SAML_TEAM_ATTR), + SOCIAL_AUTH_SAML_SECURITY_CONFIG: formatJson( + form.SOCIAL_AUTH_SAML_SECURITY_CONFIG + ), + SOCIAL_AUTH_SAML_SP_EXTRA: formatJson(form.SOCIAL_AUTH_SAML_SP_EXTRA), + SOCIAL_AUTH_SAML_EXTRA_DATA: formatJson(form.SOCIAL_AUTH_SAML_EXTRA_DATA), + }); + }; + + const handleRevertAll = async () => { + const defaultValues = Object.assign( + ...Object.entries(saml).map(([key, value]) => ({ + [key]: value.default, + })) + ); + await submitForm(defaultValues); + closeModal(); + }; + + const handleCancel = () => { + history.push('/settings/saml/details'); + }; + + const initialValues = fields => + Object.keys(fields).reduce((acc, key) => { + if (fields[key].type === 'list' || fields[key].type === 'nested object') { + const emptyDefault = fields[key].type === 'list' ? '[]' : '{}'; + acc[key] = fields[key].value + ? JSON.stringify(fields[key].value, null, 2) + : emptyDefault; + } else { + acc[key] = fields[key].value ?? ''; + } + return acc; + }, {}); -function SAMLEdit({ i18n }) { return ( - {i18n._(t`Edit form coming soon :)`)} - - - + {isLoading && } + {!isLoading && error && } + {!isLoading && saml && ( + + {formik => ( +
+ + + + + + + + + + + + + + + + + {submitError && } + + + {isModalOpen && ( + + )} + + )} +
+ )}
); } -export default withI18n()(SAMLEdit); +export default SAMLEdit; diff --git a/awx/ui_next/src/screens/Setting/SAML/SAMLEdit/SAMLEdit.test.jsx b/awx/ui_next/src/screens/Setting/SAML/SAMLEdit/SAMLEdit.test.jsx index d6319d9b2e..858bf814f7 100644 --- a/awx/ui_next/src/screens/Setting/SAML/SAMLEdit/SAMLEdit.test.jsx +++ b/awx/ui_next/src/screens/Setting/SAML/SAMLEdit/SAMLEdit.test.jsx @@ -1,16 +1,251 @@ import React from 'react'; -import { mountWithContexts } from '../../../../../testUtils/enzymeHelpers'; +import { act } from 'react-dom/test-utils'; +import { createMemoryHistory } from 'history'; +import { + mountWithContexts, + waitForElement, +} from '../../../../../testUtils/enzymeHelpers'; +import mockAllOptions from '../../shared/data.allSettingOptions.json'; +import { SettingsProvider } from '../../../../contexts/Settings'; +import { SettingsAPI } from '../../../../api'; import SAMLEdit from './SAMLEdit'; +jest.mock('../../../../api/models/Settings'); +SettingsAPI.updateAll.mockResolvedValue({}); +SettingsAPI.readCategory.mockResolvedValue({ + data: { + SAML_AUTO_CREATE_OBJECTS: true, + SOCIAL_AUTH_SAML_CALLBACK_URL: 'https://towerhost/sso/complete/saml/', + SOCIAL_AUTH_SAML_METADATA_URL: 'https://towerhost/sso/metadata/saml/', + SOCIAL_AUTH_SAML_SP_ENTITY_ID: 'mock_id', + SOCIAL_AUTH_SAML_SP_PUBLIC_CERT: 'mock_cert', + SOCIAL_AUTH_SAML_SP_PRIVATE_KEY: '$encrypted$', + SOCIAL_AUTH_SAML_ORG_INFO: {}, + SOCIAL_AUTH_SAML_TECHNICAL_CONTACT: { + givenName: 'Mock User', + emailAddress: 'mockuser@example.com', + }, + SOCIAL_AUTH_SAML_SUPPORT_CONTACT: {}, + SOCIAL_AUTH_SAML_ENABLED_IDPS: {}, + SOCIAL_AUTH_SAML_SP_EXTRA: {}, + SOCIAL_AUTH_SAML_EXTRA_DATA: [], + SOCIAL_AUTH_SAML_ORGANIZATION_MAP: {}, + SOCIAL_AUTH_SAML_TEAM_MAP: {}, + SOCIAL_AUTH_SAML_ORGANIZATION_ATTR: {}, + SOCIAL_AUTH_SAML_TEAM_ATTR: {}, + SOCIAL_AUTH_SAML_SECURITY_CONFIG: { + requestedAuthnContext: false, + }, + }, +}); + describe('', () => { let wrapper; - beforeEach(() => { - wrapper = mountWithContexts(); - }); + let history; + afterEach(() => { wrapper.unmount(); + jest.clearAllMocks(); }); + + beforeEach(async () => { + history = createMemoryHistory({ + initialEntries: ['/settings/saml/edit'], + }); + await act(async () => { + wrapper = mountWithContexts( + + + , + { + context: { router: { history } }, + } + ); + }); + await waitForElement(wrapper, 'ContentLoading', el => el.length === 0); + }); + test('initially renders without crashing', () => { expect(wrapper.find('SAMLEdit').length).toBe(1); }); + + test('should display expected form fields', async () => { + expect( + wrapper.find('FormGroup[label="SAML Service Provider Entity ID"]').length + ).toBe(1); + expect( + wrapper.find( + 'FormGroup[label="Automatically Create Organizations and Teams on SAML Login"]' + ).length + ).toBe(1); + expect( + wrapper.find( + 'FormGroup[label="SAML Service Provider Public Certificate"]' + ).length + ).toBe(1); + expect( + wrapper.find('FormGroup[label="SAML Service Provider Private Key"]') + .length + ).toBe(1); + expect( + wrapper.find('FormGroup[label="SAML Service Provider Organization Info"]') + .length + ).toBe(1); + expect( + wrapper.find('FormGroup[label="SAML Service Provider Technical Contact"]') + .length + ).toBe(1); + expect( + wrapper.find('FormGroup[label="SAML Service Provider Support Contact"]') + .length + ).toBe(1); + expect( + wrapper.find('FormGroup[label="SAML Enabled Identity Providers"]').length + ).toBe(1); + expect( + wrapper.find('FormGroup[label="SAML Organization Map"]').length + ).toBe(1); + expect(wrapper.find('FormGroup[label="SAML Team Map"]').length).toBe(1); + expect( + wrapper.find('FormGroup[label="SAML Organization Attribute Mapping"]') + .length + ).toBe(1); + expect( + wrapper.find('FormGroup[label="SAML Team Attribute Mapping"]').length + ).toBe(1); + expect(wrapper.find('FormGroup[label="SAML Security Config"]').length).toBe( + 1 + ); + expect( + wrapper.find( + 'FormGroup[label="SAML Service Provider extra configuration data"]' + ).length + ).toBe(1); + expect( + wrapper.find( + 'FormGroup[label="SAML IDP to extra_data attribute mapping"]' + ).length + ).toBe(1); + }); + + test('should successfully send default values to api on form revert all', async () => { + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(0); + expect(wrapper.find('RevertAllAlert')).toHaveLength(0); + await act(async () => { + wrapper + .find('button[aria-label="Revert all to default"]') + .invoke('onClick')(); + }); + wrapper.update(); + expect(wrapper.find('RevertAllAlert')).toHaveLength(1); + await act(async () => { + wrapper + .find('RevertAllAlert button[aria-label="Confirm revert all"]') + .invoke('onClick')(); + }); + wrapper.update(); + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(1); + expect(SettingsAPI.updateAll).toHaveBeenCalledWith({ + SAML_AUTO_CREATE_OBJECTS: true, + SOCIAL_AUTH_SAML_ENABLED_IDPS: {}, + SOCIAL_AUTH_SAML_EXTRA_DATA: null, + SOCIAL_AUTH_SAML_ORGANIZATION_ATTR: {}, + SOCIAL_AUTH_SAML_ORGANIZATION_MAP: null, + SOCIAL_AUTH_SAML_ORG_INFO: {}, + SOCIAL_AUTH_SAML_SP_ENTITY_ID: '', + SOCIAL_AUTH_SAML_SP_EXTRA: null, + SOCIAL_AUTH_SAML_SP_PRIVATE_KEY: '', + SOCIAL_AUTH_SAML_SP_PUBLIC_CERT: '', + SOCIAL_AUTH_SAML_SUPPORT_CONTACT: {}, + SOCIAL_AUTH_SAML_TEAM_ATTR: {}, + SOCIAL_AUTH_SAML_TEAM_MAP: null, + SOCIAL_AUTH_SAML_TECHNICAL_CONTACT: {}, + SOCIAL_AUTH_SAML_SECURITY_CONFIG: { + requestedAuthnContext: false, + }, + }); + }); + + test('should successfully send request to api on form submission', async () => { + act(() => { + wrapper.find('input#SOCIAL_AUTH_SAML_SP_ENTITY_ID').simulate('change', { + target: { value: 'new_id', name: 'SOCIAL_AUTH_SAML_SP_ENTITY_ID' }, + }); + wrapper + .find( + 'FormGroup[fieldId="SOCIAL_AUTH_SAML_TECHNICAL_CONTACT"] button[aria-label="Revert"]' + ) + .invoke('onClick')(); + }); + wrapper.update(); + await act(async () => { + wrapper.find('Form').invoke('onSubmit')(); + }); + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(1); + expect(SettingsAPI.updateAll).toHaveBeenCalledWith({ + SAML_AUTO_CREATE_OBJECTS: true, + SOCIAL_AUTH_SAML_ENABLED_IDPS: {}, + SOCIAL_AUTH_SAML_EXTRA_DATA: [], + SOCIAL_AUTH_SAML_ORGANIZATION_ATTR: {}, + SOCIAL_AUTH_SAML_ORGANIZATION_MAP: {}, + SOCIAL_AUTH_SAML_ORG_INFO: {}, + SOCIAL_AUTH_SAML_SP_ENTITY_ID: 'new_id', + SOCIAL_AUTH_SAML_SP_EXTRA: {}, + SOCIAL_AUTH_SAML_SP_PRIVATE_KEY: '$encrypted$', + SOCIAL_AUTH_SAML_SP_PUBLIC_CERT: 'mock_cert', + SOCIAL_AUTH_SAML_SUPPORT_CONTACT: {}, + SOCIAL_AUTH_SAML_TEAM_ATTR: {}, + SOCIAL_AUTH_SAML_TEAM_MAP: {}, + SOCIAL_AUTH_SAML_TECHNICAL_CONTACT: {}, + SOCIAL_AUTH_SAML_SECURITY_CONFIG: { + requestedAuthnContext: false, + }, + }); + }); + + test('should navigate to saml detail on successful submission', async () => { + await act(async () => { + wrapper.find('Form').invoke('onSubmit')(); + }); + expect(history.location.pathname).toEqual('/settings/saml/details'); + }); + + test('should navigate to saml detail when cancel is clicked', async () => { + await act(async () => { + wrapper.find('button[aria-label="Cancel"]').invoke('onClick')(); + }); + expect(history.location.pathname).toEqual('/settings/saml/details'); + }); + + test('should display error message on unsuccessful submission', async () => { + const error = { + response: { + data: { detail: 'An error occurred' }, + }, + }; + SettingsAPI.updateAll.mockImplementation(() => Promise.reject(error)); + expect(wrapper.find('FormSubmitError').length).toBe(0); + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(0); + await act(async () => { + wrapper.find('Form').invoke('onSubmit')(); + }); + wrapper.update(); + expect(wrapper.find('FormSubmitError').length).toBe(1); + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(1); + }); + + test('should display ContentError on throw', async () => { + SettingsAPI.readCategory.mockImplementationOnce(() => + Promise.reject(new Error()) + ); + await act(async () => { + wrapper = mountWithContexts( + + + + ); + }); + await waitForElement(wrapper, 'ContentLoading', el => el.length === 0); + expect(wrapper.find('ContentError').length).toBe(1); + }); }); diff --git a/awx/ui_next/src/screens/Setting/UI/UI.test.jsx b/awx/ui_next/src/screens/Setting/UI/UI.test.jsx index ac7a31d608..fc5aafadcd 100644 --- a/awx/ui_next/src/screens/Setting/UI/UI.test.jsx +++ b/awx/ui_next/src/screens/Setting/UI/UI.test.jsx @@ -6,11 +6,17 @@ import { waitForElement, } from '../../../../testUtils/enzymeHelpers'; import { SettingsAPI } from '../../../api'; +import { SettingsProvider } from '../../../contexts/Settings'; +import mockAllOptions from '../shared/data.allSettingOptions.json'; import UI from './UI'; jest.mock('../../../api/models/Settings'); SettingsAPI.readCategory.mockResolvedValue({ - data: {}, + data: { + CUSTOM_LOGIN_INFO: '', + CUSTOM_LOGO: '', + PENDO_TRACKING_STATE: 'off', + }, }); describe('', () => { @@ -26,9 +32,14 @@ describe('', () => { initialEntries: ['/settings/ui/details'], }); await act(async () => { - wrapper = mountWithContexts(, { - context: { router: { history } }, - }); + wrapper = mountWithContexts( + + + , + { + context: { router: { history } }, + } + ); }); await waitForElement(wrapper, 'ContentLoading', el => el.length === 0); expect(wrapper.find('UIDetail').length).toBe(1); @@ -39,9 +50,14 @@ describe('', () => { initialEntries: ['/settings/ui/edit'], }); await act(async () => { - wrapper = mountWithContexts(, { - context: { router: { history } }, - }); + wrapper = mountWithContexts( + + + , + { + context: { router: { history } }, + } + ); }); await waitForElement(wrapper, 'ContentLoading', el => el.length === 0); expect(wrapper.find('UIEdit').length).toBe(1); diff --git a/awx/ui_next/src/screens/Setting/UI/UIEdit/UIEdit.jsx b/awx/ui_next/src/screens/Setting/UI/UIEdit/UIEdit.jsx index c8d0f4df78..937c0c3e66 100644 --- a/awx/ui_next/src/screens/Setting/UI/UIEdit/UIEdit.jsx +++ b/awx/ui_next/src/screens/Setting/UI/UIEdit/UIEdit.jsx @@ -1,25 +1,128 @@ -import React from 'react'; -import { Link } from 'react-router-dom'; -import { withI18n } from '@lingui/react'; -import { t } from '@lingui/macro'; -import { Button } from '@patternfly/react-core'; -import { CardBody, CardActionsRow } from '../../../../components/Card'; +import React, { useCallback, useEffect } from 'react'; +import { useHistory } from 'react-router-dom'; +import { Formik } from 'formik'; +import { Form } from '@patternfly/react-core'; +import { CardBody } from '../../../../components/Card'; +import ContentError from '../../../../components/ContentError'; +import ContentLoading from '../../../../components/ContentLoading'; +import { FormSubmitError } from '../../../../components/FormField'; +import { FormColumnLayout } from '../../../../components/FormLayout'; +import { useSettings } from '../../../../contexts/Settings'; +import { RevertAllAlert, RevertFormActionGroup } from '../../shared'; +import { + ChoiceField, + FileUploadField, + TextAreaField, +} from '../../shared/SharedFields'; +import useModal from '../../../../util/useModal'; +import useRequest from '../../../../util/useRequest'; +import { SettingsAPI } from '../../../../api'; + +function UIEdit() { + const history = useHistory(); + const { isModalOpen, toggleModal, closeModal } = useModal(); + const { PUT: options } = useSettings(); + + const { isLoading, error, request: fetchUI, result: uiData } = useRequest( + useCallback(async () => { + const { data } = await SettingsAPI.readCategory('ui'); + const mergedData = {}; + Object.keys(data).forEach(key => { + if (!options[key]) { + return; + } + mergedData[key] = options[key]; + mergedData[key].value = data[key]; + }); + return mergedData; + }, [options]), + null + ); + + useEffect(() => { + fetchUI(); + }, [fetchUI]); + + const { error: submitError, request: submitForm } = useRequest( + useCallback( + async values => { + await SettingsAPI.updateAll(values); + history.push('/settings/ui/details'); + }, + [history] + ), + null + ); + + const handleSubmit = async form => { + await submitForm(form); + }; + + const handleRevertAll = async () => { + const defaultValues = Object.assign( + ...Object.entries(uiData).map(([key, value]) => ({ + [key]: value.default, + })) + ); + await submitForm(defaultValues); + closeModal(); + }; + + const handleCancel = () => { + history.push('/settings/ui/details'); + }; -function UIEdit({ i18n }) { return ( - {i18n._(t`Edit form coming soon :)`)} - - - + {formik => ( +
+ + {uiData?.PENDO_TRACKING_STATE?.value !== 'off' && ( + + )} + + + {submitError && } + + + {isModalOpen && ( + + )} + + )} + + )}
); } -export default withI18n()(UIEdit); +export default UIEdit; diff --git a/awx/ui_next/src/screens/Setting/UI/UIEdit/UIEdit.test.jsx b/awx/ui_next/src/screens/Setting/UI/UIEdit/UIEdit.test.jsx index c51fb06fa7..adb43a788c 100644 --- a/awx/ui_next/src/screens/Setting/UI/UIEdit/UIEdit.test.jsx +++ b/awx/ui_next/src/screens/Setting/UI/UIEdit/UIEdit.test.jsx @@ -1,16 +1,151 @@ import React from 'react'; -import { mountWithContexts } from '../../../../../testUtils/enzymeHelpers'; +import { act } from 'react-dom/test-utils'; +import { createMemoryHistory } from 'history'; +import { + mountWithContexts, + waitForElement, +} from '../../../../../testUtils/enzymeHelpers'; +import mockAllOptions from '../../shared/data.allSettingOptions.json'; +import { SettingsProvider } from '../../../../contexts/Settings'; +import { SettingsAPI } from '../../../../api'; import UIEdit from './UIEdit'; +jest.mock('../../../../api/models/Settings'); +SettingsAPI.updateAll.mockResolvedValue({}); +SettingsAPI.readCategory.mockResolvedValue({ + data: { + CUSTOM_LOGIN_INFO: 'mock info', + CUSTOM_LOGO: 'data:mock/jpeg;', + PENDO_TRACKING_STATE: 'detailed', + }, +}); + describe('', () => { let wrapper; - beforeEach(() => { - wrapper = mountWithContexts(); - }); + let history; + afterEach(() => { wrapper.unmount(); + jest.clearAllMocks(); }); + + beforeEach(async () => { + history = createMemoryHistory({ + initialEntries: ['/settings/ui/edit'], + }); + await act(async () => { + wrapper = mountWithContexts( + + + , + { + context: { router: { history } }, + } + ); + }); + await waitForElement(wrapper, 'ContentLoading', el => el.length === 0); + }); + test('initially renders without crashing', () => { expect(wrapper.find('UIEdit').length).toBe(1); }); + + test('should display expected form fields', async () => { + expect(wrapper.find('FormGroup[label="Custom Login Info"]').length).toBe(1); + expect(wrapper.find('FormGroup[label="Custom Logo"]').length).toBe(1); + expect( + wrapper.find('FormGroup[label="User Analytics Tracking State"]').length + ).toBe(1); + }); + + test('should successfully send default values to api on form revert all', async () => { + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(0); + expect(wrapper.find('RevertAllAlert')).toHaveLength(0); + await act(async () => { + wrapper + .find('button[aria-label="Revert all to default"]') + .invoke('onClick')(); + }); + wrapper.update(); + expect(wrapper.find('RevertAllAlert')).toHaveLength(1); + await act(async () => { + wrapper + .find('RevertAllAlert button[aria-label="Confirm revert all"]') + .invoke('onClick')(); + }); + wrapper.update(); + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(1); + expect(SettingsAPI.updateAll).toHaveBeenCalledWith({ + CUSTOM_LOGIN_INFO: '', + CUSTOM_LOGO: '', + PENDO_TRACKING_STATE: 'off', + }); + }); + + test('should successfully send request to api on form submission', async () => { + act(() => { + wrapper.find('textarea#CUSTOM_LOGIN_INFO').simulate('change', { + target: { value: 'new login info', name: 'CUSTOM_LOGIN_INFO' }, + }); + wrapper + .find('FormGroup[fieldId="CUSTOM_LOGO"] button[aria-label="Revert"]') + .invoke('onClick')(); + }); + wrapper.update(); + await act(async () => { + wrapper.find('Form').invoke('onSubmit')(); + }); + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(1); + expect(SettingsAPI.updateAll).toHaveBeenCalledWith({ + CUSTOM_LOGIN_INFO: 'new login info', + CUSTOM_LOGO: '', + PENDO_TRACKING_STATE: 'detailed', + }); + }); + + test('should navigate to ui detail on successful submission', async () => { + await act(async () => { + wrapper.find('Form').invoke('onSubmit')(); + }); + expect(history.location.pathname).toEqual('/settings/ui/details'); + }); + + test('should navigate to ui detail when cancel is clicked', async () => { + await act(async () => { + wrapper.find('button[aria-label="Cancel"]').invoke('onClick')(); + }); + expect(history.location.pathname).toEqual('/settings/ui/details'); + }); + + test('should display error message on unsuccessful submission', async () => { + const error = { + response: { + data: { detail: 'An error occurred' }, + }, + }; + SettingsAPI.updateAll.mockImplementation(() => Promise.reject(error)); + expect(wrapper.find('FormSubmitError').length).toBe(0); + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(0); + await act(async () => { + wrapper.find('Form').invoke('onSubmit')(); + }); + wrapper.update(); + expect(wrapper.find('FormSubmitError').length).toBe(1); + expect(SettingsAPI.updateAll).toHaveBeenCalledTimes(1); + }); + + test('should display ContentError on throw', async () => { + SettingsAPI.readCategory.mockImplementationOnce(() => + Promise.reject(new Error()) + ); + await act(async () => { + wrapper = mountWithContexts( + + + + ); + }); + await waitForElement(wrapper, 'ContentLoading', el => el.length === 0); + expect(wrapper.find('ContentError').length).toBe(1); + }); }); diff --git a/awx/ui_next/src/screens/Setting/shared/RevertButton.jsx b/awx/ui_next/src/screens/Setting/shared/RevertButton.jsx index f0fe7e8b72..a997388395 100644 --- a/awx/ui_next/src/screens/Setting/shared/RevertButton.jsx +++ b/awx/ui_next/src/screens/Setting/shared/RevertButton.jsx @@ -13,7 +13,13 @@ const ButtonWrapper = styled.div` } `; -function RevertButton({ i18n, id, defaultValue, isDisabled = false }) { +function RevertButton({ + i18n, + id, + defaultValue, + isDisabled = false, + onRevertCallback = () => null, +}) { const [field, meta, helpers] = useField(id); const initialValue = meta.initialValue ?? ''; const currentValue = field.value; @@ -30,6 +36,7 @@ function RevertButton({ i18n, id, defaultValue, isDisabled = false }) { function handleConfirm() { helpers.setValue(isRevertable ? defaultValue : initialValue); + onRevertCallback(); } const revertTooltipContent = isRevertable diff --git a/awx/ui_next/src/screens/Setting/shared/SettingDetail.jsx b/awx/ui_next/src/screens/Setting/shared/SettingDetail.jsx index ddcb5fb44d..d58c89e721 100644 --- a/awx/ui_next/src/screens/Setting/shared/SettingDetail.jsx +++ b/awx/ui_next/src/screens/Setting/shared/SettingDetail.jsx @@ -34,6 +34,18 @@ export default withI18n()( /> ); break; + case 'certificate': + detail = ( + + ); + break; case 'image': detail = ( ( } @@ -220,6 +225,44 @@ InputField.propTypes = { isRequired: bool, }; +const TextAreaField = withI18n()( + ({ i18n, name, config, isRequired = false }) => { + const validate = isRequired ? required(null, i18n) : null; + const [field, meta] = useField({ name, validate }); + const isValid = !(meta.touched && meta.error); + + return config ? ( + +