Commit 703a148c authored by Paul Gascou-Vaillancourt's avatar Paul Gascou-Vaillancourt Committed by Enrique Alcántara

Automatically select DAST profile

When there is only a single profile available in an on-demand scan's
profile selector, it is automatically selected to save the user some
clicks and to prevent potential confusion.
parent 0733c8bf
......@@ -30,7 +30,7 @@ import ProfileSelectorSummaryCell from './profile_selector/summary_cell.vue';
import ScannerProfileSelector from './profile_selector/scanner_profile_selector.vue';
import SiteProfileSelector from './profile_selector/site_profile_selector.vue';
const createProfilesApolloOptions = (name, { fetchQuery, fetchError }) => ({
const createProfilesApolloOptions = (name, field, { fetchQuery, fetchError }) => ({
query: fetchQuery,
variables() {
return {
......@@ -39,6 +39,9 @@ const createProfilesApolloOptions = (name, { fetchQuery, fetchError }) => ({
},
update(data) {
const edges = data?.project?.[name]?.edges ?? [];
if (edges.length === 1) {
this[field] = edges[0].node.id;
}
return edges.map(({ node }) => node);
},
error(e) {
......@@ -66,8 +69,16 @@ export default {
},
mixins: [glFeatureFlagsMixin()],
apollo: {
scannerProfiles: createProfilesApolloOptions('scannerProfiles', SCANNER_PROFILES_QUERY),
siteProfiles: createProfilesApolloOptions('siteProfiles', SITE_PROFILES_QUERY),
scannerProfiles: createProfilesApolloOptions(
'scannerProfiles',
'selectedScannerProfileId',
SCANNER_PROFILES_QUERY,
),
siteProfiles: createProfilesApolloOptions(
'siteProfiles',
'selectedSiteProfileId',
SITE_PROFILES_QUERY,
),
},
props: {
helpPagePath: {
......@@ -104,8 +115,8 @@ export default {
return {
scannerProfiles: [],
siteProfiles: [],
selectedScannerProfile: null,
selectedSiteProfile: null,
selectedScannerProfileId: null,
selectedSiteProfileId: null,
loading: false,
errorType: null,
errors: [],
......@@ -113,6 +124,16 @@ export default {
};
},
computed: {
selectedScannerProfile() {
return this.selectedScannerProfileId
? this.scannerProfiles.find(({ id }) => id === this.selectedScannerProfileId)
: null;
},
selectedSiteProfile() {
return this.selectedSiteProfileId
? this.siteProfiles.find(({ id }) => id === this.selectedSiteProfileId)
: null;
},
errorMessage() {
return ERROR_MESSAGES[this.errorType] || null;
},
......@@ -238,37 +259,37 @@ export default {
</template>
<template v-else-if="!failedToLoadProfiles">
<scanner-profile-selector
v-model="selectedScannerProfile"
v-model="selectedScannerProfileId"
class="gl-mb-5"
:profiles="scannerProfiles"
>
<template #summary="{ profile }">
<template v-if="selectedScannerProfile" #summary>
<div class="row">
<profile-selector-summary-cell
:class="{ 'gl-text-red-500': hasProfilesConflict }"
:label="s__('DastProfiles|Scan mode')"
:value="$options.SCAN_TYPE_LABEL[profile.scanType]"
:value="$options.SCAN_TYPE_LABEL[selectedScannerProfile.scanType]"
/>
</div>
<div class="row">
<profile-selector-summary-cell
:label="s__('DastProfiles|Spider timeout')"
:value="n__('%d minute', '%d minutes', profile.spiderTimeout)"
:value="n__('%d minute', '%d minutes', selectedScannerProfile.spiderTimeout)"
/>
<profile-selector-summary-cell
:label="s__('DastProfiles|Target timeout')"
:value="n__('%d second', '%d seconds', profile.targetTimeout)"
:value="n__('%d second', '%d seconds', selectedScannerProfile.targetTimeout)"
/>
</div>
<div class="row">
<profile-selector-summary-cell
:label="s__('DastProfiles|AJAX spider')"
:value="profile.useAjaxSpider ? __('On') : __('Off')"
:value="selectedScannerProfile.useAjaxSpider ? __('On') : __('Off')"
/>
<profile-selector-summary-cell
:label="s__('DastProfiles|Debug messages')"
:value="
profile.showDebugMessages
selectedScannerProfile.showDebugMessages
? s__('DastProfiles|Show debug messages')
: s__('DastProfiles|Hide debug messages')
"
......@@ -276,13 +297,17 @@ export default {
</div>
</template>
</scanner-profile-selector>
<site-profile-selector v-model="selectedSiteProfile" class="gl-mb-5" :profiles="siteProfiles">
<template #summary="{ profile }">
<site-profile-selector
v-model="selectedSiteProfileId"
class="gl-mb-5"
:profiles="siteProfiles"
>
<template v-if="selectedSiteProfile" #summary>
<div class="row">
<profile-selector-summary-cell
:class="{ 'gl-text-red-500': hasProfilesConflict }"
:label="s__('DastProfiles|Target URL')"
:value="profile.targetUrl"
:value="selectedSiteProfile.targetUrl"
/>
</div>
</template>
......
......@@ -25,14 +25,14 @@ export default {
default: () => [],
},
value: {
type: Object,
type: String,
required: false,
default: null,
},
},
methods: {
isChecked({ id }) {
return this.value?.id === id;
computed: {
selectedProfile() {
return this.value ? this.profiles.find(({ id }) => this.value === id) : null;
},
},
};
......@@ -67,7 +67,9 @@ export default {
</template>
<gl-dropdown
:text="
value ? value.dropdownLabel : s__('OnDemandScans|Select one of the existing profiles')
selectedProfile
? selectedProfile.dropdownLabel
: s__('OnDemandScans|Select one of the existing profiles')
"
class="mw-460"
data-testid="profiles-dropdown"
......@@ -75,9 +77,9 @@ export default {
<gl-dropdown-item
v-for="profile in profiles"
:key="profile.id"
:is-checked="isChecked(profile)"
:is-checked="value === profile.id"
is-check-item
@click="$emit('input', profile)"
@click="$emit('input', profile.id)"
>
{{ profile.profileName }}
</gl-dropdown-item>
......@@ -87,7 +89,7 @@ export default {
data-testid="selected-profile-summary"
class="gl-mt-6 gl-pt-6 gl-border-t-solid gl-border-gray-100 gl-border-t-1"
>
<slot name="summary" :profile="value"></slot>
<slot name="summary"></slot>
</div>
</gl-form-group>
<template v-else>
......
......@@ -57,8 +57,8 @@ export default {
)
}}</template>
<template #new-profile>{{ s__('OnDemandScans|Create a new scanner profile') }}</template>
<template #summary="{ profile }">
<slot name="summary" :profile="profile"></slot>
<template #summary>
<slot name="summary"></slot>
</template>
</profile-selector>
</template>
......@@ -60,8 +60,8 @@ export default {
)
}}</template>
<template #new-profile>{{ s__('OnDemandScans|Create a new site profile') }}</template>
<template #summary="{ profile }">
<slot name="summary" :profile="profile"></slot>
<template #summary>
<slot name="summary"></slot>
</template>
</profile-selector>
</template>
---
title: 'On-demand scans: automatically select DAST profile when only one is available'
merge_request: 49435
author:
type: changed
import { GlForm, GlSkeletonLoader } from '@gitlab/ui';
import { shallowMount, mount } from '@vue/test-utils';
import { shallowMount, mount, createLocalVue } from '@vue/test-utils';
import { merge } from 'lodash';
import VueApollo from 'vue-apollo';
import createApolloProvider from 'helpers/mock_apollo_helper';
import OnDemandScansForm from 'ee/on_demand_scans/components/on_demand_scans_form.vue';
import ScannerProfileSelector from 'ee/on_demand_scans/components/profile_selector/scanner_profile_selector.vue';
import SiteProfileSelector from 'ee/on_demand_scans/components/profile_selector/site_profile_selector.vue';
import dastOnDemandScanCreate from 'ee/on_demand_scans/graphql/dast_on_demand_scan_create.mutation.graphql';
import dastScannerProfilesQuery from 'ee/security_configuration/dast_profiles/graphql/dast_scanner_profiles.query.graphql';
import dastSiteProfilesQuery from 'ee/security_configuration/dast_profiles/graphql/dast_site_profiles.query.graphql';
import * as responses from '../mocks/apollo_mocks';
import { scannerProfiles, siteProfiles } from '../mocks/mock_data';
import { redirectTo } from '~/lib/utils/url_utility';
import { scannerProfiles, siteProfiles } from '../mock_data';
const helpPagePath = '/application_security/dast/index#on-demand-scans';
const projectPath = 'group/project';
......@@ -22,17 +27,6 @@ const defaultProps = {
defaultBranch,
};
const defaultMocks = {
$apollo: {
mutate: jest.fn(),
queries: {
scannerProfiles: {},
siteProfiles: {},
},
addSmartQuery: jest.fn(),
},
};
const pipelineUrl = `/${projectPath}/pipelines/123`;
const [passiveScannerProfile, activeScannerProfile] = scannerProfiles;
const [nonValidatedSiteProfile, validatedSiteProfile] = siteProfiles;
......@@ -43,7 +37,9 @@ jest.mock('~/lib/utils/url_utility', () => ({
}));
describe('OnDemandScansForm', () => {
let localVue;
let subject;
let requestHandlers;
const findForm = () => subject.find(GlForm);
const findByTestId = testId => subject.find(`[data-testid="${testId}"]`);
......@@ -52,13 +48,44 @@ describe('OnDemandScansForm', () => {
const findSubmitButton = () => findByTestId('on-demand-scan-submit-button');
const setValidFormData = () => {
subject.find(ScannerProfileSelector).vm.$emit('input', passiveScannerProfile);
subject.find(SiteProfileSelector).vm.$emit('input', nonValidatedSiteProfile);
subject.find(ScannerProfileSelector).vm.$emit('input', passiveScannerProfile.id);
subject.find(SiteProfileSelector).vm.$emit('input', nonValidatedSiteProfile.id);
return subject.vm.$nextTick();
};
const submitForm = () => findForm().vm.$emit('submit', { preventDefault: () => {} });
const subjectMounterFactory = (mountFn = shallowMount) => (options = {}) => {
const createMockApolloProvider = handlers => {
localVue.use(VueApollo);
requestHandlers = {
dastScannerProfiles: jest.fn().mockResolvedValue(responses.dastScannerProfiles()),
dastSiteProfiles: jest.fn().mockResolvedValue(responses.dastSiteProfiles()),
...handlers,
};
return createApolloProvider([
[dastScannerProfilesQuery, requestHandlers.dastScannerProfiles],
[dastSiteProfilesQuery, requestHandlers.dastSiteProfiles],
]);
};
const subjectMounterFactory = (mountFn = shallowMount) => (options = {}, withHandlers) => {
localVue = createLocalVue();
let defaultMocks = {
$apollo: {
mutate: jest.fn(),
queries: {
scannerProfiles: {},
siteProfiles: {},
},
addSmartQuery: jest.fn(),
},
};
let apolloProvider;
if (withHandlers) {
apolloProvider = createMockApolloProvider(withHandlers);
defaultMocks = {};
}
subject = mountFn(
OnDemandScansForm,
merge(
......@@ -76,7 +103,7 @@ describe('OnDemandScansForm', () => {
},
},
},
options,
{ ...options, localVue, apolloProvider },
{
data() {
return { ...options.data };
......@@ -243,8 +270,8 @@ describe('OnDemandScansForm', () => {
'profiles conflict prevention',
({ description, selectedScannerProfile, selectedSiteProfile, hasConflict }) => {
const setFormData = () => {
subject.find(ScannerProfileSelector).vm.$emit('input', selectedScannerProfile);
subject.find(SiteProfileSelector).vm.$emit('input', selectedSiteProfile);
subject.find(ScannerProfileSelector).vm.$emit('input', selectedScannerProfile.id);
subject.find(SiteProfileSelector).vm.$emit('input', selectedSiteProfile.id);
return subject.vm.$nextTick();
};
......@@ -253,7 +280,12 @@ describe('OnDemandScansForm', () => {
? `warns about conflicting profiles when user selects ${description}`
: `does not report any conflict when user selects ${description}`,
async () => {
mountShallowSubject();
mountShallowSubject({
data: {
scannerProfiles,
siteProfiles,
},
});
await setFormData();
expect(findProfilesConflictAlert().exists()).toBe(hasConflict);
......@@ -269,6 +301,10 @@ describe('OnDemandScansForm', () => {
securityOnDemandScansSiteValidation: false,
},
},
data: {
scannerProfiles,
siteProfiles,
},
});
return setFormData();
});
......@@ -280,4 +316,25 @@ describe('OnDemandScansForm', () => {
});
},
);
describe.each`
profileType | query | selector | profiles
${'scanner'} | ${'dastScannerProfiles'} | ${ScannerProfileSelector} | ${scannerProfiles}
${'site'} | ${'dastSiteProfiles'} | ${SiteProfileSelector} | ${siteProfiles}
`('when there is a single $profileType profile', ({ query, selector, profiles }) => {
const [profile] = profiles;
beforeEach(() => {
mountShallowSubject(
{},
{
[query]: jest.fn().mockResolvedValue(responses[query]([profile])),
},
);
});
it('automatically selects the only available profile', () => {
expect(subject.find(selector).attributes('value')).toBe(profile.id);
});
});
});
......@@ -4,7 +4,7 @@ exports[`OnDemandScansScannerProfileSelector renders properly with profiles 1`]
<div
class="gl-card"
data-foo="bar"
value="[object Object]"
value="gid://gitlab/DastScannerProfile/1"
>
<div
class="gl-card-header"
......
......@@ -4,7 +4,7 @@ exports[`OnDemandScansSiteProfileSelector renders properly with profiles 1`] = `
<div
class="gl-card"
data-foo="bar"
value="[object Object]"
value="gid://gitlab/DastSiteProfile/1"
>
<div
class="gl-card-header"
......
......@@ -2,7 +2,7 @@ import { GlDropdownItem } from '@gitlab/ui';
import { mount } from '@vue/test-utils';
import { merge } from 'lodash';
import OnDemandScansProfileSelector from 'ee/on_demand_scans/components/profile_selector/profile_selector.vue';
import { scannerProfiles } from '../../mock_data';
import { scannerProfiles } from '../../mocks/mock_data';
describe('OnDemandScansProfileSelector', () => {
let wrapper;
......@@ -41,12 +41,10 @@ describe('OnDemandScansProfileSelector', () => {
slots: {
title: 'Section title',
label: 'Use existing scanner profile',
summary: `<div>Profile's summary</div>`,
'no-profiles': 'No profile yet',
'new-profile': 'Create a new profile',
},
scopedSlots: {
summary: "<div>{{ props.profile.profileName }}'s summary</div>",
},
},
options,
),
......@@ -105,7 +103,7 @@ describe('OnDemandScansProfileSelector', () => {
it('when a profile is selected, input event is emitted', async () => {
await selectFirstProfile();
expect(wrapper.emitted('input')).toEqual([[scannerProfiles[0]]]);
expect(wrapper.emitted('input')).toEqual([[scannerProfiles[0].id]]);
});
it('shows dropdown items for each profile', () => {
......@@ -130,7 +128,7 @@ describe('OnDemandScansProfileSelector', () => {
createFullComponent({
propsData: {
profiles: scannerProfiles,
value: selectedProfile,
value: selectedProfile.id,
},
});
});
......@@ -139,7 +137,7 @@ describe('OnDemandScansProfileSelector', () => {
const summary = findSelectedProfileSummary();
expect(summary.exists()).toBe(true);
expect(summary.text()).toContain(`${scannerProfiles[0].profileName}'s summary`);
expect(summary.text()).toContain(`Profile's summary`);
});
it('displays item as checked', () => {
......
......@@ -2,7 +2,7 @@ import { mount, shallowMount } from '@vue/test-utils';
import { merge } from 'lodash';
import ProfileSelector from 'ee/on_demand_scans/components/profile_selector/profile_selector.vue';
import OnDemandScansScannerProfileSelector from 'ee/on_demand_scans/components/profile_selector/scanner_profile_selector.vue';
import { scannerProfiles } from '../../mock_data';
import { scannerProfiles } from '../../mocks/mock_data';
const TEST_LIBRARY_PATH = '/test/scanner/profiles/library/path';
const TEST_NEW_PATH = '/test/new/scanner/profile/path';
......@@ -31,8 +31,8 @@ describe('OnDemandScansScannerProfileSelector', () => {
newScannerProfilePath: TEST_NEW_PATH,
glFeatures: { securityOnDemandScansSiteValidation: true },
},
scopedSlots: {
summary: '<div slot-scope="{ profile }">{{ profile.profileName }}\'s summary</div>',
slots: {
summary: `<div>${profiles[0].profileName}'s summary</div>`,
},
},
options,
......@@ -50,7 +50,7 @@ describe('OnDemandScansScannerProfileSelector', () => {
it('renders properly with profiles', () => {
createFullComponent({
propsData: { profiles, value: profiles[0] },
propsData: { profiles, value: profiles[0].id },
});
expect(wrapper.element).toMatchSnapshot();
......
......@@ -2,7 +2,7 @@ import { mount, shallowMount } from '@vue/test-utils';
import { merge } from 'lodash';
import ProfileSelector from 'ee/on_demand_scans/components/profile_selector/profile_selector.vue';
import OnDemandScansSiteProfileSelector from 'ee/on_demand_scans/components/profile_selector/site_profile_selector.vue';
import { siteProfiles } from '../../mock_data';
import { siteProfiles } from '../../mocks/mock_data';
const TEST_LIBRARY_PATH = '/test/site/profiles/library/path';
const TEST_NEW_PATH = '/test/new/site/profile/path';
......@@ -34,8 +34,8 @@ describe('OnDemandScansSiteProfileSelector', () => {
newSiteProfilePath: TEST_NEW_PATH,
glFeatures: { securityOnDemandScansSiteValidation: true },
},
scopedSlots: {
summary: '<div slot-scope="{ profile }">{{ profile.profileName }}\'s summary</div>',
slots: {
summary: `<div>${profiles[0].profileName}'s summary</div>`,
},
},
options,
......@@ -53,7 +53,7 @@ describe('OnDemandScansSiteProfileSelector', () => {
it('renders properly with profiles', () => {
createFullComponent({
propsData: { profiles, value: profiles[0] },
propsData: { profiles, value: profiles[0].id },
});
expect(wrapper.element).toMatchSnapshot();
......
import { scannerProfiles, siteProfiles } from './mock_data';
const defaults = {
pageInfo: {
hasNextPage: false,
hasPreviousPage: false,
startCursor: null,
endCursor: null,
},
};
export const dastScannerProfiles = (profiles = scannerProfiles) => ({
data: {
project: {
scannerProfiles: {
...defaults,
edges: profiles.map(profile => ({
cursor: '',
node: profile,
})),
},
},
},
});
export const dastSiteProfiles = (profiles = siteProfiles) => ({
data: {
project: {
siteProfiles: {
...defaults,
edges: profiles.map(profile => ({
cursor: '',
node: profile,
})),
},
},
},
});
......@@ -7,6 +7,7 @@ export const scannerProfiles = [
scanType: 'PASSIVE',
useAjaxSpider: false,
showDebugMessages: false,
editPath: '/scanner_profile/edit/1',
},
{
id: 'gid://gitlab/DastScannerProfile/2',
......@@ -16,6 +17,7 @@ export const scannerProfiles = [
scanType: 'ACTIVE',
useAjaxSpider: true,
showDebugMessages: true,
editPath: '/scanner_profile/edit/2',
},
];
......@@ -24,12 +26,16 @@ export const siteProfiles = [
id: 'gid://gitlab/DastSiteProfile/1',
profileName: 'Site profile #1',
targetUrl: 'https://foo.com',
normalizedTargetUrl: 'https://foo.com:443',
editPath: '/site_profiles/edit/1',
validationStatus: 'PENDING_VALIDATION',
},
{
id: 'gid://gitlab/DastSiteProfile/2',
profileName: 'Site profile #2',
targetUrl: 'https://bar.com',
normalizedTargetUrl: 'https://bar.com:443',
editPath: '/site_profiles/edit/2',
validationStatus: 'PASSED_VALIDATION',
},
];
......@@ -6,7 +6,7 @@ import DastScannerProfileForm from 'ee/security_configuration/dast_scanner_profi
import { SCAN_TYPE } from 'ee/security_configuration/dast_scanner_profiles/constants';
import dastScannerProfileCreateMutation from 'ee/security_configuration/dast_scanner_profiles/graphql/dast_scanner_profile_create.mutation.graphql';
import dastScannerProfileUpdateMutation from 'ee/security_configuration/dast_scanner_profiles/graphql/dast_scanner_profile_update.mutation.graphql';
import { scannerProfiles } from 'ee_jest/on_demand_scans/mock_data';
import { scannerProfiles } from 'ee_jest/on_demand_scans/mocks/mock_data';
import { TEST_HOST } from 'helpers/test_constants';
import { redirectTo } from '~/lib/utils/url_utility';
......
......@@ -7,7 +7,7 @@ import VueApollo from 'vue-apollo';
import DastSiteProfileForm from 'ee/security_configuration/dast_site_profiles_form/components/dast_site_profile_form.vue';
import dastSiteProfileCreateMutation from 'ee/security_configuration/dast_site_profiles_form/graphql/dast_site_profile_create.mutation.graphql';
import dastSiteProfileUpdateMutation from 'ee/security_configuration/dast_site_profiles_form/graphql/dast_site_profile_update.mutation.graphql';
import { siteProfiles } from 'ee_jest/on_demand_scans/mock_data';
import { siteProfiles } from 'ee_jest/on_demand_scans/mocks/mock_data';
import * as responses from 'ee_jest/security_configuration/dast_site_profiles_form/mock_data/apollo_mock';
import { TEST_HOST } from 'helpers/test_constants';
import waitForPromises from 'jest/helpers/wait_for_promises';
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment