audit: fix cookie expiry/partition fidelity and profile-safety gaps

- Cookie stream: moz_cookies.expiry is milliseconds, but CDP expects
  seconds. The old code imported 52 already-expired cookies in the real
  profile and gave every remaining cookie a ~55,000-year expiry; convert
  units before comparing/sending, and skip session cookies that cannot
  survive the temporary Chromium session.
- Dashboard cookies: request partitionKey:{} for Chrome as well as Firefox
  (Chrome also omits CHIPS cookies otherwise), keep hasCrossSiteAncestor,
  omit the "unspecified" SameSite attribute for older targets, and never
  fall back to an arbitrary cookie store when importing.
- Profile safety: resolve symlinks before cp -a (a symlinked --firefox-profile
  was copied as a symlink and Firefox then opened the original profile),
  detect Chromium's dangling SingletonLock symlink with lstat, check Firefox's
  .parentlock/open descriptors via /proc instead of an optional fuser, refuse
  Firefox-looking Chromium targets and root/home, keep the OS password store
  for existing Chromium profiles, and clean the sensitive profile clone on
  SIGINT/SIGTERM.
- Exporter: never write through a dangling output symlink (O_EXCL|O_NOFOLLOW),
  refuse to export while Firefox holds the profile lock, and canonicalise
  origins so one odd origin cannot make the importer reject the whole bundle.
- Revert formatting-only manifest changes; align tools/README with the code
  (IndexedDB is supported, Node.js 22.12+, lock/symlink/password-store and
  key-generator limitations) and add regression tests for all of the above.
This commit is contained in:
souta
2026-10-23 20:54:18 +09:00
parent 1b617cef84
commit 7fb8ef7509
26 changed files with 1021 additions and 210 deletions
+28 -1
View File
@@ -42,7 +42,34 @@ async function main() {
],()=>{}), '127.0.0.1');
assert.equal(cookie.imported,1,JSON.stringify(cookie));
assert.equal((await page.cookies()).find(c=>c.name==='portage-test')?.value,'synthetic');
console.log(`PASS actual Chrome ${await browser.version()}: synthetic cookie imported`);
// The dashboard must also *collect* partitioned (CHIPS) cookies; Chrome's
// getAllCookieStores()/getAll() omit them unless partitionKey is requested.
const collected = await ext.evaluate(async () => {
await chrome.cookies.set({url:'https://example.com/',name:'portage-partitioned',value:'p',
secure:true,sameSite:'no_restriction',partitionKey:{topLevelSite:'https://example.com'}});
const result = await collectCookies();
const partitioned = result.data.find((entry) => entry.name === 'portage-partitioned');
return {count: result.count, partitionKey: partitioned?.partitionKey || null};
});
assert.equal(collected.partitionKey?.topLevelSite, 'https://example.com',
'collectCookies() must include partitioned cookies');
assert(collected.count >= 2);
// Importing a partitioned cookie must preserve the top-level site and the
// third-party ancestor bit; dropping either moves it between partitions.
const importedPartition = await ext.evaluate(async () => {
const result = await importCookies([{
name:'portage-import-partitioned', value:'v', domain:'example.com', path:'/', hostOnly:true,
secure:true, sameSite:'no_restriction',
partitionKey:{topLevelSite:'https://example.com', hasCrossSiteAncestor:true},
}], () => {});
const cookies = await chrome.cookies.getAll({partitionKey:{}});
const found = cookies.find((entry) => entry.name === 'portage-import-partitioned');
return {result, partitionKey: found?.partitionKey || null};
});
assert.equal(importedPartition.result.imported, 1);
assert.equal(importedPartition.partitionKey?.topLevelSite, 'https://example.com');
assert.equal(importedPartition.partitionKey?.hasCrossSiteAncestor, true);
console.log(`PASS actual Chrome ${await browser.version()}: cookie import/collect, partitioning and ancestor bit`);
} finally {
if(browser) await browser.close();
await new Promise(resolve=>server.close(resolve));
+68 -21
View File
@@ -1,22 +1,69 @@
'use strict';
const cp=require('node:child_process'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),assert=require('node:assert/strict');
const {transfer}=require('../tools/chromium_cookie_import.cjs');
const pp=require('../tools/node_modules/puppeteer-core');
(async()=>{const root=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cookie-cli-'));
const src=path.join(root,'firefox'),dst=path.join(root,'brave');fs.mkdirSync(src);
try{
const code=`import sqlite3,sys; c=sqlite3.connect(sys.argv[1]);c.execute('CREATE TABLE moz_cookies (name TEXT,value TEXT,host TEXT,path TEXT,expiry INTEGER,isSecure INTEGER,isHttpOnly INTEGER,sameSite INTEGER,originAttributes TEXT)');c.executemany('INSERT INTO moz_cookies VALUES(?,?,?,?,?,?,?,?,?)',[
('hello','test-value','example.com','/',1999999999,1,1,1,''),
('divided','test-value','example.org','/',1999999999,1,1,2,'^userContextId=1'),
('invalid','test-value','example.org','/',1999999999,0,0,0,''),
]);c.commit()`;
const p=cp.spawnSync('python3',['-c',code,path.join(src,'cookies.sqlite')],{encoding:'utf8'});assert.equal(p.status,0,p.stderr);
const result=await transfer({sourceProfile:src,targetProfile:dst,browserPath:'/usr/bin/brave-browser'});
assert.equal(result.candidate,1);assert.equal(result.accepted,1);assert.equal(result.failed,0);
assert.equal(result.skipped.partitioned_or_containers,1);assert.equal(result.skipped.insecure_none,1);
const browser=await pp.launch({executablePath:'/usr/bin/brave-browser',userDataDir:dst,headless:true,args:['--disable-background-networking']});
try{const page=await browser.newPage(),session=await page.createCDPSession();let r=await session.send('Storage.getCookies');assert(r.cookies.some(c=>c.name==='hello'&&c.httpOnly&&c.secure));}
finally{await browser.close()}
console.log('PASS native Brave cookie CLI: 1 persisted; unsafe/partitioned skipped');
}finally{fs.rmSync(root,{recursive:true,force:true})}
})().catch(e=>{console.error(e.stack);process.exitCode=1});
// Synthetic Firefox cookie DB -> CDP cookie import -> disposable Brave/Chrome
// profile. No real browser profile or cookie value is read or written.
const cp = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const assert = require('node:assert/strict');
const {transfer} = require('../tools/chromium_cookie_import.cjs');
let puppeteer;
try { puppeteer = require('../tools/node_modules/puppeteer-core'); } catch { puppeteer = require('puppeteer'); }
const BROWSER = process.env.PORTAGE_TEST_BRAVE
|| process.env.PORTAGE_TEST_COOKIE_BROWSER
|| '/usr/bin/brave-browser';
(async () => {
if (!fs.existsSync(BROWSER)) {
console.log(`SKIP: browser not found at ${BROWSER}; set PORTAGE_TEST_BRAVE`);
return;
}
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-cookie-cli-'));
const src = path.join(root, 'firefox'), dst = path.join(root, 'chromium');
fs.mkdirSync(src);
const futureMs = Date.now() + 3600 * 1000;
const pastMs = Date.now() - 3600 * 1000;
try {
// moz_cookies.expiry is milliseconds since the epoch. The expired row and
// a seconds-based value would both have been imported by the old code.
const code = `import sqlite3,sys
c=sqlite3.connect(sys.argv[1])
c.execute('CREATE TABLE moz_cookies (name TEXT,value TEXT,host TEXT,path TEXT,expiry INTEGER,isSecure INTEGER,isHttpOnly INTEGER,sameSite INTEGER,originAttributes TEXT)')
c.executemany('INSERT INTO moz_cookies VALUES(?,?,?,?,?,?,?,?,?)',[
('hello','test-value','example.com','/',${futureMs},1,1,1,''),
('expired','test-value','example.com','/',${pastMs},1,0,1,''),
('divided','test-value','example.org','/',${futureMs},1,1,2,'^userContextId=1'),
('invalid','test-value','example.org','/',${futureMs},0,0,0,''),
])
c.commit()`;
const created = cp.spawnSync('python3', ['-c', code, path.join(src, 'cookies.sqlite')], {encoding: 'utf8'});
assert.equal(created.status, 0, created.stderr);
const result = await transfer({sourceProfile: src, targetProfile: dst, browserPath: BROWSER});
assert.equal(result.candidate, 1);
assert.equal(result.accepted, 1);
assert.equal(result.failed, 0);
assert.equal(result.skipped.partitioned_or_containers, 1);
assert.equal(result.skipped.expired, 1, 'expired milliseconds cookies must be excluded');
assert.equal(result.skipped.insecure_none, 1);
const browser = await puppeteer.launch({
executablePath: BROWSER, userDataDir: dst, headless: true, args: ['--disable-background-networking'],
});
try {
const page = await browser.newPage();
const session = await page.createCDPSession();
const stored = (await session.send('Storage.getCookies')).cookies;
const hello = stored.find((cookie) => cookie.name === 'hello');
assert(hello && hello.httpOnly && hello.secure);
assert(Math.abs(hello.expires - futureMs / 1000) < 5, 'expiry must be stored in seconds');
assert(!stored.some((cookie) => cookie.name === 'expired'), 'expired cookie must not be resurrected');
} finally {
await browser.close();
}
console.log('PASS native Chromium cookie CLI: expiry unit/expiry filtering, unsafe/partitioned skipped');
} finally {
fs.rmSync(root, {recursive: true, force: true});
}
})().catch((error) => { console.error(error.stack); process.exitCode = 1; });
+3 -1
View File
@@ -3,19 +3,21 @@
// Creates only disposable profiles and uses synthetic site values.
'use strict';
const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome';
const FIREFOX = process.env.PORTAGE_TEST_FIREFOX || '/usr/local/bin/firefox';
const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http');
const assert=require('node:assert/strict');
const {spawn,spawnSync}=require('node:child_process');
let pp; try { pp = require('../tools/node_modules/puppeteer-core'); } catch { pp = require('puppeteer'); }
const {decryptWrapper,validateBundle,restoreSites}=require('../tools/chromium_localstorage_import.cjs');
function fire(args) {return new Promise((resolve,reject)=>{
let stderr='';const p=spawn('/usr/local/bin/firefox',args,{stdio:['ignore','ignore','pipe']});
let stderr='';const p=spawn(FIREFOX,args,{stdio:['ignore','ignore','pipe']});
p.stderr.on('data',b=>{stderr+=b.toString()});
const kill=setTimeout(()=>{p.kill();reject(new Error('Firefox timeout'))},20000);
p.on('error',e=>{clearTimeout(kill);reject(e)});
p.on('exit',code=>{clearTimeout(kill);if(code!==0)reject(new Error(`Firefox exited ${code}: ${stderr.slice(-500)}`));else resolve()});
});}
async function main(){
if(!fs.existsSync(FIREFOX)||!fs.existsSync(CHROMIUM)){console.log(`SKIP: Firefox/Chromium not found (PORTAGE_TEST_FIREFOX=${FIREFOX}, PORTAGE_TEST_CHROMIUM=${CHROMIUM})`);return;}
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cross-browser-'));
const fx=path.join(dir,'firefox-profile'), chrome=path.join(dir,'chrome-profile');
fs.mkdirSync(fx);let requests=0;
+6 -4
View File
@@ -1,13 +1,15 @@
'use strict';
const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome';
const FIREFOX = process.env.PORTAGE_TEST_FIREFOX || '/usr/local/bin/firefox';
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
const http=require('node:http');
const pp=require('../tools/node_modules/puppeteer-core');
let pp; try { pp = require('../tools/node_modules/puppeteer-core'); } catch { pp = require('puppeteer'); }
const {migrate,originsForFirefox,inertPage,navigateOffline,restoreOrigin}=require('../tools/indexeddb_migrate.cjs');
async function main(){
if(!fs.existsSync(FIREFOX)||!fs.existsSync(CHROMIUM)){console.log(`SKIP: Firefox/Chromium not found (PORTAGE_TEST_FIREFOX=${FIREFOX}, PORTAGE_TEST_CHROMIUM=${CHROMIUM})`);return;}
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-test-'));
const fx=path.join(scratch,'firefox'),chrome=path.join(scratch,'chrome');
const hits=[0,0];
@@ -16,7 +18,7 @@ async function main(){
const origins=servers.map(s=>`http://127.0.0.1:${s.address().port}`);
let browser;
try {
browser=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:'/usr/local/bin/firefox',userDataDir:fx,headless:true});
browser=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:FIREFOX,userDataDir:fx,headless:true});
const page=await browser.newPage();
for(const [n,origin] of origins.entries()) {
await page.goto(origin);
@@ -48,7 +50,7 @@ async function main(){
await browser.close();browser=null;
assert.deepEqual(originsForFirefox(fx),[...origins].sort());
const before=hits.slice();
const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:CHROMIUM,apply:true,timeout:20000});
const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:FIREFOX,chromium:CHROMIUM,apply:true,timeout:20000});
assert.equal(stats.restored,2,JSON.stringify(stats));
assert.deepEqual(hits,before,'IndexedDB migration must not access real origin');
browser=await pp.launch({executablePath:CHROMIUM,userDataDir:chrome,headless:true,args:['--disable-background-networking']});
@@ -91,7 +93,7 @@ async function main(){
await verify.close();await browser.close();browser=null;
assert.deepEqual(hits,before,'No real site traffic including verification');
// Re-running must never overwrite existing destination IndexedDB databases.
const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:CHROMIUM,apply:true,timeout:20000});
const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:FIREFOX,chromium:CHROMIUM,apply:true,timeout:20000});
assert.equal(repeated.restored,0);assert.equal(repeated.skipped,2);
process.exitCode=undefined;
console.log('PASS: Firefox 159 -> Chrome 156 indexedDB: 2 origins, schema, indexes, rich values, no target-site traffic');
+6 -2
View File
@@ -16,11 +16,14 @@ async function main() {
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'portage-offline-e2e-'));
const profile=path.join(dir,'profile');
const origin=`http://127.0.0.1:${server.address().port}`;
const bundle={portage:{format:'portage-bundle',version:1,source:'firefox'},data:{localStorage:[{origin,items:{token:'synthetic-value',a:'猫'}}]}};
// A __proto__ key must survive as ordinary localStorage data, not mutate the
// bundle object. JSON.parse (unlike an object literal) creates an own property.
const items=JSON.parse('{"token":"synthetic-value","a":"猫","__proto__":"proto-value"}');
const bundle={portage:{format:'portage-bundle',version:1,source:'firefox'},data:{localStorage:[{origin,items}]}};
const file=path.join(dir,'synthetic.portage.json');
fs.writeFileSync(file,JSON.stringify(bundle),{mode:0o600});
try {
assert.equal(validateBundle(bundle).totalKeys,2);
assert.equal(validateBundle(bundle).totalKeys,3);
await run({bundle:file, userDataDir:profile, browser:CHROMIUM, profileDirectory:'Default', timeout:12000, apply:true});
assert.equal(hits,0,'Importer must NOT send a single request to the origin');
const browser=await puppeteer.launch({executablePath:CHROMIUM,headless:true,userDataDir:profile,args:['--no-sandbox','--disable-background-networking']});
@@ -29,6 +32,7 @@ async function main() {
await page.goto(origin);
assert.equal(await page.evaluate(()=>localStorage.getItem('token')),'synthetic-value');
assert.equal(await page.evaluate(()=>localStorage.getItem('a')),'猫');
assert.equal(await page.evaluate(()=>localStorage.getItem('__proto__')),'proto-value');
} finally {await browser.close();}
console.log('PASS Chrome offline LocalStorage restore: zero origin requests during import; persistent after restart');
} finally {
+73
View File
@@ -0,0 +1,73 @@
import sqlite3
import sys
import tempfile
import time
import unittest
from contextlib import closing
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
from firefox_cookie_stream import collect
class FirefoxCookieStreamTest(unittest.TestCase):
def _profile(self, root, rows):
profile = Path(root) / 'profile'
profile.mkdir()
with closing(sqlite3.connect(profile / 'cookies.sqlite')) as connection, connection:
connection.execute(
'CREATE TABLE moz_cookies (name TEXT, value TEXT, host TEXT, path TEXT, '
'expiry INTEGER, isSecure INTEGER, isHttpOnly INTEGER, sameSite INTEGER, '
'originAttributes TEXT)'
)
connection.executemany('INSERT INTO moz_cookies VALUES (?,?,?,?,?,?,?,?,?)', rows)
return profile
def test_expiry_is_converted_from_milliseconds_and_unsafe_cookies_are_skipped(self):
now = time.time()
future_ms = int((now + 3600) * 1000)
past_ms = int((now - 3600) * 1000)
rows = [
# Persistent, unspecified SameSite: included, expiry seconds.
('future', 'v', 'example.com', '/', future_ms, 1, 1, 256, ''),
# Already expired: the old milliseconds-vs-seconds mix-up imported these.
('expired', 'v', 'example.com', '/', past_ms, 1, 0, 256, ''),
# Session cookies cannot survive the importer closing Chromium.
('session', 'v', 'example.com', '/', 0, 1, 0, 1, ''),
# SameSite=None (requires Secure) and Strict map to CDP names.
('none_secure', 'v', 'example.com', '/', future_ms, 1, 0, 0, ''),
('strict', 'v', 'example.com', '/', future_ms, 1, 0, 2, ''),
# Insecure SameSite=None is invalid and must be skipped.
('insecure_none', 'v', 'example.com', '/', future_ms, 0, 0, 0, ''),
# Firefox containers/partitions carry non-empty originAttributes.
('partitioned', 'v', 'example.com', '/', future_ms, 1, 0, 1, '^userContextId=1'),
# Malformed rows are skipped rather than forwarded to Chrome.
('bad_host', 'v', '', '/', future_ms, 1, 0, 1, ''),
('bad_path', 'v', 'example.com', 'not-a-path', future_ms, 1, 0, 1, ''),
]
with tempfile.TemporaryDirectory() as root:
profile = self._profile(root, rows)
result = collect(profile)
cookies = {cookie['name']: cookie for cookie in result['cookies']}
self.assertEqual(set(cookies), {'future', 'none_secure', 'strict'})
self.assertAlmostEqual(cookies['future']['expires'], now + 3600, delta=2)
self.assertNotIn('sameSite', cookies['future'])
self.assertEqual(cookies['none_secure']['sameSite'], 'None')
self.assertEqual(cookies['strict']['sameSite'], 'Strict')
self.assertEqual(result['skipped'], {
'partitioned_or_containers': 1,
'expired': 1,
'session': 1,
'invalid': 2,
'insecure_none': 1,
})
def test_missing_database_is_an_error(self):
with tempfile.TemporaryDirectory() as root:
with self.assertRaises(FileNotFoundError):
collect(Path(root) / 'missing-profile')
if __name__ == '__main__':
unittest.main()
+163 -27
View File
@@ -1,14 +1,48 @@
import base64
import hashlib
import json
import os
import sqlite3
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import unittest
from contextlib import closing
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
from firefox_localstorage import decode_value, export_profile, snappy_decode, valid_origin
from firefox_localstorage import (
decode_value, export_profile, firefox_profile_in_use, normalize_origin, snappy_decode, valid_origin,
)
try:
import cryptography # noqa: F401 (only needed for the encryption test)
HAVE_CRYPTOGRAPHY = True
except ImportError:
HAVE_CRYPTOGRAPHY = False
SCRIPT = Path(__file__).resolve().parents[1] / 'tools' / 'firefox_localstorage.py'
def write_ls_origin(profile, directory_name, origin, items):
ls = Path(profile) / 'storage' / 'default' / directory_name / 'ls'
ls.mkdir(parents=True)
with closing(sqlite3.connect(ls / 'data.sqlite')) as con, con:
con.execute('CREATE TABLE "database" (origin TEXT)')
con.execute('INSERT INTO "database" VALUES (?)', (origin,))
con.execute(
'CREATE TABLE data (key TEXT, utf16_length INTEGER, conversion_type INTEGER, '
'compression_type INTEGER, last_access_time INTEGER, value BLOB)'
)
for key, value in items.items():
con.execute('INSERT INTO data VALUES (?,?,?,?,?,?)', (key, len(value), 1, 0, 0, value.encode()))
def make_profile(root):
profile = Path(root) / 'profile'
write_ls_origin(profile, 'https+++first.test', 'https://first.test', {'login': 'token-A'})
return profile
class FirefoxLocalStorageTest(unittest.TestCase):
@@ -33,34 +67,136 @@ class FirefoxLocalStorageTest(unittest.TestCase):
self.assertFalse(valid_origin('https://example.org/some/path'))
self.assertFalse(valid_origin('javascript:alert(1)'))
def test_origin_normalization_matches_chromium_url_parser(self):
self.assertEqual(normalize_origin('HTTPS://Example.ORG:443/'), 'https://example.org')
self.assertEqual(normalize_origin('http://Example.org:80'), 'http://example.org')
self.assertEqual(normalize_origin('https://example.org:8443'), 'https://example.org:8443')
self.assertEqual(normalize_origin('https://[::1]:443'), 'https://[::1]')
self.assertIsNone(normalize_origin('https://例え.jp')) # Firefox stores punycode
self.assertIsNone(normalize_origin('https://example.org^userContextId=1'))
self.assertIsNone(normalize_origin('https://[::1'))
self.assertIsNone(normalize_origin('https://example.org:not-a-port'))
def test_export_all_offline_origins_and_permissions(self):
with tempfile.TemporaryDirectory() as t:
p=Path(t)
for name, origin, value in [('https+++first.test','https://first.test','token-A'), ('https+++second.test','https://second.test','こんにちは')]:
d=p/'storage'/'default'/name/'ls'
d.mkdir(parents=True)
with sqlite3.connect(d/'data.sqlite') as con:
con.execute('CREATE TABLE "database" (origin TEXT)')
con.execute('INSERT INTO "database" VALUES (?)',(origin,))
con.execute('CREATE TABLE data (key TEXT, utf16_length INTEGER, conversion_type INTEGER, compression_type INTEGER, last_access_time INTEGER, value BLOB)')
con.execute('INSERT INTO data VALUES (?,?,?,?,?,?)',('login',len(value),1,0,0,value.encode()))
con.close()
(p/'storage'/'default'/'idb-site'/'idb').mkdir(parents=True)
(p/'storage'/'default'/'idb-site'/'idb'/'1.sqlite').touch()
sites,warnings=export_profile(p)
self.assertEqual(len(sites),2)
p = Path(t)
write_ls_origin(p, 'https+++first.test', 'https://first.test', {'login': 'token-A'})
write_ls_origin(p, 'https+++second.test', 'https://second.test', {'login': 'こんにちは'})
(p / 'storage' / 'default' / 'idb-site' / 'idb').mkdir(parents=True)
(p / 'storage' / 'default' / 'idb-site' / 'idb' / '1.sqlite').touch()
sites, warnings = export_profile(p)
self.assertEqual(len(sites), 2)
self.assertFalse(warnings)
self.assertEqual([s['origin'] for s in sites],['https://first.test','https://second.test'])
output=p/'export.portage.json'
script=Path(__file__).resolve().parents[1]/'tools'/'firefox_localstorage.py'
r=subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output),'--plaintext'],capture_output=True,text=True)
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(os.stat(output).st_mode & 0o777,0o600)
parsed=json.loads(output.read_text())
self.assertEqual(parsed['meta']['counts']['localStorage'],2)
self.assertEqual(parsed['meta']['unsupported']['indexedDBOrigins'],1)
self.assertEqual(len(parsed['data']['localStorage']),2)
self.assertNotEqual(subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output)],capture_output=True).returncode,0)
self.assertEqual([s['origin'] for s in sites], ['https://first.test', 'https://second.test'])
output = p / 'export.portage.json'
result = subprocess.run(
[sys.executable, str(SCRIPT), '--profile', str(p), '--output', str(output), '--plaintext'],
capture_output=True, text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(os.stat(output).st_mode & 0o777, 0o600)
parsed = json.loads(output.read_text())
self.assertEqual(parsed['meta']['counts']['localStorage'], 2)
self.assertEqual(parsed['meta']['unsupported']['indexedDBOrigins'], 1)
self.assertEqual(len(parsed['data']['localStorage']), 2)
# Existing output is never overwritten, even by the encrypted path.
self.assertNotEqual(subprocess.run(
[sys.executable, str(SCRIPT), '--profile', str(p), '--output', str(output)],
capture_output=True,
).returncode, 0)
def test_export_normalizes_duplicate_and_invalid_origins(self):
with tempfile.TemporaryDirectory() as t:
p = Path(t)
write_ls_origin(p, 'https+++upper.test', 'HTTPS://Upper.TEST:443/', {'k': 'v'})
write_ls_origin(p, 'https+++canonical.test', 'https://upper.test', {'k': 'v'})
write_ls_origin(p, 'https+++container.test', 'https://container.test^userContextId=1', {'k': 'v'})
sites, warnings = export_profile(p)
self.assertEqual([s['origin'] for s in sites], ['https://upper.test'])
self.assertEqual(len(warnings), 2)
def test_output_symlink_is_not_followed(self):
with tempfile.TemporaryDirectory() as t:
p = Path(t)
profile = make_profile(p)
victim = p / 'victim'
victim.mkdir()
output = p / 'export.portage.json'
os.symlink(victim / 'created.json', output)
result = subprocess.run(
[sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output), '--plaintext'],
capture_output=True, text=True,
)
self.assertNotEqual(result.returncode, 0)
self.assertFalse((victim / 'created.json').exists())
self.assertTrue(output.is_symlink())
def test_firefox_lock_detection(self):
with tempfile.TemporaryDirectory() as t:
profile = make_profile(Path(t))
self.assertFalse(firefox_profile_in_use(profile))
lock = profile / '.parentlock'
lock.write_bytes(b'')
# A stale lock file alone does not count as a running profile.
self.assertFalse(firefox_profile_in_use(profile))
descriptor = os.open(lock, os.O_RDONLY)
try:
self.assertTrue(firefox_profile_in_use(profile))
finally:
os.close(descriptor)
self.assertFalse(firefox_profile_in_use(profile))
def test_cli_refuses_a_running_profile(self):
with tempfile.TemporaryDirectory() as t:
profile = make_profile(Path(t))
output = Path(t) / 'export.portage.json'
lock = profile / '.parentlock'
lock.write_bytes(b'')
descriptor = os.open(lock, os.O_RDONLY)
try:
result = subprocess.run(
[sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output),
'--plaintext'],
capture_output=True, text=True,
)
finally:
os.close(descriptor)
self.assertNotEqual(result.returncode, 0)
self.assertIn('close Firefox', result.stderr)
self.assertFalse(output.exists())
@unittest.skipUnless(HAVE_CRYPTOGRAPHY, 'cryptography package is not installed')
def test_encrypted_export_roundtrip(self):
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
passphrase = 'synthetic-passphrase-for-test-123'
with tempfile.TemporaryDirectory() as t:
p = Path(t)
profile = make_profile(p)
write_ls_origin(profile, 'https+++second.test', 'https://second.test', {'secret': 'secret-value-猫'})
output = p / 'encrypted.portage.json'
result = subprocess.run(
[sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output),
'--passphrase-stdin'],
input=passphrase + '\n', capture_output=True, text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(os.stat(output).st_mode & 0o777, 0o600)
raw = output.read_text()
self.assertNotIn('secret-value', raw)
wrapper = json.loads(raw)
meta = wrapper['portage']
self.assertEqual(meta['format'], 'portage-bundle-encrypted')
self.assertEqual(meta['iterations'], 250000)
key = hashlib.pbkdf2_hmac(
'sha256', passphrase.encode(), base64.b64decode(meta['salt']), meta['iterations'], dklen=32,
)
plaintext = AESGCM(key).decrypt(
base64.b64decode(meta['iv']), base64.b64decode(wrapper['ciphertext']), None,
)
inner = json.loads(plaintext)
self.assertEqual(inner['meta']['counts']['localStorage'], 2)
self.assertEqual(inner['data']['localStorage'][1]['items']['secret'], 'secret-value-猫')
if __name__ == '__main__':
+72
View File
@@ -0,0 +1,72 @@
'use strict';
// Path/symlink handling for the IndexedDB tool. Runs in dry-run mode only, so
// no Firefox or Chromium executable is needed and no browser profile is touched.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {migrate, options} = require('../tools/indexeddb_migrate.cjs');
function createQuotaDatabase(profile) {
// Use the Python toolchain when node:sqlite is unavailable.
const script = `import sqlite3,sys\ncon=sqlite3.connect(sys.argv[1])\ncon.execute('CREATE TABLE origin (origin TEXT, client_usages TEXT)')\ncon.execute('INSERT INTO origin VALUES (?,?)', ('https://example.test','I1234'))\ncon.commit()\ncon.close()`;
const result = require('node:child_process').spawnSync('python3', ['-c', script, path.join(profile, 'storage.sqlite')], {encoding: 'utf8'});
assert.equal(result.status, 0, result.stderr);
}
async function main() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-idb-paths-'));
try {
const source = path.join(root, 'firefox-profile');
const target = path.join(root, 'chromium-profile');
fs.mkdirSync(source);
fs.mkdirSync(target);
createQuotaDatabase(source);
// A symlinked --firefox-profile must be resolved before cp/browser launch;
// otherwise `cp -a` copies the symlink and Firefox opens the source profile.
const sourceLink = path.join(root, 'firefox-link');
fs.symlinkSync(source, sourceLink);
const dry = await migrate({
firefoxProfile: sourceLink, chromiumProfile: target,
firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'),
apply: false,
});
assert.equal(dry.origins, 1);
// A target that is a symlink to the source must be rejected, not silently
// used as the destination profile.
const targetLink = path.join(root, 'chromium-link');
fs.symlinkSync(source, targetLink);
await assert.rejects(() => migrate({
firefoxProfile: sourceLink, chromiumProfile: targetLink,
firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'),
apply: false,
}), /must differ|looks like a Firefox profile/);
// A Firefox-looking Chromium target is refused before anything is written.
fs.writeFileSync(path.join(target, 'prefs.js'), '');
await assert.rejects(() => migrate({
firefoxProfile: source, chromiumProfile: target,
firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'),
apply: false,
}), /looks like a Firefox profile/);
const parsed = options([
'--firefox-profile', source, '--chromium-profile', target,
'--firefox', '/usr/bin/firefox', '--chromium', '/usr/bin/chromium',
'--chromium-profile-directory', 'Profile 1',
]);
assert.equal(parsed.chromiumProfileDirectory, 'Profile 1');
assert.throws(() => options([
'--firefox-profile', source, '--chromium-profile', target,
'--firefox', '/usr/bin/firefox', '--chromium', '/usr/bin/chromium',
'--chromium-profile-directory', '../escape',
]), /Invalid Chromium profile directory/);
console.log('PASS: IndexedDB path resolution, symlink and profile guards');
} finally {
fs.rmSync(root, {recursive: true, force: true});
}
}
main().catch((error) => { console.error(error.stack); process.exitCode = 1; });
+79
View File
@@ -0,0 +1,79 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const cp = require('node:child_process');
const {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed} =
require('../tools/profile_safety.cjs');
function waitFor(predicate, timeoutMs = 3000) {
const start = Date.now();
return new Promise((resolve, reject) => {
const poll = () => {
if (predicate()) return resolve();
if (Date.now() - start > timeoutMs) return reject(new Error('timed out waiting for lock state'));
setTimeout(poll, 25);
};
poll();
});
}
async function main() {
assert.throws(() => assertSafeTargetProfile('/'), /root or home/);
assert.throws(() => assertSafeTargetProfile(os.homedir()), /root or home/);
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-safety-'));
const firefoxProfile = path.join(root, 'firefox-profile');
const chromiumProfile = path.join(root, 'chromium-profile');
fs.mkdirSync(firefoxProfile);
fs.mkdirSync(chromiumProfile);
fs.writeFileSync(path.join(firefoxProfile, 'prefs.js'), '');
try {
assert.throws(() => assertSafeTargetProfile(firefoxProfile), /looks like a Firefox profile/);
assert.equal(assertSafeTargetProfile(chromiumProfile), chromiumProfile);
assert.equal(assertSafeTargetProfile(path.join(root, 'not-created-yet')),
path.join(root, 'not-created-yet'));
// Fresh disposable profiles keep Puppeteer's --password-store=basic, while
// existing profiles must not be switched to the fallback cookie key store.
assert.deepEqual(chromiumLaunchProfileOptions(chromiumProfile), {});
fs.mkdirSync(path.join(chromiumProfile, 'Default'));
assert.deepEqual(chromiumLaunchProfileOptions(chromiumProfile).ignoreDefaultArgs,
['--password-store=basic', '--use-mock-keychain']);
// Chrome's lock is a dangling symlink while the browser is running;
// existsSync() would miss it, so the helper must use lstat().
assert.equal(chromiumLockPath(chromiumProfile), null);
assertChromiumClosed(chromiumProfile);
fs.symlinkSync('somehost-4242', path.join(chromiumProfile, 'SingletonLock'));
assert.equal(chromiumLockPath(chromiumProfile), path.join(chromiumProfile, 'SingletonLock'));
assert.throws(() => assertChromiumClosed(chromiumProfile), /SingletonLock present/);
fs.unlinkSync(path.join(chromiumProfile, 'SingletonLock'));
// Stale lock file: exists but is not held open => the profile is closed.
const lock = firefoxLockPath(firefoxProfile);
// prefs.js is a marker, not a lock; add one.
fs.writeFileSync(path.join(firefoxProfile, '.parentlock'), '');
assert.equal(firefoxLockPath(firefoxProfile), path.join(firefoxProfile, '.parentlock'));
assert.equal(isLockHeld(path.join(firefoxProfile, '.parentlock')), false);
assertFirefoxClosed(firefoxProfile);
// A live process holding the lock file open must be detected.
const child = cp.spawn(process.execPath, ['-e',
"require('node:fs').openSync(process.argv[1], 'r'); setTimeout(() => {}, 15000);",
path.join(firefoxProfile, '.parentlock')], {stdio: 'ignore'});
try {
await waitFor(() => isLockHeld(path.join(firefoxProfile, '.parentlock')));
assert.throws(() => assertFirefoxClosed(firefoxProfile), /appears to be in use/);
} finally {
child.kill('SIGKILL');
}
await waitFor(() => !isLockHeld(path.join(firefoxProfile, '.parentlock')));
assertFirefoxClosed(firefoxProfile);
console.log('PASS: profile target and Firefox lock safety checks');
} finally {
fs.rmSync(root, {recursive: true, force: true});
}
}
main().catch((error) => { console.error(error.stack); process.exitCode = 1; });
+110 -30
View File
@@ -1,33 +1,113 @@
'use strict';
const assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
const {validOrigin, validateBundle}=require('../tools/chromium_localstorage_import.cjs');
for (const browser of ['chrome','firefox']) {
const src=fs.readFileSync(`${browser}/dashboard.js`,'utf8');
const start=src.indexOf('function mapSameSite(');
const end=src.indexOf('async function importTabs(',start);
assert(start>0 && end>start);
const ctx=vm.createContext({URL,Number,Array,IS_FIREFOX:browser==='firefox',tick:async()=>{}});
vm.runInContext(src.slice(start,end),ctx);
for(const s of ['strict','lax','no_restriction','unspecified']) {
assert.equal(ctx.mapSameSite(s),s);
// Exercises the dashboard's cookie collection/import code in a VM with mocked
// WebExtension APIs; no real browser profile is read or written.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const {validOrigin, validateBundle} = require('../tools/chromium_localstorage_import.cjs');
function browserContext(browser) {
const source = fs.readFileSync(`${browser}/dashboard.js`, 'utf8');
const context = vm.createContext({
URL, Number, Array, String, Object, IS_FIREFOX: browser === 'firefox', tick: async () => {},
});
for (const [startMarker, endMarker] of [
['async function collectCookies()', 'async function collectTabs()'],
['function mapSameSite(s)', 'async function importTabs('],
]) {
const start = source.indexOf(startMarker);
const end = source.indexOf(endMarker, start);
assert(start > 0 && end > start, `${browser}: missing ${startMarker}`);
vm.runInContext(source.slice(start, end), context);
}
assert.equal(ctx.mapSameSite('unknown'),'unspecified');
(async()=>{
const written=[];
ctx.api={cookies:{getAllCookieStores:async()=>[{id:browser==='firefox'?'firefox-default':'0'}],set:async d=>{written.push(d);return d;}}};
const r=await ctx.importCookies([
{name:'test',value:'value',domain:'example.com',path:'/',hostOnly:true,sameSite:'unspecified'},
{name:'partition',value:'v',domain:'example.com',path:'/',hostOnly:true,sameSite:'lax',partitionKey:{topLevelSite:'https://site.test'}},
{name:'container',domain:'example.org',storeId:'firefox-container-1',hostOnly:true},
],()=>{});
assert.equal(r.imported,2);assert.equal(r.skipped,1);
assert.equal(written[0].sameSite,'unspecified');
assert.equal(written[1].partitionKey.topLevelSite,'https://site.test');
if(browser==='firefox')assert.equal(written[0].firstPartyDomain,'');
console.log(browser+': cookie import metadata and SameSite passed');
})().catch(e=>{console.error(e);process.exitCode=1});
return context;
}
assert(validOrigin('https://example.org'));
assert(!validOrigin('javascript:foo'));
assert.throws(()=>validateBundle({portage:{format:'portage-bundle',version:1},data:{localStorage:[{origin:'https://example.org/path',items:{x:'y'}}]}}));
assert.throws(()=>validateBundle({portage:{format:'portage-bundle',version:1},data:{localStorage:[{origin:'https://example.org',items:{x:123}}]}}));
async function main() {
for (const browser of ['chrome', 'firefox']) {
const firefox = browser === 'firefox';
const context = browserContext(browser);
const defaultStoreId = firefox ? 'firefox-default' : '0';
for (const sameSite of ['strict', 'lax', 'no_restriction', 'unspecified']) {
assert.equal(context.mapSameSite(sameSite), sameSite);
}
assert.equal(context.mapSameSite(undefined), 'unspecified');
assert.equal(context.mapSameSite('unknown'), 'unspecified');
// collectCookies: partitioned cookies must be requested explicitly for
// both browsers; a store that cannot be read must not abort the scan.
const queries = [];
context.api = {
cookies: {
getAllCookieStores: async () => [
{id: defaultStoreId}, {id: firefox ? 'firefox-container-1' : '1'}, {id: 'unreadable-store'},
],
getAll: async (query) => {
queries.push({...query});
if (query.storeId === 'unreadable-store') throw new Error('store is not accessible');
return [{
name: 'cookie-' + query.storeId, value: 'v', domain: 'example.com', path: '/',
secure: true, httpOnly: true, sameSite: 'lax', session: true, hostOnly: true,
storeId: query.storeId, partitionKey: {topLevelSite: 'https://top.test', hasCrossSiteAncestor: false},
firstPartyDomain: firefox ? '' : undefined,
}];
},
},
};
const collected = await context.collectCookies();
assert.equal(queries.length, 3);
for (const query of queries) {
assert.equal(Object.keys(query.partitionKey).length, 0, `${browser}: partitionKey filter missing`);
assert.equal(typeof query.storeId, 'string');
if (firefox) assert.equal(query.firstPartyDomain, null);
else assert.equal('firstPartyDomain' in query, false, 'Chrome rejects unknown firstPartyDomain');
}
assert.equal(collected.count, 2, `${browser}: unreadable store aborted collection`);
assert.equal(collected.data[0].partitionKey.topLevelSite, 'https://top.test');
// importCookies: only the browser default store is a valid target, and
// partitioned/FPI metadata must survive the conversion.
const written = [];
context.api = {cookies: {set: async (details) => { written.push(details); return details; }}};
const result = await context.importCookies([
{name: 'plain', value: 'v', domain: 'example.com', path: '/', hostOnly: true, sameSite: undefined},
{name: 'partitioned', value: 'v', domain: 'example.com', path: '/', hostOnly: true, sameSite: 'lax',
partitionKey: {topLevelSite: 'https://top.test', hasCrossSiteAncestor: true}},
{name: 'container', value: 'v', domain: 'example.com', path: '/', storeId: 'firefox-container-1'},
{name: 'incognito', value: 'v', domain: 'example.com', path: '/', storeId: '1'},
{name: 'fpi', value: 'v', domain: 'example.com', path: '/', firstPartyDomain: 'example.com'},
], () => {});
const names = written.map((details) => details.name);
assert.equal(result.imported, firefox ? 3 : 2, `${browser}: unexpected import count`);
assert.equal(result.skipped, firefox ? 2 : 3, `${browser}: unexpected skip count`);
assert.deepEqual(names, firefox ? ['plain', 'partitioned', 'fpi'] : ['plain', 'partitioned']);
for (const details of written) assert.equal(details.storeId, defaultStoreId);
assert.equal('sameSite' in written[0], false, 'unspecified must omit the attribute');
assert.equal(written.find((details) => details.name === 'partitioned').partitionKey.hasCrossSiteAncestor, true);
if (firefox) {
assert.equal(written[0].firstPartyDomain, '');
assert.equal(written.find((details) => details.name === 'fpi').firstPartyDomain, 'example.com');
}
console.log(`${browser}: cookie collect/import metadata, partitioning, SameSite passed`);
}
assert(validOrigin('https://example.org'));
assert(!validOrigin('javascript:foo'));
assert.throws(() => validateBundle({portage: {format: 'portage-bundle', version: 1},
data: {localStorage: [{origin: 'https://example.org/path', items: {x: 'y'}}]}}));
assert.throws(() => validateBundle({portage: {format: 'portage-bundle', version: 1},
data: {localStorage: [{origin: 'https://example.org', items: {x: 123}}]}}));
// A __proto__ storage key is data, not a prototype mutation; JSON.parse
// defines it as an own property, and validateBundle must accept it.
const protoBundle = JSON.parse('{"portage":{"format":"portage-bundle","version":1},' +
'"data":{"localStorage":[{"origin":"https://example.org","items":{"__proto__":"value"}}]}}');
const protoItems = validateBundle(protoBundle).sites[0].items;
assert.equal(Object.getPrototypeOf(protoItems), Object.prototype);
assert.equal(Object.prototype.hasOwnProperty.call(protoItems, '__proto__'), true);
assert.equal(protoItems['__proto__'], 'value');
console.log('PASS: dashboard cookies and bundle validation');
}
main().catch((error) => { console.error(error.stack); process.exitCode = 1; });