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

✨Analytics: CookieWriter #18406

Merged
merged 5 commits into from
Sep 28, 2018
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions build-system/conformance-config.textproto
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ requirement: {
whitelist: 'src/experiments.js'
whitelist: 'src/service/cid-api.js'
whitelist: 'src/service/cid-impl.js'
whitelist: 'extensions/amp-analytics/0.1/cookie-writer.js'
}

# Function
Expand Down
1 change: 1 addition & 0 deletions build-system/tasks/presubmit-checks.js
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,7 @@ const forbiddenTermsSrcInclusive = {
whitelist: [
'extensions/amp-form/0.1/amp-form.js',
'src/service/url-replacements-impl.js',
'extensions/amp-analytics/0.1/cookie-writer.js',
],
},
'\\.expandInputValueSync\\(': {
Expand Down
5 changes: 5 additions & 0 deletions extensions/amp-analytics/0.1/amp-analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import {Activity} from './activity-impl';
import {AnalyticsConfig, mergeObjects} from './config';
import {AnalyticsEventType} from './events';
import {CookieWriter} from './cookie-writer';
import {
ExpansionOptions,
installVariableService,
Expand Down Expand Up @@ -211,6 +212,10 @@ export class AmpAnalytics extends AMP.BaseElement {
})
.then(config => {
this.config_ = config;
return new CookieWriter(this.win,
this.element, this.config_).write();
})
.then(() => {
this.transport_ =
new Transport(this.win, this.config_['transport'] || {});
})
Expand Down
153 changes: 153 additions & 0 deletions extensions/amp-analytics/0.1/cookie-writer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {BASE_CID_MAX_AGE_MILLIS} from '../../../src/service/cid-impl';
import {Services} from '../../../src/services';
import {getNameArgs} from './variables';
import {hasOwn} from '../../../src/utils/object';
import {isInFie} from '../../../src/friendly-iframe-embed';
import {isObject} from '../../../src/types';
import {isProxyOrigin} from '../../../src/url';
import {setCookie} from '../../../src/cookies';
import {user} from '../../../src/log';


const TAG = 'amp-analytics/cookie-writer';

const EXPAND_WHITELIST = {
'QUERY_PARAM': true,
// TODO: Add linker_param
};

export class CookieWriter {

/**
* @param {!Window} win
* @param {!Element} element
* @param {!JsonObject} config
*/
constructor(win, element, config) {
/** @private {!Window} */
this.win_ = win;

/** @private {!Element} */
this.element_ = element;

/** @private {!../../../src/service/url-replacements-impl.UrlReplacements} */
this.urlReplacementService_ = Services.urlReplacementsForDoc(element);

/** @private {?Promise} */
this.writePromise_ = null;

/** @private {!JsonObject} */
this.config_ = config;
}

/**
* @return {!Promise}
*/
write() {
if (!this.writePromise_) {
this.writePromise_ = this.init_();
}

return this.writePromise_;
}

/**
* Parse the config and write to cookie
* @return {!Promise}
*/
init_() {
// TODO: Need the consider the case for shadow doc.
if (isInFie(this.element_) || isProxyOrigin(this.win_.location)) {
// Disable cookie writer in friendly iframe and proxy origin.
// Note: It's important to check origin here so that setCookie doesn't
// throw error "should not attempt ot set cookie on proxy origin"
return Promise.resolve();
}


if (!hasOwn(this.config_, 'writeCookies')) {
return Promise.resolve();
}

if (!isObject(this.config_['writeCookies'])) {
user().error(TAG, 'writeCookies config must be an object');
return Promise.resolve();
}

const inputConfig = this.config_['writeCookies'];
const ids = Object.keys(inputConfig);
const promises = [];
for (let i = 0; i < ids.length; i++) {
const cookieName = ids[i];
const cookieValue = inputConfig[cookieName];
if (this.isCookieValueStringValid_(cookieValue)) {
promises.push(this.expandAndWrite_(cookieName, cookieValue));
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

print user error otherwise

}

return Promise.all(promises);
}

/**
* Check whether the cookie value is supported. Currently only support
* QUERY_PARAM(***)
* @param {*} str
* @return {boolean}
*/
isCookieValueStringValid_(str) {
if (typeof str !== 'string') {
user().error(TAG, 'cookie value needs to be a string');
return false;
}

// Make sure that only QUERY_PARAM and LINKER_PARAM is supported
const {name} = getNameArgs(str);
if (!EXPAND_WHITELIST[name]) {
user().error(TAG, `cookie value ${str} not supported. ` +
'Only QUERY_PARAM is supported');
return false;
}

return true;
}

/**
* Expand the value and write to cookie if necessary
* @param {string} cookieName
* @param {string} cookieValue
* @return {!Promise}
*/
expandAndWrite_(cookieName, cookieValue) {
// Note: Have to use `expandStringAsync` because QUERY_PARAM can wait for
// trackImpressionPromise and resolve async
return this.urlReplacementService_.expandStringAsync(cookieValue,
/* TODO: Add opt_binding */ undefined, EXPAND_WHITELIST).then(
value => {
// Note: We ignore empty cookieValue, that means currently we don't
// provide a way to overwrite or erase existing cookie
if (value) {
const expireDate = Date.now() + BASE_CID_MAX_AGE_MILLIS;
setCookie(this.win_, cookieName, value, expireDate);
}
}).catch(e => {
user().error(TAG, 'Error expanding cookie string', e);
});
}
}

210 changes: 210 additions & 0 deletions extensions/amp-analytics/0.1/test/test-cookie-writer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as cookie from '../../../../src/cookies';
import {CookieWriter} from '../cookie-writer';
import {dict} from '../../../../src/utils/object';


const TAG = '[amp-analytics/cookie-writer]';

describes.realWin('amp-analytics.cookie-writer', {
amp: true,
runtimeOn: true,
}, env => {

let sandbox;
let win;
let doc;
let setCookieSpy;
let element;

beforeEach(() => {
sandbox = env.sandbox;
setCookieSpy = sandbox.spy();
win = env.win;
doc = win.document;
sandbox.stub(cookie, 'setCookie').callsFake(
(win, name, value) => {
setCookieSpy(name, value);
});
element = doc.createElement('div');
doc.body.appendChild(element);
});

describe('write with condition', () => {
let expandAndWriteSpy;

it('Resolve when no config', () => {
const config = dict({});
const cookieWriter = new CookieWriter(win, element, config);
expandAndWriteSpy = sandbox.spy(cookieWriter, 'expandAndWrite_');
return cookieWriter.write().then(() => {
expect(expandAndWriteSpy).to.not.be.called;
});
});

it('Resovle when config is invalid', () => {
const config = dict({
'writeCookies': 'invalid',
});
expectAsyncConsoleError(TAG + ' writeCookies config must be an object');
const cookieWriter = new CookieWriter(win, element, config);
expandAndWriteSpy = sandbox.spy(cookieWriter, 'expandAndWrite_');
return cookieWriter.write().then(() => {
expect(expandAndWriteSpy).to.not.be.called;
});
});

it('Resolve when element is in FIE', () => {
const config = dict({
'writeCookies': {
'testId': 'QUERY_PARAM(test)',
},
});
const parent = doc.createElement('div');
parent.classList.add('i-amphtml-fie');
doc.body.appendChild(parent);
parent.appendChild(element);
const cookieWriter = new CookieWriter(win, element, config);
expandAndWriteSpy = sandbox.spy(cookieWriter, 'expandAndWrite_');
return cookieWriter.write().then(() => {
expect(expandAndWriteSpy).to.not.be.called;
});
});

it('Resolve when in viewer', () => {
const config = dict({
'writeCookies': {
'testId': 'testValue',
},
});
const mockWin = {
location: 'https://www-example-com.cdn.ampproject.org',
};
const cookieWriter = new CookieWriter(mockWin, element, config);
expandAndWriteSpy = sandbox.spy(cookieWriter, 'expandAndWrite_');
return cookieWriter.write().then(() => {
expect(expandAndWriteSpy).to.not.be.called;
});
});

it('Resolve with nothing to write', () => {
const config = dict({
'writeCookies': {},
});
const cookieWriter = new CookieWriter(win, element, config);
expandAndWriteSpy = sandbox.spy(cookieWriter, 'expandAndWrite_');
return cookieWriter.write().then(() => {
expect(expandAndWriteSpy).to.not.be.called;
});
});

it('Resolve when cookie value is not supported', () => {
const config = dict({
'writeCookies': {
'testId': 'RANDOM',
'testId1': 'static',
'testId2': 'QUERY_PARAM(abc)-suf',
'testId3': 'pre-QUERY_PARAM(abc)',
},
});
const cookieWriter = new CookieWriter(win, element, config);
expectAsyncConsoleError(TAG + ' cookie value RANDOM not supported. ' +
'Only QUERY_PARAM is supported');
expectAsyncConsoleError(TAG + ' cookie value static not supported. ' +
'Only QUERY_PARAM is supported');
expectAsyncConsoleError(TAG + ' cookie value QUERY_PARAM(abc)-suf not ' +
'supported. Only QUERY_PARAM is supported');
expectAsyncConsoleError(TAG + ' cookie value pre-QUERY_PARAM(abc) not ' +
'supported. Only QUERY_PARAM is supported');
expandAndWriteSpy = sandbox.spy(cookieWriter, 'expandAndWrite_');
return cookieWriter.write().then(() => {
expect(expandAndWriteSpy).to.not.be.called;
});
});
});

describe('Cookie value', () => {
it('Write cookie', () => {
const config = dict({
'writeCookies': {
'testId': 'QUERY_PARAM(abc)',
},
});
const cookieWriter = new CookieWriter(win, element, config);
sandbox.stub(cookieWriter.urlReplacementService_,
'expandStringAsync').callsFake(string => {
return Promise.resolve(string);});
return cookieWriter.write().then(() => {
expect(setCookieSpy).to.be.calledOnce;
expect(setCookieSpy).to.be.calledWith('testId', 'QUERY_PARAM(abc)');
});
});

it('Write multiple cookie', () => {
const config = dict({
'writeCookies': {
'testId': 'QUERY_PARAM(abc)',
'testId2': 'QUERY_PARAM(def)',
},
});
const cookieWriter = new CookieWriter(win, element, config);
sandbox.stub(cookieWriter.urlReplacementService_,
'expandStringAsync').callsFake(string => {
return Promise.resolve(string);});
return cookieWriter.write().then(() => {
expect(setCookieSpy).to.be.calledTwice;
expect(setCookieSpy).to.be.calledWith('testId', 'QUERY_PARAM(abc)');
expect(setCookieSpy).to.be.calledWith('testId2', 'QUERY_PARAM(def)');
});
});

it('Do not write when string is empty', () => {
const config = dict({
'writeCookies': {
'testId': 'QUERY_PARAM(noexist)',
},
});
const cookieWriter = new CookieWriter(win, element, config);
sandbox.stub(cookieWriter.urlReplacementService_,
'expandStringAsync').callsFake(() => {
return Promise.resolve('');});
return cookieWriter.write().then(() => {
// Both cookie value resolve to empty string
expect(setCookieSpy).to.not.be.called;
});
});

it('Handle expandString error', () => {
const config = dict({
'writeCookies': {
'testId': 'QUERY_PARAM',
},
});
const cookieWriter = new CookieWriter(win, element, config);
expectAsyncConsoleError(TAG + ' Error expanding cookie string ' +
'Error: The first argument to QUERY_PARAM, ' +
'the query string param is required​​​');
expectAsyncConsoleError('The first argument to QUERY_PARAM, ' +
'the query string param is required');
return cookieWriter.write().then(() => {
// Both cookie value resolve to empty string
expect(setCookieSpy).to.not.be.called;
});
});
});
});
Loading