Skip to content
This repository has been archived by the owner on Dec 11, 2019. It is now read-only.

Commit

Permalink
Merge pull request #7721 from brave/feature/1987
Browse files Browse the repository at this point in the history
Add setting to block all cookies
  • Loading branch information
bbondy authored Mar 15, 2017
2 parents 10fe466 + 5e506bb commit 11ec4f3
Show file tree
Hide file tree
Showing 13 changed files with 172 additions and 37 deletions.
30 changes: 2 additions & 28 deletions app/extensions/brave/content/scripts/block3rdPartyContent.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
* Whether this is running in a third-party document.
*/
function is3rdPartyDoc () {
try {
// Try accessing an element that cross-origin frames aren't supposed to
window.top.document
} catch (e) {
if (e.name === 'SecurityError') {
return true
} else {
console.log('got unexpected error accessing window.top.document', e)
// Err on the safe side and assume this is a third-party frame
return true
}
}
return false
}

function blockReferer () {
if (document.referrer) {
// Blocks cross-origin referer
var parser = document.createElement('a')
parser.href = document.referrer
if (parser.origin !== document.location.origin) {
window.Document.prototype.__defineGetter__('referrer', () => { return document.location.origin })
}
}
window.Document.prototype.__defineGetter__('referrer', () => { return document.location.origin })
}

function blockCookie () {
Expand All @@ -50,6 +24,6 @@ if (chrome.contentSettings.referer != 'allow' &&
document.location.origin && document.location.origin !== 'https://youtube.googleapis.com') {
executeScript(getBlockRefererScript())
}
if (chrome.contentSettings.cookies != 'allow' && is3rdPartyDoc()) {
if (chrome.contentSettings.cookies != 'allow') {
executeScript(getBlockCookieScript())
}
1 change: 1 addition & 0 deletions app/extensions/brave/locales/en-US/bravery.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ fingerprintingProtection=Fingerprinting Protection
adControl=Ad Control
cookieControl=Cookie Control
allowAllCookies=Allow all cookies
blockAllCookies=Block all cookies
adBlock=Ad Block
showBraveAds=Show Brave Ads
adsBlocked={[plural(blockedAdCount)]}
Expand Down
20 changes: 16 additions & 4 deletions app/filtering.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,17 +253,20 @@ function registerForBeforeSendHeaders (session, partition) {
}
}

if (module.exports.isResourceEnabled(appConfig.resourceNames.COOKIEBLOCK, firstPartyUrl, isPrivate)) {
const cookieSetting = module.exports.isResourceEnabled(appConfig.resourceNames.COOKIEBLOCK, firstPartyUrl, isPrivate)
if (cookieSetting) {
const parsedTargetUrl = urlParse(details.url || '')
const parsedFirstPartyUrl = urlParse(firstPartyUrl)

if (module.exports.isThirdPartyHost(parsedFirstPartyUrl.hostname, parsedTargetUrl.hostname)) {
if (cookieSetting === 'blockAllCookies' ||
module.exports.isThirdPartyHost(parsedFirstPartyUrl.hostname, parsedTargetUrl.hostname)) {
// Clear cookie and referer on third-party requests
if (requestHeaders['Cookie'] &&
getOrigin(firstPartyUrl) !== pdfjsOrigin) {
requestHeaders['Cookie'] = undefined
}
if (requestHeaders['Referer'] &&
if (cookieSetting !== 'blockAllCookies' &&
requestHeaders['Referer'] &&
!refererExceptions.includes(parsedTargetUrl.hostname)) {
requestHeaders['Referer'] = getOrigin(details.url)
}
Expand Down Expand Up @@ -656,6 +659,14 @@ module.exports.getSiteSettings = (url, isPrivate) => {
return siteSettings.getSiteSettingsForURL(settings, url)
}

/**
* Returns whether a resource is enabled for url. For COOKIEBLOCK, returns
* the either false or the string value of the cookie setting.
* @param {string} resourceName
* @param {string} url
* @param {boolean=} isPrivate
* @returns {boolean|string}
*/
module.exports.isResourceEnabled = (resourceName, url, isPrivate) => {
if (resourceName === 'siteHacks') {
return true
Expand Down Expand Up @@ -700,7 +711,8 @@ module.exports.isResourceEnabled = (resourceName, url, isPrivate) => {
if (braverySettings.cookieControl === 'allowAllCookies') {
return false
} else {
return true
// Return the cookieControl setting
return braverySettings.cookieControl
}
}

Expand Down
5 changes: 4 additions & 1 deletion docs/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ AppStore
cookieblock: {
enabled: boolean // enable 3p cookie/referer blocking
},
cookieblockAll: {
enabled: boolean // enable all cookie/referer blocking
},
defaultBrowserCheckComplete: boolean, // true to indicate default browser check is complete
defaultWindowHeight: number, // DEPRECATED (0.12.7); replaced w/ defaultWindowParams.height
defaultWindowParams: {
Expand Down Expand Up @@ -237,7 +240,7 @@ AppStore
siteSettings: {
[hostPattern]: {
adControl: string, // (showBraveAds | blockAds | allowAdsAndTracking)
cookieControl: string, // (block3rdPartyCookie | allowAllCookies)
cookieControl: string, // (block3rdPartyCookie | allowAllCookies | blockAllCookies)
fingerprintingProtection: boolean,
flash: (number|boolean), // approval expiration time if allowed, false if never allow
fullscreenPermission: boolean,
Expand Down
3 changes: 3 additions & 0 deletions js/about/preferences.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const searchProviders = require('../data/searchProviders')

const adblock = appConfig.resourceNames.ADBLOCK
const cookieblock = appConfig.resourceNames.COOKIEBLOCK
const cookieblockAll = appConfig.resourceNames.COOKIEBLOCK_ALL
const adInsertion = appConfig.resourceNames.AD_INSERTION
const trackingProtection = appConfig.resourceNames.TRACKING_PROTECTION
const httpsEverywhere = appConfig.resourceNames.HTTPS_EVERYWHERE
Expand Down Expand Up @@ -494,6 +495,7 @@ class ShieldsTab extends ImmutableComponent {
}
onChangeCookieControl (e) {
aboutActions.setResourceEnabled(cookieblock, e.target.value === 'block3rdPartyCookie')
aboutActions.setResourceEnabled(cookieblockAll, e.target.value === 'blockAllCookies')
}
onToggleSetting (setting, e) {
aboutActions.setResourceEnabled(setting, e.target.value)
Expand All @@ -517,6 +519,7 @@ class ShieldsTab extends ImmutableComponent {
onChange={this.onChangeCookieControl}>
<option data-l10n-id='block3rdPartyCookie' value='block3rdPartyCookie' />
<option data-l10n-id='allowAllCookies' value='allowAllCookies' />
<option data-l10n-id='blockAllCookies' value='blockAllCookies' />
</SettingDropdown>
</SettingItem>
<SettingCheckbox checked={this.props.braveryDefaults.get('httpsEverywhere')} dataL10nId='httpsEverywhere' onChange={this.onToggleHTTPSE} />
Expand Down
1 change: 1 addition & 0 deletions js/components/braveryPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ class BraveryPanel extends ImmutableComponent {
<FormDropdown data-test-id='cookieControl' value={this.props.braverySettings.cookieControl} onChange={this.onToggleCookieControl} disabled={!shieldsUp}>
<option data-l10n-id='block3rdPartyCookie' value='block3rdPartyCookie' />
<option data-l10n-id='allowAllCookies' value='allowAllCookies' />
<option data-l10n-id='blockAllCookies' value='blockAllCookies' />
</FormDropdown>
<SwitchControl onClick={this.onToggleFp} rightl10nId='fingerprintingProtection' checkedOn={fpEnabled} disabled={!shieldsUp} onInfoClick={this.onInfoClick} infoTitle={config.fingerprintingInfoUrl} className='fingerprintingProtectionSwitch' />
<SwitchControl onClick={this.onToggleSafeBrowsing} rightl10nId='safeBrowsing' checkedOn={this.props.braverySettings.safeBrowsing} disabled={!shieldsUp} className='safeBrowsingSwitch' />
Expand Down
4 changes: 4 additions & 0 deletions js/constants/appConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,17 @@ module.exports = {
FLASH: 'flash',
WIDEVINE: 'widevine',
COOKIEBLOCK: 'cookieblock', // block 3p cookies and referer
COOKIEBLOCK_ALL: 'cookieblockAll', // block all cookies and referer
SITEHACK: 'siteHacks',
WEBTORRENT: 'webtorrent'
// ... other optional resource files are identified by uuid such as for regional adblock
},
cookieblock: {
enabled: true
},
cookieblockAll: {
enabled: false
},
noScript: {
enabled: false
},
Expand Down
19 changes: 18 additions & 1 deletion js/state/contentSettings.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const getDefaultUserPrefContentSettings = (braveryDefaults, appSettings, appConf
return Immutable.fromJS({
cookies: getDefault3rdPartyStorageSettings(braveryDefaults, appSettings, appConfig),
referer: [{
setting: braveryDefaults.get('cookieControl') === 'block3rdPartyCookie' ? 'block' : 'allow',
setting: braveryDefaults.get('cookieControl') !== 'allowAllCookies' ? 'block' : 'allow',
primaryPattern: '*'
}],
adInsertion: [{
Expand Down Expand Up @@ -182,6 +182,20 @@ const getDefault3rdPartyStorageSettings = (braveryDefaults, appSettings, appConf
secondaryPattern: exceptionPair[1]
})))
return contentSettings
} else if (braveryDefaults.get('cookieControl') === 'blockAllCookies') {
return [
{
setting: 'block',
primaryPattern: '*',
secondaryPattern: '*'
},
{
// Needed for coinbase widget localStorage to work in about:preferences
setting: 'allow',
primaryPattern: `chrome-extension://${config.braveExtensionId}`,
secondaryPattern: config.coinbaseOrigin
}
]
} else {
return [
{
Expand Down Expand Up @@ -238,6 +252,9 @@ const siteSettingsToContentSettings = (currentSiteSettings, defaultContentSettin
cookieExceptions.forEach((exceptionPair) => {
contentSettings = addContentSettings(contentSettings, 'cookies', exceptionPair[0], exceptionPair[1], 'allow')
})
} else if (siteSetting.get('cookieControl') === 'blockAllCookies') {
contentSettings = addContentSettings(contentSettings, 'cookies', primaryPattern, '*', 'block')
contentSettings = addContentSettings(contentSettings, 'referer', primaryPattern, '*', 'block')
} else {
contentSettings = addContentSettings(contentSettings, 'cookies', primaryPattern, '*', 'allow')
contentSettings = addContentSettings(contentSettings, 'referer', primaryPattern, '*', 'allow')
Expand Down
4 changes: 4 additions & 0 deletions js/state/siteSettings.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@ module.exports.braveryDefaults = (appState, appConfig) => {
let blockAds = defaults[appConfig.resourceNames.ADBLOCK] || false
let blockTracking = defaults[appConfig.resourceNames.TRACKING_PROTECTION] || false
let blockCookies = defaults[appConfig.resourceNames.COOKIEBLOCK] || false
let blockCookiesAll = defaults[appConfig.resourceNames.COOKIEBLOCK_ALL] || false
defaults.adControl = 'allowAdsAndTracking'
if (blockAds && replaceAds && blockTracking) {
defaults.adControl = 'showBraveAds'
} else if (blockAds && !replaceAds && blockTracking) {
defaults.adControl = 'blockAds'
}
defaults.cookieControl = blockCookies ? 'block3rdPartyCookie' : 'allowAllCookies'
if (blockCookiesAll) {
defaults.cookieControl = 'blockAllCookies'
}

// TODO(bridiver) this should work just like the other bravery settings
let fingerprintingProtection = appState.get('settings').get('privacy.block-canvas-fingerprinting')
Expand Down
6 changes: 4 additions & 2 deletions js/state/syncUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ const applySiteSettingRecord = (record) => {
}
const cookieControlEnum = {
0: 'block3rdPartyCookie',
1: 'allowAllCookies'
1: 'allowAllCookies',
2: 'blockAllCookies'
}
const getValue = (key, value) => {
if (key === 'adControl') {
Expand Down Expand Up @@ -437,7 +438,8 @@ module.exports.createSiteSettingsData = (hostPattern, setting) => {
}
const cookieControlEnum = {
block3rdPartyCookie: 0,
allowAllCookies: 1
allowAllCookies: 1,
blockAllCookies: 2
}
const objectData = {hostPattern}

Expand Down
44 changes: 43 additions & 1 deletion test/components/braveryPanelTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const Brave = require('../lib/brave')
const messages = require('../../js/constants/messages')
const {urlInput, braveMenu, braveMenuDisabled, adsBlockedStat, adsBlockedControl, showAdsOption, blockAdsOption, braveryPanel, httpsEverywhereStat, noScriptStat, noScriptSwitch, fpSwitch, fpStat, noScriptNavButton, customFiltersInput} = require('../lib/selectors')
const {cookieControl, allowAllCookiesOption, blockAllCookiesOption, urlInput, braveMenu, braveMenuDisabled, adsBlockedStat, adsBlockedControl, showAdsOption, blockAdsOption, braveryPanel, httpsEverywhereStat, noScriptStat, noScriptSwitch, fpSwitch, fpStat, noScriptNavButton, customFiltersInput} = require('../lib/selectors')
const {getTargetAboutUrl} = require('../../js/lib/appUrlUtil')

describe('Bravery Panel', function () {
Expand Down Expand Up @@ -427,6 +427,48 @@ describe('Bravery Panel', function () {
.then((size) => size.height > 0)
})
})
it('blocks cookies', function * () {
const url = Brave.server.url('cookies.html')
const expectedBlocked = ['local storage:',
'session storage:',
'indexeddb:',
'cookies:',
'""',
'websql:',
'filesystem API:'
].join('\n')
yield this.app.client
.tabByIndex(0)
.loadUrl(url)
.openBraveMenu(braveMenu, braveryPanel)
.click(cookieControl)
.waitForVisible(blockAllCookiesOption)
.click(blockAllCookiesOption)
.tabByIndex(0)
.loadUrl(url)
.waitUntil(function () {
return this.getText('body').then((text) => {
return text === expectedBlocked
})
})
})
it('allows cookies', function * () {
const url = Brave.server.url('cookies.html')
yield this.app.client
.tabByIndex(0)
.loadUrl(url)
.openBraveMenu(braveMenu, braveryPanel)
.click(cookieControl)
.waitForVisible(allowAllCookiesOption)
.click(allowAllCookiesOption)
.tabByIndex(0)
.loadUrl(url)
.waitUntil(function () {
return this.getText('body').then((text) => {
return text.includes('abc=123')
})
})
})
it('blocks fingerprinting', function * () {
const url = Brave.server.url('fingerprinting.html')
yield this.app.client
Expand Down
71 changes: 71 additions & 0 deletions test/fixtures/cookies.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<body>
local storage:
<div id='localstorage'>
</div>
session storage:
<div id='sessionstorage'>
</div>
indexeddb:
<div id='idb'>
</div>
cookies:
<div id='cookies'>
</div>
websql:
<div id='websql'>
</div>
filesystem API:
<div id='fs'>
</div>

<script>
function setText (id, result) {
document.getElementById(id).innerText = JSON.stringify(result)
}

// If storage is not blocked, these item values change on every page load.
// Otherwise they stay at 0.
try {
localStorage['a'] = localStorage['a'] ? localStorage['a'] + 0 : 0
setText('localstorage', localStorage.getItem('a'))
} catch (e) {}
try {
sessionStorage.setItem('b', sessionStorage['b'] ? sessionStorage['b'] + 0 : 0)
setText('sessionstorage', sessionStorage['b'])
} catch (e) {}
try {
document.cookie = 'abc=123'
setText('cookies', document.cookie)
} catch (e) {}

try {
var idb = indexedDB.open('idb', 1)
idb.onsuccess = function () {
indexedDB.webkitGetDatabaseNames().onsuccess = (sender) => {
setText('idb', sender.target.result)
}
}
} catch (e) {}

try {
var wdb = openDatabase("wdb", "0.1", "test", 1024 * 1024)
if (wdb.transaction) {
wdb.transaction(function (tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS " +
"todo(ID INTEGER PRIMARY KEY ASC, todo TEXT, added_on DATETIME)", [])
});
wdb.transaction(function(tx) {
tx.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [], function (t, rs) {
setText('websql', rs.rows)
});
});
}
} catch (e) {}

try {
webkitRequestFileSystem(PERSISTENT, 1024*1024, (fs) => {
setText('fs', fs.name)
})
} catch (e) {}
</script>
</body>
1 change: 1 addition & 0 deletions test/lib/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ module.exports = {
blockAdsOption: '[data-l10n-id="blockAds"]',
cookieControl: '[data-test-id="cookieControl"]',
allowAllCookiesOption: '[data-l10n-id="allowAllCookies"]',
blockAllCookiesOption: '[data-l10n-id="blockAllCookies"]',
braveryPanel: '.braveryPanel',
httpsEverywhereStat: '.braveryStat.redirectedResourcesStat',
httpsEverywhereSwitch: '.httpsEverywhereSwitch .switchMiddle',
Expand Down

0 comments on commit 11ec4f3

Please sign in to comment.