Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: secure forms with a captcha according to the ICM server settings #200

Merged
merged 4 commits into from
May 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions e2e/cypress/integration/framework/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,15 @@ export function fillFormField(parent: string, key: string, value: number | strin
const field = form.find(`[data-testing-id="${key}"]`);
expect(field.length).to.equal(1, `expected to find one form field "${key}" in "${parent}"`);
const tagName = field.prop('tagName');
expect(tagName).to.match(/^(INPUT|SELECT)$/);
expect(tagName).to.match(/^(INPUT|SELECT|TEXTAREA)$/);

cy.get(parent).within(() => {
if (tagName === 'INPUT') {
if (/^(INPUT|TEXTAREA)$/.test(tagName)) {
const inputField = cy.get(`[data-testing-id="${key}"]`);
inputField.clear();
if (value) {
inputField.type(value.toString());
inputField.focus().type(value.toString());
}
inputField.blur();
} else if (tagName === 'SELECT') {
if (typeof value === 'number') {
cy.get(`[data-testing-id="${key}"]`)
Expand Down
9 changes: 9 additions & 0 deletions e2e/cypress/integration/pages/account/registration.page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ export class RegistrationPage {
.forEach((key: keyof Registration) => {
fillFormField(this.tag, key, register[key]);
});

// special handling as captcha component steals focus
if (register.login) {
fillFormField(this.tag, 'login', register.login);
}
if (register.password) {
fillFormField(this.tag, 'password', register.password);
}

return this;
}

Expand Down
25 changes: 15 additions & 10 deletions e2e/cypress/integration/pages/contact/contact.page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { fillFormField } from '../../framework';
import { BreadcrumbModule } from '../breadcrumb.module';

declare interface ContactForm {
name: string;
email: string;
phone: string;
subject: string;
comment: string;
}

export class ContactPage {
readonly tag = 'ish-contact-page';
readonly breadcrumb = new BreadcrumbModule();
Expand All @@ -18,17 +27,13 @@ export class ContactPage {
return cy.get('input[data-testing-id="email"]');
}

get phoneInput() {
return cy.get('input[data-testing-id="phone"]');
}
fillForm(content: ContactForm) {
Object.keys(content)
.filter(key => content[key] !== undefined)
.forEach((key: keyof ContactForm) => {
fillFormField(this.tag, key, content[key]);
});

fillForm(name: string, email: string, phone: string, subject: string, comments: string) {
this.nameInput.clear().type(name).blur();
this.emailInput.clear().type(email).blur();
this.phoneInput.clear().type(phone).blur();
// tslint:disable-next-line:ban
cy.get('select[data-testing-id="subject"]').select(subject);
cy.get('textarea[data-testing-id="comments"]').clear().type(comments).blur();
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@ const _ = {
email: 'patricia@test.intershop.de',
password: '!InterShop00!',
fullName: 'Patricia Miller',
formContent: {
phone: '12345',
subject: 'Returns',
comment: "Don't fit.",
},
};

describe('Contact', () => {
it('anonymous user should send the contact successfully', () => {
ContactPage.navigateTo();
at(ContactPage, page => {
page.fillForm(_.fullName, _.email, '12345', 'Returns', "Don't fit.");
page.fillForm({ ..._.formContent, email: _.email, name: _.fullName });
page.submit();
});
at(ContactConfirmationPage, page => {
Expand Down
5 changes: 0 additions & 5 deletions src/app/core/configuration.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import localeDe from '@angular/common/locales/de';
import localeFr from '@angular/common/locales/fr';
import { Inject, LOCALE_ID, NgModule } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { RECAPTCHA_V3_SITE_KEY } from 'ng-recaptcha';

import { environment } from '../../environments/environment';

Expand All @@ -14,8 +13,6 @@ import { ThemeService } from './utils/theme/theme.service';
@NgModule({
imports: [FeatureToggleModule],
providers: [
// tslint:disable-next-line:no-string-literal
{ provide: RECAPTCHA_V3_SITE_KEY, useValue: environment['captchaSiteKey'] },
// tslint:disable-next-line:no-string-literal
{ provide: injectionKeys.MOCK_SERVER_API, useValue: environment['mockServerAPI'] },
// tslint:disable-next-line:no-string-literal
Expand All @@ -28,8 +25,6 @@ import { ThemeService } from './utils/theme/theme.service';
{ provide: injectionKeys.DEFAULT_PRODUCT_LISTING_VIEW_TYPE, useValue: environment.defaultProductListingViewType },
// TODO: get from REST call
{ provide: injectionKeys.USER_REGISTRATION_LOGIN_TYPE, useValue: 'email' },
// tslint:disable-next-line:no-string-literal
{ provide: injectionKeys.CAPTCHA_SITE_KEY, useValue: environment['captchaSiteKey'] },
{ provide: injectionKeys.SMALL_BREAKPOINT_WIDTH, useValue: environment.smallBreakpointWidth },
{ provide: injectionKeys.MEDIUM_BREAKPOINT_WIDTH, useValue: environment.mediumBreakpointWidth },
{ provide: injectionKeys.LARGE_BREAKPOINT_WIDTH, useValue: environment.largeBreakpointWidth },
Expand Down
5 changes: 0 additions & 5 deletions src/app/core/configurations/injection-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,6 @@ export const MEDIUM_BREAKPOINT_WIDTH = new InjectionToken<number>('mediumBreakpo
export const LARGE_BREAKPOINT_WIDTH = new InjectionToken<number>('largeBreakpointWidth');
export const EXTRALARGE_BREAKPOINT_WIDTH = new InjectionToken<number>('extralargeBreakpointWidth');

/**
* The captcha configuration siteKey
*/
export const CAPTCHA_SITE_KEY = new InjectionToken<string>('captchaSiteKey');

/**
* The configured theme for the application (or 'default' if not configured)
*/
Expand Down
7 changes: 7 additions & 0 deletions src/app/core/models/captcha/captcha.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* The contact request to send, when a customer want to get in contact with the shop
*/
export interface Captcha {
captcha?: string;
captchaAction?: string;
}
4 changes: 3 additions & 1 deletion src/app/core/models/contact/contact.model.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Captcha } from 'ish-core/models/captcha/captcha.model';

/**
* The contact request to send, when a customer want to get in contact with the shop
*/
export interface Contact {
export interface Contact extends Captcha {
name: string;
type?: string;
email: string;
Expand Down
5 changes: 2 additions & 3 deletions src/app/core/models/customer/customer.model.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Address } from 'ish-core/models/address/address.model';
import { Captcha } from 'ish-core/models/captcha/captcha.model';
import { Credentials } from 'ish-core/models/credentials/credentials.model';
import { User } from 'ish-core/models/user/user.model';

Expand Down Expand Up @@ -29,9 +30,7 @@ export interface CustomerUserType {
/**
* registration request data type
*/
export interface CustomerRegistrationType extends CustomerUserType {
export interface CustomerRegistrationType extends CustomerUserType, Captcha {
credentials: Credentials;
address: Address;
captchaResponse?: string;
captchaAction?: string;
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export interface PasswordReminder {
import { Captcha } from 'ish-core/models/captcha/captcha.model';

export interface PasswordReminder extends Captcha {
email: string;
firstName: string;
lastName: string;
answer?: string;
captcha?: string;
captchaAction?: string;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export interface ServerConfigDataEntry {
id: string;
elements?: ServerConfigDataEntry[];
[key: string]: string | boolean | string[] | ServerConfigDataEntry[];
[key: string]: string | boolean | number | string[] | ServerConfigDataEntry[];
}

export interface ServerConfigData {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ describe('Server Config Mapper', () => {
id: 'services',
elements: [
{ id: 'captcha', siteKey: 'ASDF' },
{ id: 'gtm', token: 'QWERTY', monitor: true },
{ id: 'deeper', elements: [{ id: 'hidden', foo: 'bar' }] },
{ id: 'gtm', token: 'QWERTY', monitor: 'true' },
{ id: 'deeper', elements: [{ id: 'hidden', foo: 'bar', num: 123, alt: '123' }] },
],
},
],
Expand All @@ -41,7 +41,9 @@ describe('Server Config Mapper', () => {
},
"deeper": Object {
"hidden": Object {
"alt": 123,
"foo": "bar",
"num": 123,
},
},
"gtm": Object {
Expand Down
23 changes: 20 additions & 3 deletions src/app/core/models/server-config/server-config.mapper.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,35 @@
import { omit } from 'lodash-es';
import { mapValues, omit } from 'lodash-es';

import { ServerConfigData, ServerConfigDataEntry } from './server-config.interface';
import { ServerConfig } from './server-config.model';

export class ServerConfigMapper {
private static transformType(val) {
if (typeof val === 'string') {
if (!isNaN(+val)) {
return +val;
} else if (val === 'true') {
return true;
} else if (val === 'false') {
return false;
}
}
return val;
}

private static mapEntries(entries: ServerConfigDataEntry[]) {
return entries.reduce(
(acc, entry) => ({
...acc,
[entry.id]: Array.isArray(entry.elements)
? // do recursion if elements array is set
ServerConfigMapper.mapEntries(entry.elements)
: // filter out unnecessary 'id' attribute
omit(entry, 'id'),
: mapValues(
// filter out unnecessary 'id' attribute
omit(entry, 'id'),
// transform string types to better values
ServerConfigMapper.transformType
),
}),
{}
);
Expand Down
27 changes: 27 additions & 0 deletions src/app/core/services/api/api.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,5 +487,32 @@ describe('Api Service', () => {
const req = httpTestingController.expectOne(`${REST_URL}/dummy`);
expect(req.request.headers.has(ApiService.TOKEN_HEADER_KEY)).toBeFalse();
});

it('should set Captcha V2 authorization header key when captcha is supplied without captchaAction', () => {
apiService.get('dummy', { captcha: { captcha: 'captchatoken' } }).subscribe(fail, fail, fail);

const req = httpTestingController.expectOne(`${REST_URL}/dummy`);
expect(req.request.headers.get(ApiService.AUTHORIZATION_HEADER_KEY)).toMatchInlineSnapshot(
`"CAPTCHA g-recaptcha-response=captchatoken foo=bar"`
);
});

it('should set Captcha V3 authorization header key when captcha is supplied', () => {
apiService
.get('dummy', { captcha: { captcha: 'captchatoken', captchaAction: 'create_account' } })
.subscribe(fail, fail, fail);

const req = httpTestingController.expectOne(`${REST_URL}/dummy`);
expect(req.request.headers.get(ApiService.AUTHORIZATION_HEADER_KEY)).toMatchInlineSnapshot(
`"CAPTCHA recaptcha_token=captchatoken action=create_account"`
);
});

it('should not set header when captcha config object is empty', () => {
apiService.get('dummy', { captcha: {} }).subscribe(fail, fail, fail);

const req = httpTestingController.expectOne(`${REST_URL}/dummy`);
expect(req.request.headers.get(ApiService.AUTHORIZATION_HEADER_KEY)).toBeFalsy();
});
});
});
33 changes: 31 additions & 2 deletions src/app/core/services/api/api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Store, select } from '@ngrx/store';
import { Observable, OperatorFunction, Subject, forkJoin, of, throwError } from 'rxjs';
import { catchError, concatMap, defaultIfEmpty, filter, map, switchMap, tap, throwIfEmpty } from 'rxjs/operators';

import { Captcha } from 'ish-core/models/captcha/captcha.model';
import { Link } from 'ish-core/models/link/link.model';
import { Locale } from 'ish-core/models/locale/locale.model';
import { getCurrentLocale, getICMServerURL, getRestEndpoint } from 'ish-core/store/configuration';
Expand Down Expand Up @@ -105,6 +106,7 @@ export interface AvailableOptions {
headers?: HttpHeaders;
skipApiErrorHandling?: boolean;
runExclusively?: boolean;
captcha?: Captcha;
}

@Injectable({ providedIn: 'root' })
Expand Down Expand Up @@ -137,17 +139,44 @@ export class ApiService {
: headers;
}

/**
- * sets the request header for the appropriate captcha service
- @param captcha captcha token for captcha V2 and V3
- @param captchaAction captcha action for captcha V3
- @returns HttpHeader http header with captcha Authorization key
- */
private appendCaptchaTokenToHeaders(headers: HttpHeaders, captcha: string, captchaAction: string) {
// testing token gets 'null' from captcha service, so we accept it as a valid value here
if (captchaAction !== undefined) {
// captcha V3
return headers.set(
ApiService.AUTHORIZATION_HEADER_KEY,
`CAPTCHA recaptcha_token=${captcha} action=${captchaAction}`
);
} else {
// captcha V2
// TODO: remove second parameter 'foo=bar' that currently only resolves a shortcoming of the server side implemenation that still requires two parameters
return headers.set(ApiService.AUTHORIZATION_HEADER_KEY, `CAPTCHA g-recaptcha-response=${captcha} foo=bar`);
}
}

/**
* merges supplied and default headers
*/
private constructHeaders(options?: { headers?: HttpHeaders }): HttpHeaders {
private constructHeaders(options?: AvailableOptions): HttpHeaders {
const defaultHeaders = new HttpHeaders().set('content-type', 'application/json').set('Accept', 'application/json');

let newHeaders = defaultHeaders;
if (options && options.headers) {
newHeaders = options.headers.keys().reduce((acc, key) => acc.set(key, options.headers.get(key)), defaultHeaders);
}
return this.appendAPITokenToHeaders(newHeaders);

// testing token gets 'null' from captcha service, so we accept it as a valid value here
if (options && options.captcha && options.captcha.captcha !== undefined) {
return this.appendCaptchaTokenToHeaders(newHeaders, options.captcha.captcha, options.captcha.captchaAction);
} else {
return this.appendAPITokenToHeaders(newHeaders);
}
}

private wrapHttpCall<T>(httpCall: () => Observable<T>, options: AvailableOptions) {
Expand Down
10 changes: 8 additions & 2 deletions src/app/core/services/contact/contact.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Injectable } from '@angular/core';
import { pick } from 'lodash-es';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { Contact } from 'ish-core/models/contact/contact.model';
import { ApiService, unpackEnvelope } from 'ish-core/services/api/api.service';
import { ApiService, AvailableOptions, unpackEnvelope } from 'ish-core/services/api/api.service';

@Injectable({ providedIn: 'root' })
export class ContactService {
Expand All @@ -23,6 +24,11 @@ export class ContactService {
* Send contact us request, when a customer want to get in contact with the shop
*/
createContactRequest(contactData: Contact): Observable<void> {
return this.apiService.post(`contact`, contactData, { skipApiErrorHandling: true });
const options: AvailableOptions = {
skipApiErrorHandling: true,
captcha: pick(contactData, ['captcha', 'captchaAction']),
};

return this.apiService.post(`contact`, { ...contactData, captcha: undefined, captchaAction: undefined }, options);
}
}
4 changes: 2 additions & 2 deletions src/app/core/services/user/user.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ describe('User Service', () => {
});

it("should create a new private user when 'createUser' is called with type 'PrivateCustomer'", done => {
when(apiServiceMock.post(anyString(), anything())).thenReturn(of({}));
when(apiServiceMock.post(anyString(), anything(), anything())).thenReturn(of({}));

const payload = {
customer: { customerNo: '4711', type: 'PrivateCustomer' } as Customer,
Expand All @@ -90,7 +90,7 @@ describe('User Service', () => {
} as CustomerRegistrationType;

userService.createUser(payload).subscribe(() => {
verify(apiServiceMock.post('customers', anything())).once();
verify(apiServiceMock.post('customers', anything(), anything())).once();
done();
});
});
Expand Down
Loading