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

COOKIE macro #22815

Merged
merged 6 commits into from
Jun 19, 2019
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion build-system/amp4test.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ app.use('/compose-doc', function(req, res) {
head,
spec,
});
res.cookie('test-cookie', 'test');
res.send(doc);
});

Expand Down Expand Up @@ -211,7 +212,8 @@ app.get('/a4a/:bid', (req, res) => {
"navTiming": "\${navTiming(requestStart,requestStart)}",
"navType": "\${navType}",
"navRedirectCount": "\${navRedirectCount}",
"sourceUrl": "\${sourceUrl}"
"sourceUrl": "\${sourceUrl}",
"cookie": "\${cookie(test-cookie)}"
}
}
}
Expand All @@ -225,6 +227,7 @@ app.get('/a4a/:bid', (req, res) => {
css: 'body { background-color: #f4f4f4; }',
extensions: ['amp-analytics'],
});
res.cookie('test-cookie', 'test');
res.send(doc);
});

Expand Down
50 changes: 50 additions & 0 deletions extensions/amp-analytics/0.1/cookie-reader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Copyright 2019 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 {getCookie} from '../../../src/cookies';
import {getMode} from '../../../src/mode';
import {isInFie} from '../../../src/friendly-iframe-embed';
import {isProxyOrigin} from '../../../src/url';

/**
* COOKIE macro resolver
* @param {!Window} win
* @param {!Element} element
* @param {string} name
* @return {?string}
*/
export function cookieReader(win, element, name) {
if (!isCookieAllowed(win, element)) {
return null;
}
return getCookie(win, name);
}

/**
* Determine if cookie writing/reading feature is supported in current
* environment.
* Disable cookie writer in friendly iframe and proxy origin and inabox.
* @param {!Window} win
* @param {!Element} element
* @return {boolean}
*/
export function isCookieAllowed(win, element) {
return (
!isInFie(element) &&
!isProxyOrigin(win.location) &&
!(getMode(win).runtime == 'inabox')
);
}
11 changes: 2 additions & 9 deletions extensions/amp-analytics/0.1/cookie-writer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@

import {BASE_CID_MAX_AGE_MILLIS} from '../../../src/service/cid-impl';
import {Services} from '../../../src/services';
import {getMode} from '../../../src/mode';
import {hasOwn} from '../../../src/utils/object';
import {isInFie} from '../../../src/friendly-iframe-embed';
import {isCookieAllowed} from './cookie-reader';
import {isObject} from '../../../src/types';
import {isProxyOrigin} from '../../../src/url';
import {setCookie} from '../../../src/cookies';
import {user} from '../../../src/log';
import {variableServiceForDoc} from './variables';
Expand Down Expand Up @@ -90,12 +88,7 @@ export class CookieWriter {
*/
init_() {
// TODO: Need the consider the case for shadow doc.
if (
isInFie(this.element_) ||
isProxyOrigin(this.win_.location) ||
getMode(this.win_).runtime == 'inabox'
) {
// Disable cookie writer in friendly iframe and proxy origin and inabox.
if (!isCookieAllowed(this.win_, this.element_)) {
// 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();
Expand Down
2 changes: 2 additions & 0 deletions extensions/amp-analytics/0.1/requests.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
} from './variables';
import {SANDBOX_AVAILABLE_VARS} from './sandbox-vars-whitelist';
import {Services} from '../../../src/services';
import {cookieReader} from './cookie-reader';
import {devAssert, userAssert} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {getResourceTiming} from './resource-timing';
Expand Down Expand Up @@ -130,6 +131,7 @@ export class RequestHandler {
// TODO: (@zhouyx) Move to variable service once that becomes
// a doc level services
bindings['CONSENT_STATE'] = getConsentStateStr(this.element_);
bindings['COOKIE'] = name => cookieReader(this.win, this.element_, name);

if (!this.baseUrlPromise_) {
expansionOption.freezeVar('extraUrlParams');
Expand Down
19 changes: 19 additions & 0 deletions extensions/amp-analytics/0.1/test/test-requests.js
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,25 @@ describes.realWin('Requests', {amp: 1}, env => {
expect(spy).to.be.calledWith('r1&test&test2');
});

it('COOKIE read cookie value', function*() {
const spy = sandbox.spy();
const r = {'baseUrl': 'r1&c1=COOKIE(test)&c2=${cookie(test)}'};
let handler = createRequestHandler(r, spy);
const expansionOptions = new ExpansionOptions({
'cookie': 'COOKIE',
});
handler.send({}, {}, expansionOptions);
yield macroTask();
expect(spy).to.be.calledWith('r1&c1=&c2=');

env.win.document.cookie = 'test=123';
spy.resetHistory();
handler = createRequestHandler(r, spy);
handler.send({}, {}, expansionOptions);
yield macroTask();
expect(spy).to.be.calledWith('r1&c1=123&c2=123');
});

describe('expandPostMessage', () => {
let expansionOptions;
let params;
Expand Down
1 change: 1 addition & 0 deletions extensions/amp-analytics/0.1/vendors.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export const ANALYTICS_CONFIG = /** @type {!JsonObject} */ ({
'clientId': 'CLIENT_ID',
'consentState': 'CONSENT_STATE',
'contentLoadTime': 'CONTENT_LOAD_TIME',
'cookie': 'COOKIE',
'counter': 'COUNTER',
'documentCharset': 'DOCUMENT_CHARSET',
'documentReferrer': 'DOCUMENT_REFERRER',
Expand Down
6 changes: 5 additions & 1 deletion test/integration/test-amp-analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ describe('amp-analytics', function() {
"b": "\${title}",
"cid": "\${clientId(_cid)}",
"loadend": "\${navTiming(loadEventEnd)}",
"default": "\$DEFAULT( , test)"
"default": "\$DEFAULT( , test)",
"cookie": "\${cookie(test-cookie)}"
}
}
</script>
Expand All @@ -69,6 +70,9 @@ describe('amp-analytics', function() {
expect(q['cid']).to.equal('amp-12345');
expect(q['loadend']).to.not.equal('0');
expect(q['default']).to.equal('test');
// cookie set via http response header when requesting
// localhost:9876/amp4test/compose-doc
expect(q['cookie']).to.equal('test');
Copy link
Contributor

Choose a reason for hiding this comment

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

same comment needed here

expect(
req.headers.referer,
'should keep referrer if no referrerpolicy specified'
Expand Down
4 changes: 4 additions & 0 deletions test/integration/test-amp-inabox.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ describe
const queries = parseQueryString(req.url.substr('/bar'.length));
expect(queries['cid']).to.equal('');
expect(queries['sourceUrl']).be.ok;
// Cookie is sent via http response header when requesting
// localhost:9876/amp4test/a4a/
// COOKIE macro is not allowed in inabox and resolves to empty
expect(queries['cookie']).to.equal('');
zhouyx marked this conversation as resolved.
Show resolved Hide resolved
});
return Promise.all([imgPromise, pixelPromise, analyticsPromise]);
}
Expand Down