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

core: INSECURE_DOCUMENT_REQUEST errors still return lhr #6608

Merged
merged 28 commits into from
Jan 11, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
4c658fb
INSECURE_DOCUMENT_REQUEST errors still return lhr (#6595)
connorjclark Nov 19, 2018
eb7f5a3
fix comment. remove dead code
connorjclark Nov 19, 2018
62787ee
Merge branch 'master' into issue-6595-insecure
connorjclark Dec 18, 2018
3577e0c
move security check to wait for page load
connorjclark Dec 19, 2018
2c0b251
remove finally for timing
connorjclark Dec 19, 2018
e22d9ca
set cancel
connorjclark Dec 20, 2018
9e54f1b
update test name
connorjclark Dec 20, 2018
059d95e
tweak security logic
connorjclark Dec 20, 2018
51e4f05
fix test
connorjclark Dec 20, 2018
1ce9144
add smoke test, other stuff
connorjclark Dec 20, 2018
4bd59e4
fix offline case for security check
connorjclark Dec 20, 2018
53e00a7
skip security check when offline
connorjclark Dec 20, 2018
1b6e678
skip security check if localhost
connorjclark Dec 20, 2018
dde5b95
Merge branch 'master' into issue-6595-insecure
connorjclark Jan 8, 2019
4807cf0
only do security check if online and https
connorjclark Jan 8, 2019
2d505e8
consider all secure schemes
connorjclark Jan 8, 2019
1e1fc8a
move security check to promise race. only rejects now.
connorjclark Jan 8, 2019
0a0e8e0
fix typo
connorjclark Jan 8, 2019
b863fbd
Merge remote-tracking branch 'origin/master' into issue-6595-insecure
connorjclark Jan 8, 2019
da6fd9c
Merge remote-tracking branch 'origin/master' into issue-6595-insecure
connorjclark Jan 8, 2019
3c54326
fix typo, add comment
connorjclark Jan 9, 2019
ab0582b
make security check cancelable promise again
connorjclark Jan 9, 2019
f272978
simplify cancels
connorjclark Jan 9, 2019
e6a659a
fix cancel bug
connorjclark Jan 10, 2019
271a80a
move security error creation
connorjclark Jan 10, 2019
8bbcbc4
cr changes
connorjclark Jan 10, 2019
04b1f64
create driver for each test
connorjclark Jan 10, 2019
1da3b01
cr changes
connorjclark Jan 11, 2019
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
63 changes: 36 additions & 27 deletions lighthouse-core/gather/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,6 @@ class Driver {
this._eventEmitter.emit(event.method, event.params);
});

/**
* Used for monitoring network status events during gotoURL.
* @type {?LH.Crdp.Security.SecurityStateChangedEvent}
* @private
*/
this._lastSecurityState = null;

/**
* @type {number}
* @private
Expand Down Expand Up @@ -512,6 +505,35 @@ class Driver {
});
}

/**
* Returns LHError if the security state is insecure.
* @param {LH.Crdp.Security.SecurityStateChangedEvent} securityState
* @returns {LHError|undefined}
*/
checkForSecurityIssues({securityState, explanations}) {
if (securityState === 'insecure') {
const insecureDescriptions = explanations
.filter(exp => exp.securityState === 'insecure')
.map(exp => exp.description);
return new LHError(LHError.errors.INSECURE_DOCUMENT_REQUEST, {
securityMessages: insecureDescriptions.join(' '),
});
}
}

waitForSecurityIssuesCheck() {
Copy link
Member

Choose a reason for hiding this comment

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

can we just combine the two of these? Seems unnecessary to split (waitForSecurityIssuesCheck doesn't really do anything in isolation and they aren't called separately)

Copy link
Member

Choose a reason for hiding this comment

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

we talked earlier about the order of the listener vs calling enable().

......maybe the order right now is OK. if you listened before calling security.enable then perhaps you would get a statechanged event for the about:blank state.

I'm not totally sure about this.

but typically we do like setting up the event listener before enable is called, because enable usually flushes all events before it results.

return new Promise((resolve, reject) => {
this.once('Security.securityStateChanged', state => {
const err = this.checkForSecurityIssues(state);
if (err) {
reject(err);
} else {
resolve();
}
});
});
}

/**
* Returns a promise that resolve when a frame has been navigated.
* Used for detecting that our about:blank reset has been completed.
Expand Down Expand Up @@ -895,6 +917,13 @@ class Driver {
// No timeout needed for Page.navigate. See #6413.
const waitforPageNavigateCmd = this._innerSendCommand('Page.navigate', {url});

try {
await this.sendCommand('Security.enable');
await this.waitForSecurityIssuesCheck();
} finally {
this.sendCommand('Security.disable');
}
Copy link
Member

Choose a reason for hiding this comment

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

To do this right, I think @paulirish is right and this should move into waitForFullyLoaded. We shouldn't be mucking around looking at network traffic before our traffic monitor is allowed to start monitoring :)

Take a look at this._waitForLoadEvent or this._waitForNetworkIdle for the promise/cancel cancellable promise model used, and _waitForFullyLoaded itself for where to put it in parallel with the timeout. It should be a pretty simple translation from waitForSecurityIssuesCheck already in this PR.

(and forgive the state of the code in those methods...they're super old and have pretty much only grown through accretion, not really refactored, so they're a bit creaky and brittle :)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

what about the _waitForFrameNavigated case?

Copy link
Member

Choose a reason for hiding this comment

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

what about the _waitForFrameNavigated case?

that's only used for loading about:blank, so we're ok there. We should probably make that clearer, though really if you're saying waitForNavigated: true, you're basically forgoing all our checks already.


if (waitForNavigated) {
await this._waitForFrameNavigated();
} else if (waitForLoad) {
Expand Down Expand Up @@ -959,26 +988,6 @@ class Driver {
return result.body;
}

async listenForSecurityStateChanges() {
this.on('Security.securityStateChanged', state => {
this._lastSecurityState = state;
});
await this.sendCommand('Security.enable');
}

/**
* @return {LH.Crdp.Security.SecurityStateChangedEvent}
*/
getSecurityState() {
if (!this._lastSecurityState) {
// happens if 'listenForSecurityStateChanges' is not called,
// or if some assumptions about the Security domain are wrong
throw new Error('Expected a security state.');
}

return this._lastSecurityState;
}

/**
* @param {string} name The name of API whose permission you wish to query
* @return {Promise<string>} The state of permissions, resolved in a promise.
Expand Down
27 changes: 5 additions & 22 deletions lighthouse-core/gather/gather-runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ class GatherRunner {
await driver.cacheNatives();
await driver.registerPerformanceObserver();
await driver.dismissJavaScriptDialogs();
await driver.listenForSecurityStateChanges();
if (resetStorage) await driver.clearDataForOrigin(options.requestedUrl);
log.timeEnd(status);
}
Expand Down Expand Up @@ -172,23 +171,6 @@ class GatherRunner {
}
}

/**
* Throws an error if the security state is insecure.
* @param {LH.Crdp.Security.SecurityStateChangedEvent} securityState
* @throws {LHError}
*/
static assertNoSecurityIssues({securityState, explanations}) {
if (securityState === 'insecure') {
const insecureDescriptions = explanations
.filter(exp => exp.securityState === 'insecure')
.map(exp => exp.description);
throw new LHError(
LHError.errors.INSECURE_DOCUMENT_REQUEST,
{securityMessages: insecureDescriptions.join(' ')}
);
}
}

/**
* Calls beforePass() on gatherers before tracing
* has started and before navigation to the target page.
Expand Down Expand Up @@ -256,8 +238,11 @@ class GatherRunner {
if (recordTrace) await driver.beginTrace(settings);

// Navigate.
await GatherRunner.loadPage(driver, passContext);
log.timeEnd(status);
try {
await GatherRunner.loadPage(driver, passContext);
Copy link
Collaborator

Choose a reason for hiding this comment

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

we're injecting a lot of new if/try/catch blocks into some already beefy methods, do you think there's a way we might be able to push some of these complications down a level so the busier method is still easy to parse?

Copy link
Collaborator Author

@connorjclark connorjclark Nov 20, 2018

Choose a reason for hiding this comment

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

yes, if we can refactor Runner.run to easily return a (errored) LHR in its catch. Then changes to gather-runner wouldn't be necessary.

Copy link
Member

Choose a reason for hiding this comment

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

We're dropping the LHR requirement for now, so we can also drop these changes (there won't be a timing object to add this to if an error was thrown)

} finally {
log.timeEnd(status);
}

const pStatus = {msg: `Running pass methods`, id: `lh:gather:pass`};
log.time(pStatus, 'verbose');
Expand Down Expand Up @@ -311,8 +296,6 @@ class GatherRunner {
const networkRecords = NetworkRecorder.recordsFromLogs(devtoolsLog);
log.timeEnd(status);

this.assertNoSecurityIssues(driver.getSecurityState());

let pageLoadError = GatherRunner.getPageLoadError(passContext.url, networkRecords);
// If the driver was offline, a page load error is expected, so do not save it.
if (!driver.online) pageLoadError = undefined;
Expand Down
4 changes: 2 additions & 2 deletions lighthouse-core/lib/file-namer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@
* Generate a filenamePrefix of hostname_YYYY-MM-DD_HH-MM-SS
* Date/time uses the local timezone, however Node has unreliable ICU
* support, so we must construct a YYYY-MM-DD date format manually. :/
* @param {{finalUrl: string, fetchTime: string}} lhr
* @param {{requestedUrl: string, finalUrl: string, fetchTime: string}} lhr
Copy link
Member

Choose a reason for hiding this comment

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

What is this requestedUrl business about? Does it relate to INSECURE DOC requests?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

if the doc fails to load, the "finalUrl" is never set. so fall back to requestUrl

Copy link
Member

Choose a reason for hiding this comment

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

What is this requestedUrl business about?

I believe left over from the old version of the PR, should be able to remove from here now (and from github-api.js and report-ui-features.js)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Oof you're right, forgot to check if that was still necessary.

* @return {string}
*/
function getFilenamePrefix(lhr) {
const hostname = new (getUrlConstructor())(lhr.finalUrl).hostname;
const hostname = new (getUrlConstructor())(lhr.finalUrl || lhr.requestedUrl).hostname;
const date = (lhr.fetchTime && new Date(lhr.fetchTime)) || new Date();

const timeStr = date.toLocaleTimeString('en-US', {hour12: false});
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/lib/i18n/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -952,7 +952,7 @@
"description": "Error message explaining that Lighthouse couldn't complete because the page has stopped responding to its instructions."
},
"lighthouse-core/lib/lh-error.js | pageLoadFailedInsecure": {
"message": "The URL you have provided does not have valid security credentials. ({securityMessages})",
"message": "The URL you have provided does not have valid security credentials. {securityMessages}",
"description": "Error message explaining that the credentials included in the Lighthouse run were invalid, so the URL cannot be accessed."
},
"lighthouse-core/lib/lh-error.js | pageLoadFailedWithDetails": {
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/lib/lh-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const UIStrings = {
/** Error message explaining that Lighthouse could not load the requested URL and the steps that might be taken to fix the unreliability. */
pageLoadFailedWithDetails: 'Lighthouse was unable to reliably load the page you requested. Make sure you are testing the correct URL and that the server is properly responding to all requests. (Details: {errorDetails})',
/** Error message explaining that the credentials included in the Lighthouse run were invalid, so the URL cannot be accessed. */
pageLoadFailedInsecure: 'The URL you have provided does not have valid security credentials. ({securityMessages})',
pageLoadFailedInsecure: 'The URL you have provided does not have valid security credentials. {securityMessages}',
Copy link
Member

Choose a reason for hiding this comment

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

Any reason for removing these? I feel like a list that might make no sense as a sentence like this belongs in parens. e.g. The URL...credentials. (Reason 1 Reason 2)

Copy link
Member

@exterkamp exterkamp Dec 18, 2018

Choose a reason for hiding this comment

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

A realistic error message reads like this:

The URL you have provided does not have valid security credentials. This site is missing a valid, trusted certificate (net::ERR_CERT_DATE_INVALID).

Which is a valid sentence. So...ignore this maybe.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

correct-o, the sentences should make sense as - is.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

at least, in english ..

Copy link
Member

Choose a reason for hiding this comment

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

I think we need to add something about securityMessages to the description for the translators. "securityMessages will be replaced with one or more strings from the browser explaining what was insecure about the page load." or whatever

/** Error message explaining that Chrome has encountered an error during the Lighthouse run, and that Chrome should be restarted. */
internalChromeError: 'An internal Chrome error occurred. Please restart Chrome and try re-running Lighthouse.',
/** Error message explaining that fetching the resources of the webpage has taken longer than the maximum time. */
Expand Down
1 change: 1 addition & 0 deletions lighthouse-core/report/html/renderer/report-ui-features.js
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,7 @@ class ReportUIFeatures {
*/
_saveFile(blob) {
const filename = getFilenamePrefix({
requestedUrl: this.json.requestedUrl,
finalUrl: this.json.finalUrl,
fetchTime: this.json.fetchTime,
});
Expand Down
36 changes: 36 additions & 0 deletions lighthouse-core/test/gather/driver-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ describe('Browser Driver', () => {
}
const replayConnection = new ReplayConnection();
const driver = new Driver(replayConnection);
driver.waitForSecurityIssuesCheck = () => Promise.resolve();

// Redirect in log will go through
const startUrl = 'http://en.wikipedia.org/';
Expand Down Expand Up @@ -535,4 +536,39 @@ describe('Multiple tab check', () => {
});
});
});

describe('.checkForSecurityIssues', () => {
it('returns nothing when page is secure', () => {
const secureSecurityState = {
securityState: 'secure',
};
const err = driverStub.checkForSecurityIssues(secureSecurityState);
assert.equal(err, undefined);
});

it('returns an error when page is insecure', () => {
const insecureSecurityState = {
explanations: [
{
description: 'reason 1.',
securityState: 'insecure',
},
{
description: 'blah.',
securityState: 'info',
},
{
description: 'reason 2.',
securityState: 'insecure',
},
],
securityState: 'insecure',
};
const err = driverStub.checkForSecurityIssues(insecureSecurityState);
assert.equal(err.message, 'INSECURE_DOCUMENT_REQUEST');
assert.equal(err.code, 'INSECURE_DOCUMENT_REQUEST');
/* eslint-disable-next-line max-len */
expect(err.friendlyMessage).toBeDisplayString('The URL you have provided does not have valid security credentials. reason 1. reason 2.');
});
});
});
7 changes: 1 addition & 6 deletions lighthouse-core/test/gather/fake-driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,9 @@ const fakeDriver = {
setExtraHTTPHeaders() {
return Promise.resolve();
},
listenForSecurityStateChanges() {
waitForSecurityIssuesCheck() {
return Promise.resolve();
},
getSecurityState() {
return Promise.resolve({
securityState: 'secure',
});
},
};

module.exports = fakeDriver;
Expand Down
40 changes: 0 additions & 40 deletions lighthouse-core/test/gather/gather-runner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,6 @@ describe('GatherRunner', function() {
clearDataForOrigin: createCheck('calledClearStorage'),
blockUrlPatterns: asyncFunc,
setExtraHTTPHeaders: asyncFunc,
listenForSecurityStateChanges: asyncFunc,
};

return GatherRunner.setupDriver(driver, {settings: {}}).then(_ => {
Expand Down Expand Up @@ -382,7 +381,6 @@ describe('GatherRunner', function() {
clearDataForOrigin: createCheck('calledClearStorage'),
blockUrlPatterns: asyncFunc,
setExtraHTTPHeaders: asyncFunc,
listenForSecurityStateChanges: asyncFunc,
};

return GatherRunner.setupDriver(driver, {
Expand Down Expand Up @@ -696,44 +694,6 @@ describe('GatherRunner', function() {
});
});

describe('#assertNoSecurityIssues', () => {
it('succeeds when page is secure', () => {
const secureSecurityState = {
securityState: 'secure',
};
GatherRunner.assertNoSecurityIssues(secureSecurityState);
});

it('fails when page is insecure', () => {
const insecureSecurityState = {
explanations: [
{
description: 'reason 1',
securityState: 'insecure',
},
{
description: 'blah.',
securityState: 'info',
},
{
description: 'reason 2',
securityState: 'insecure',
},
],
securityState: 'insecure',
};
try {
GatherRunner.assertNoSecurityIssues(insecureSecurityState);
assert.fail('expected INSECURE_DOCUMENT_REQUEST LHError');
} catch (err) {
assert.equal(err.message, 'INSECURE_DOCUMENT_REQUEST');
assert.equal(err.code, 'INSECURE_DOCUMENT_REQUEST');
expect(err.friendlyMessage)
.toBeDisplayString(/The URL.*security credentials.*reason 1 reason 2/);
}
});
});

describe('artifact collection', () => {
// Make sure our gatherers never execute in parallel
it('runs gatherer lifecycle methods strictly in sequence', async () => {
Expand Down
1 change: 1 addition & 0 deletions lighthouse-viewer/app/src/github-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class GithubApi {
return this._auth.getAccessToken()
.then(accessToken => {
const filename = getFilenamePrefix({
requestedUrl: jsonFile.requestedUrl,
finalUrl: jsonFile.finalUrl,
fetchTime: jsonFile.fetchTime,
});
Expand Down