-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
✨Analytics: CookieWriter #18406
Changes from 4 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} | ||
} | ||
|
||
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
210
extensions/amp-analytics/0.1/test/test-cookie-writer.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}); | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
print user error otherwise