Debian Codegraph @

tests/TestSpecial.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (c) 2008-2026 Andrew Ziem.
3 #
4 # This work is licensed under the terms of the GNU GPL, version 3 or
5 # later. See the COPYING file in the top-level directory.
6
7
8 """
9 Test case for module Special
10 """
11
12 # standard imports
13 import contextlib
14 import os
15 import re
16 import shutil
17 import sqlite3
18 from unittest import mock
19
20 # first party imports
21 from bleachbit.Options import options
22 from bleachbit import FileUtilities, Special
23 from bleachbit import IS_WINDOWS
24 from tests import common
25
26 CHROME_BOOKMARKS = b"""
27 {
28 "checksum": "0313bd70dd6343134782af4b233016bf",
29 "roots": {
30 "bookmark_bar": {
31 "children": [ ],
32 "date_added": "12985843036082659",
33 "date_modified": "0",
34 "id": "1",
35 "name": "Bookmarks Bar",
36 "type": "folder"
37 },
38 "other": {
39 "children": [ {
40 "children": [ {
41 "date_added": "12985843072462200",
42 "id": "6",
43 "name": "BleachBit",
44 "type": "url",
45 "url": "https://www.bleachbit.org/"
46 } ],
47 "date_added": "12985843051141788",
48 "date_modified": "12985843072462200",
49 "id": "4",
50 "name": "software",
51 "type": "folder"
52 }, {
53 "children": [ {
54 "date_added": "12985843081812026",
55 "id": "7",
56 "name": "Slashdot",
57 "type": "url",
58 "url": "http://www.slashdot.org/"
59 } ],
60 "date_added": "12985843060482329",
61 "date_modified": "12985843081812026",
62 "id": "5",
63 "name": "news",
64 "type": "folder"
65 } ],
66 "date_added": "12985843036082740",
67 "date_modified": "0",
68 "id": "2",
69 "name": "Other Bookmarks",
70 "type": "folder"
71 },
72 "synced": {
73 "children": [ ],
74 "date_added": "12985843036082744",
75 "date_modified": "0",
76 "id": "3",
77 "name": "Mobile Bookmarks",
78 "type": "folder"
79 }
80 },
81 "version": 1
82 }"""
83
84 # <Default/History> from Google Chrome 23
85 CHROME_HISTORY_SQL = """
86 CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR);
87 INSERT INTO "meta" VALUES('version','23');
88 CREATE TABLE urls(id INTEGER PRIMARY KEY,url LONGVARCHAR,title LONGVARCHAR,visit_count INTEGER DEFAULT 0 NOT NULL,typed_count INTEGER DEFAULT 0 NOT NULL,last_visit_time INTEGER NOT NULL,hidden INTEGER DEFAULT 0 NOT NULL,favicon_id INTEGER DEFAULT 0 NOT NULL);
89 INSERT INTO "urls" VALUES(1,'http://sqlite.org/','SQLite Home Page',1,0,13001833567334094,0,0);
90 INSERT INTO "urls" VALUES(2,'https://www.bleachbit.org/','BleachBit - Clean Disk Space, Maintain Privacy',1,0,13001833567892577,0,0);
91 CREATE TABLE visits(id INTEGER PRIMARY KEY,url INTEGER NOT NULL,visit_time INTEGER NOT NULL,from_visit INTEGER,transition INTEGER DEFAULT 0 NOT NULL,segment_id INTEGER,is_indexed BOOLEAN,visit_duration INTEGER DEFAULT 0 NOT NULL);
92 INSERT INTO "visits" VALUES(1,1,13001833567334094,0,805306374,0,1,8629624);
93 INSERT INTO "visits" VALUES(2,2,13001833567892577,0,805306374,0,1,9249493);
94 CREATE TABLE keyword_search_terms (keyword_id INTEGER NOT NULL,url_id INTEGER NOT NULL,lower_term LONGVARCHAR NOT NULL,term LONGVARCHAR NOT NULL);
95 INSERT INTO "keyword_search_terms" VALUES(2,3,'bleachbit','bleachbit');
96 CREATE TABLE downloads (id INTEGER PRIMARY KEY,full_path LONGVARCHAR NOT NULL,url LONGVARCHAR NOT NULL,start_time INTEGER NOT NULL,received_bytes INTEGER NOT NULL,total_bytes INTEGER NOT NULL,state INTEGER NOT NULL,end_time INTEGER NOT NULL,opened INTEGER NOT NULL);
97 CREATE TABLE segments (id INTEGER PRIMARY KEY,name VARCHAR,url_id INTEGER NON NULL,pres_index INTEGER DEFAULT -1 NOT NULL);
98 CREATE TABLE segment_usage (id INTEGER PRIMARY KEY,segment_id INTEGER NOT NULL,time_slot INTEGER NOT NULL,visit_count INTEGER DEFAULT 0 NOT NULL);
99 """
100
101
102 # <Default/Web Data> from Google Chrome 23
103 CHROME_WEBDATA = """
104 CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR);
105 INSERT INTO "meta" VALUES('version','46');
106 CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,show_in_default_list INTEGER,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0,sync_guid VARCHAR);
107 INSERT INTO "keywords" VALUES(2,'Google','google.com','http://www.google.com/favicon.ico','{google:baseURL}search?q={searchTerms}&{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}{google:assistedQueryStats}{google:searchFieldtrialParameter}sourceid=chrome&ie={inputEncoding}',1,'',0,0,'UTF-8',1,'{google:baseSuggestURL}search?{google:searchFieldtrialParameter}client=chrome&hl={language}&q={searchTerms}&sugkey={google:suggestAPIKeyParameter}',1,0,'{google:baseURL}webhp?sourceid=chrome-instant&{google:RLZ}{google:instantEnabledParameter}ie={inputEncoding}',0,'2D65ABE4-008A-21F1-8C9E-C95DE46CC245');
108 INSERT INTO "keywords" VALUES(3,'Yahoo! Canada','ca.yahoo.com','http://ca.search.yahoo.com/favicon.ico','http://ca.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&p={searchTerms}',1,'',0,0,'UTF-8',1,'http://gossip.ca.yahoo.com/gossip-ca-sayt?output=fxjsonp&command={searchTerms}',2,0,'',0,'F4BAF053-6C8E-6183-C8BB-3104F82260AD');
109 INSERT INTO "keywords" VALUES(4,'Yahoo! Québec','qc.yahoo.com','http://qc.search.yahoo.com/favicon.ico','http://qc.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&p={searchTerms}',1,'',0,0,'UTF-8',1,'',5,0,'',0,'B42D7616-CF8F-6677-A206-19345BB5FE0F');
110 INSERT INTO "keywords" VALUES(5,'Bing','bing.com','http://www.bing.com/s/wlflag.ico','http://www.bing.com/search?setmkt=en-CA&q={searchTerms}',1,'',0,0,'UTF-8',1,'http://api.bing.com/osjson.aspx?query={searchTerms}&language={language}',3,0,'',0,'73FA48F9-1ABD-BA46-F563-1AF75572B5DF');
111 INSERT INTO "keywords" VALUES(6,'Bing','bing.com_','http://www.bing.com/s/wlflag.ico','http://www.bing.com/search?setmkt=fr-CA&q={searchTerms}',1,'',0,0,'UTF-8',1,'http://api.bing.com/osjson.aspx?query={searchTerms}&language={language}',7,0,'',0,'2D932B46-8F26-5C02-7E2F-BE62F263BE9D');
112 INSERT INTO "keywords" VALUES(7,'cnn.com','cnn.com','http://www.cnn.com/favicon.ico','http://www.cnn.com/search/?query={searchTerms}&x=0&y=0&primaryType=mixed&sortBy=relevance&intl=false',1,'',1357360881,0,'UTF-8',0,'',0,0,'',1357360881,'0B71F4CA-380D-0228-064F-24CDF1F8FBD1');
113 CREATE TABLE keywords_backup(
114 id INT,
115 short_name TEXT,
116 keyword TEXT,
117 favicon_url TEXT,
118 url TEXT,
119 safe_for_autoreplace INT,
120 originating_url TEXT,
121 date_created INT,
122 usage_count INT,
123 input_encodings TEXT,
124 show_in_default_list INT,
125 suggest_url TEXT,
126 prepopulate_id INT,
127 created_by_policy INT,
128 instant_url TEXT,
129 last_modified INT,
130 sync_guid TEXT
131 );
132 INSERT INTO "keywords_backup" VALUES(2,'Google','google.com','http://www.google.com/favicon.ico','{google:baseURL}search?q={searchTerms}&{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}{google:assistedQueryStats}{google:searchFieldtrialParameter}sourceid=chrome&ie={inputEncoding}',1,'',0,0,'UTF-8',1,'{google:baseSuggestURL}search?{google:searchFieldtrialParameter}client=chrome&hl={language}&q={searchTerms}&sugkey={google:suggestAPIKeyParameter}',1,0,'{google:baseURL}webhp?sourceid=chrome-instant&{google:RLZ}{google:instantEnabledParameter}ie={inputEncoding}',0,'CB88DDB4-E4A2-80BC-3BEE-C8F02FDBA58A');
133 INSERT INTO "keywords_backup" VALUES(3,'Yahoo! Canada','ca.yahoo.com','http://ca.search.yahoo.com/favicon.ico','http://ca.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&p={searchTerms}',1,'',0,0,'UTF-8',1,'http://gossip.ca.yahoo.com/gossip-ca-sayt?output=fxjsonp&command={searchTerms}',2,0,'',0,'21CD15EC-B9CA-4DCB-8526-0A4048CBA5F3');
134 INSERT INTO "keywords_backup" VALUES(4,'Yahoo! Québec','qc.yahoo.com','http://qc.search.yahoo.com/favicon.ico','http://qc.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&p={searchTerms}',1,'',0,0,'UTF-8',1,'',5,0,'',0,'AB0C2A23-C483-F255-8BEB-7A2B4E0C465F');
135 INSERT INTO "keywords_backup" VALUES(5,'Bing','bing.com','http://www.bing.com/s/wlflag.ico','http://www.bing.com/search?setmkt=en-CA&q={searchTerms}',1,'',0,0,'UTF-8',1,'http://api.bing.com/osjson.aspx?query={searchTerms}&language={language}',3,0,'',0,'D77A8BC1-3CD6-4AB5-93B2-72B0C2E94E73');
136 INSERT INTO "keywords_backup" VALUES(6,'Bing','bing.com_','http://www.bing.com/s/wlflag.ico','http://www.bing.com/search?setmkt=fr-CA&q={searchTerms}',1,'',0,0,'UTF-8',1,'http://api.bing.com/osjson.aspx?query={searchTerms}&language={language}',7,0,'',0,'E1035236-31F4-216A-632A-A7323A1B7A70');
137 CREATE TABLE autofill (name VARCHAR, value VARCHAR, value_lower VARCHAR, pair_id INTEGER PRIMARY KEY, count INTEGER DEFAULT 1);
138 INSERT INTO "autofill" VALUES('ltmpl','sso','sso',1,3);
139 CREATE TABLE autofill_dates ( pair_id INTEGER DEFAULT 0, date_created INTEGER DEFAULT 0);
140 INSERT INTO "autofill_dates" VALUES(1,1268958682);
141 CREATE TABLE autofill_profile_names ( guid VARCHAR, first_name VARCHAR, middle_name VARCHAR, last_name VARCHAR, full_name VARCHAR);
142 INSERT INTO "autofill_profile_names" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA','andrew','','ziem','');
143 CREATE TABLE autofill_profile_emails ( guid VARCHAR, email VARCHAR);
144 INSERT INTO "autofill_profile_emails" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA','[email protected]');
145 CREATE TABLE "autofill_profile_phones" ( guid VARCHAR, number VARCHAR);
146 INSERT INTO "autofill_profile_phones" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA','123457890');
147 CREATE TABLE "autofill_profiles" ( guid VARCHAR PRIMARY KEY, company_name VARCHAR, street_address VARCHAR, dependent_locality VARCHAR, city VARCHAR, state VARCHAR, zipcode VARCHAR, sorting_code VARCHAR, country_code VARCHAR, date_modified INTEGER NOT NULL DEFAULT 0, origin VARCHAR DEFAULT '', language_code VARCHAR, use_count INTEGER NOT NULL DEFAULT 0, use_date INTEGER NOT NULL DEFAULT 0);
148 INSERT INTO "autofill_profiles" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA','','1234 anywhere st','','City','ST','000000','','US',1386736740,'','',5,1437861201);
149 CREATE TABLE local_addresses(guid VARCHAR, use_count INTEGER, use_date INTEGER, date_modified INTEGER, language_code VARCHAR, label VARCHAR, initial_creator_id INTEGER, last_modifier_id INTEGER);
150 INSERT INTO "local_addresses" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 1, 1667776445, 1667776456, '', '', 70073, 70073);
151 CREATE TABLE local_addresses_type_tokens(guid VARCHAR, type INTEGER, value VARCHAR, verification_status INTEGER);
152 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 60, '', 0);
153 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 3, 'andrew', 1);
154 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 5, 'ziem', 1);
155 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 77, '1234 anywhere st', 3);
156 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 33, 'City', 0);
157 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 36, 'US', 3);
158 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 35, '0000000', 3);
159 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 9, '[email protected]', 0);
160 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 14, '123457890', 0);
161 INSERT INTO "local_addresses_type_tokens" VALUES('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA', 60, 'bleachbit company', 0);
162 CREATE TABLE server_addresses (id VARCHAR,company_name VARCHAR,street_address VARCHAR,address_1 VARCHAR,address_2 VARCHAR,address_3 VARCHAR,address_4 VARCHAR,postal_code VARCHAR,sorting_code VARCHAR,country_code VARCHAR,language_code VARCHAR, recipient_name VARCHAR, phone_number VARCHAR);
163 INSERT INTO "server_addresses" VALUES('a','','123 anywhere','ST','City','',NULL,'0000','','US','','andrew ziem','+1 000-000-0000');
164 """
165
166 # databases/Databases.db from Chromium 12
167 CHROME_DATABASES_DB = """
168 CREATE TABLE Databases (id INTEGER PRIMARY KEY AUTOINCREMENT, origin TEXT NOT NULL, name TEXT NOT NULL, description TEXT NOT NULL, estimated_size INTEGER NOT NULL);
169 INSERT INTO "Databases" VALUES(1,'chrome-extension_fjnbnpbmkenffdnngjfgmeleoegfcffe_0','stylish','Stylish Styles',5242880);
170 INSERT INTO "Databases" VALUES(2,'http_samy.pl_0','sqlite_evercookie','evercookie',1048576);
171 """
172
173
174 FIREFOX78_PLACES_SQL = """
175 CREATE TABLE moz_annos ( id INTEGER PRIMARY KEY, place_id INTEGER NOT NULL, anno_attribute_id INTEGER, content LONGVARCHAR, flags INTEGER DEFAULT 0, expiration INTEGER DEFAULT 0, type INTEGER DEFAULT 0, dateAdded INTEGER DEFAULT 0, lastModified INTEGER DEFAULT 0);
176 CREATE TABLE moz_historyvisits ( id INTEGER PRIMARY KEY, from_visit INTEGER, place_id INTEGER, visit_date INTEGER, visit_type INTEGER, session INTEGER);
177 INSERT INTO moz_historyvisits VALUES(1,0,13,1597441943359769,2,0);
178 CREATE TABLE moz_inputhistory ( place_id INTEGER NOT NULL, input LONGVARCHAR NOT NULL, use_count INTEGER, PRIMARY KEY (place_id, input));
179 INSERT INTO moz_inputhistory VALUES(12,'bleachbit.org',1);
180 CREATE TABLE moz_meta (key TEXT PRIMARY KEY, value NOT NULL) WITHOUT ROWID ;
181 INSERT INTO moz_meta VALUES('origin_frecency_count',3);
182 INSERT INTO moz_meta VALUES('origin_frecency_sum',52148);
183 INSERT INTO moz_meta VALUES('origin_frecency_sum_of_squares',2312614202);
184 CREATE TABLE moz_origins ( id INTEGER PRIMARY KEY, prefix TEXT NOT NULL, host TEXT NOT NULL, frecency INTEGER NOT NULL, UNIQUE (prefix, host) );
185 INSERT INTO moz_origins VALUES(1,'https://','support.mozilla.org',-1);
186 CREATE TABLE moz_bookmarks (id INTEGER PRIMARY KEY, type INTEGER, fk INTEGER DEFAULT NULL, parent INTEGER, position INTEGER, title LONGVARCHAR, keyword_id INTEGER, folder_type TEXT, dateAdded INTEGER, lastModified INTEGER, guid TEXT, syncStatus INTEGER NOT NULL DEFAULT 0, syncChangeCounter INTEGER NOT NULL DEFAULT 1);
187 INSERT INTO moz_bookmarks VALUES(1,2,NULL,2,0,'Mozilla Firefox',NULL,NULL,1604681523951000,1604681523951000,'I3rvZbIM7HUh',0,1);
188 INSERT INTO moz_bookmarks VALUES(5,1,4,7,3,'About Us',NULL,NULL,1604681523951000,1604681523951000,'kz-2zgrxtHgA',0,1);
189 INSERT INTO moz_bookmarks VALUES(6,1,5,3,0,'Getting Started',NULL,NULL,1604681524006000,1604681524006000,'cLugSkZM_O0C',0,1);
190 INSERT INTO moz_bookmarks VALUES(7,1,10,5,0,'tubecast',NULL,NULL,1606684638623000,1606684669335000,'pTngoES7vS4t',1,4);
191 INSERT INTO moz_bookmarks VALUES(8,1,1048,5,1,'reddit: the front page of the internet',NULL,NULL,1625670902669000,1625670902669000,'HboIUJAnNSQq',1,1);
192 INSERT INTO moz_bookmarks VALUES(9,1,1049,5,2,'Wikipedia',NULL,NULL,1625678442192000,1625678442192000,'kLNboN4LnQyQ',1,1);
193 INSERT INTO moz_bookmarks VALUES(10,1,1047,5,3,'Base64 Image Encoder',NULL,NULL,1625678511003000,1625678511003000,'mJswt5mUpX6V',1,1);
194 INSERT INTO moz_bookmarks VALUES(11,1,1052,5,4,'Lebab Modernizing Javascript Code',NULL,NULL,1625678570164000,1625678570164000,'KnR8OLEDutKj',1,1);
195 INSERT INTO moz_bookmarks VALUES(12,1,1055,5,5,'Epoch Times | Truth and Tradition',NULL,NULL,1634407905800000,1634407905800000,'xiNkiy3pRnRM',1,1);
196 INSERT INTO moz_bookmarks VALUES(13,1,1074,5,3,'javascript_bookmark',NULL,NULL,1634541546301000,1634541578237000,'5zn7HFpTz9Zk',1,3);
197 INSERT INTO moz_bookmarks VALUES(14,1,1062,5,6,'Local File Bookmark',NULL,NULL,1634541546301000,1634541578237000,'5zn7HFpTz9Zl',1,1);
198 INSERT INTO moz_bookmarks VALUES(15,1,1063,5,7,'Deep Path Bookmark',NULL,NULL,1634541546301000,1634541578237000,'5zn7HFpTz9Zm',1,1);
199 CREATE TABLE moz_places (id INTEGER PRIMARY KEY, url LONGVARCHAR, title LONGVARCHAR, rev_host LONGVARCHAR, visit_count INTEGER DEFAULT 0, hidden INTEGER DEFAULT 0 NOT NULL, typed INTEGER DEFAULT 0 NOT NULL, frecency INTEGER DEFAULT -1 NOT NULL, last_visit_date INTEGER , guid TEXT, foreign_count INTEGER DEFAULT 0 NOT NULL, url_hash INTEGER DEFAULT 0 NOT NULL , description TEXT, preview_image_url TEXT, origin_id INTEGER REFERENCES moz_origins(id));
200 INSERT INTO moz_places VALUES(4,'https://www.mozilla.org/en-US/about/',NULL,'gro.allizom.www.',0,0,0,-1,NULL,'qku4XnVuwKXz',1,47358774953055,NULL,NULL,2);
201 INSERT INTO moz_places VALUES(5,'https://www.mozilla.org/en-US/firefox/central/',NULL,'gro.allizom.www.',0,0,1,-1,NULL,'zEH44cXgEbiW',1,47356370932282,NULL,NULL,2);
202 INSERT INTO moz_places VALUES(10,'javascript:location.href="tubecast:link="+location.href%3B',NULL,'.',0,0,0,-1,NULL,'CVfq8S1yN9ob',1,61195540700963,NULL,NULL,4);
203 INSERT INTO moz_places VALUES(1047,'https://www.base64-image.de/',NULL,'ed.egami-46esab.www.',0,0,1,-1,NULL,'CdMLr4ivquym',1,47357677431233,NULL,NULL,52);
204 INSERT INTO moz_places VALUES(1048,'https://www.reddit.com/',NULL,'moc.tidder.www.',2,0,1,2250,1634421287533000,'Wm14AXzccAt2',1,47359719085711,NULL,NULL,53);
205 INSERT INTO moz_places VALUES(1049,'https://www.wikipedia.org/',NULL,'gro.aidepikiw.www.',0,0,1,-1,NULL,'S1IyTeEofltl',1,47356939545358,NULL,NULL,54);
206 INSERT INTO moz_places VALUES(1052,'https://lebab.unibtc.me/editor/',NULL,'em.ctbinu.babel.',0,0,1,-1,NULL,'y4p_ByrC9qLQ',1,47358502989035,NULL,NULL,56);
207 INSERT INTO moz_places VALUES(1055,'https://theepochtimes.com/',NULL,'gro.afadnulaf.',0,0,1,-1,NULL,'oLhJTCaTzP2H',1,47357288143104,NULL,NULL,59);
208 INSERT INTO moz_places VALUES(1056,'https://www.youtube.com/',NULL,'moc.ebutuoy.www.',1,0,1,2000,1634421071354000,'nqpzAbgRUY_X',0,47360296250519,NULL,NULL,60);
209 INSERT INTO moz_places VALUES(1057,'https://duckduckgo.com/?t=ffab&q=duck',NULL,'moc.ogkcudkcud.',1,0,1,2000,1634421160833000,'R1rB2oXM7G1w',0,47357908794703,NULL,NULL,61);
210 INSERT INTO moz_places VALUES(1058,'https://duckduckgo.com/?t=ffab&q=duck&ia=web',NULL,'moc.ogkcudkcud.',1,0,0,100,1634421161955000,'LfiihU6H8JTJ',0,47357725238190,NULL,NULL,61);
211 INSERT INTO moz_places VALUES(1059,'https://duckduckgo.com/',NULL,'moc.ogkcudkcud.',1,0,0,100,1634421168747000,'3_aU-W5GQtVY',0,47357557756924,NULL,NULL,61);
212 INSERT INTO moz_places VALUES(1060,'https://www.reddit.com/r/bulgaria/?f=flair_name%3A%22IMAGE%22',NULL,'moc.tidder.www.',1,0,0,100,1634421202542000,'91A-gGXCdGJo',0,47358238683930,NULL,NULL,53);
213 INSERT INTO moz_places VALUES(1074,'javascript:(function(d){d.PwnBkmkVer=3%3Bd.body.appendChild(d.createElement(''script'')).src=''https://deturl.com/ld.php?''+1*new Date%3B})(document)%3B',NULL,'.',0,0,0,140,NULL,'MHLDGrz54C06',1,61196492657957,NULL,NULL,69);
214 INSERT INTO moz_places VALUES(1061,'file:///home/user/local-page.html',NULL,'',0,0,0,-1,NULL,'aB1cD2eF3gH4',0,47359988123456,NULL,NULL,70);
215 INSERT INTO moz_places VALUES(1062,'file:///home/user/bookmarked-page.html',NULL,'',0,0,0,-1,NULL,'bC2dE3fG4hI5',1,47359988123457,NULL,NULL,70);
216 INSERT INTO moz_places VALUES(1063,'https://deep.example.com/path/to/page',NULL,'moc.elpmaxe.peekd.',0,0,0,-1,NULL,'cD3eF4gH5iJ6',1,47359988123458,NULL,NULL,71);
217 """
218
219
220 firefox78_favicons_sql = """
221 CREATE TABLE moz_icons (id INTEGER PRIMARY KEY, icon_url TEXT NOT NULL, fixed_icon_url_hash INTEGER NOT NULL, width INTEGER NOT NULL DEFAULT 0, root INTEGER NOT NULL DEFAULT 0, color INTEGER, expire_ms INTEGER NOT NULL DEFAULT 0, data BLOB);
222 INSERT INTO moz_icons VALUES(1,'fake-favicon-uri:https://support.mozilla.org/en-US/products/firefox',136572340459075,32,0,NULL,1605286324005,NULL);
223 INSERT INTO moz_icons VALUES(2,'fake-favicon-uri:https://support.mozilla.org/en-US/kb/customize-firefox-controls-buttons-and-toolbars?utm_source=firefox-browser&utm_medium=default-bookmarks&utm_campaign=customize',136571753046205,32,0,NULL,1605286324005,NULL);
224 INSERT INTO moz_icons VALUES(3,'fake-favicon-uri:https://www.mozilla.org/en-US/contribute/',136575540959674,65535,0,NULL,1605286324005,NULL);
225 INSERT INTO moz_icons VALUES(4,'fake-favicon-uri:https://www.mozilla.org/en-US/about/',136574776814270,65535,0,NULL,1605286324005,NULL);
226 INSERT INTO moz_icons VALUES(5,'fake-favicon-uri:https://www.mozilla.org/en-US/firefox/central/',136572730577725,32,0,NULL,1605286324059,NULL);
227 INSERT INTO moz_icons VALUES(6,'https://www.redditstatic.com/desktop2x/img/favicon/android-icon-192x192.png',292525218,192,0,NULL,1635025978652,NULL);
228 INSERT INTO moz_icons VALUES(7,'https://www.redditstatic.com/desktop2x/img/favicon/favicon-16x16.png',2364888881,16,0,NULL,1635025978655,NULL);
229 INSERT INTO moz_icons VALUES(13,'https://lebab.unibtc.me/favicon.ico',2265932027,32,1,NULL,1635027449609,NULL);
230 INSERT INTO moz_icons VALUES(14,'https://theepochtimes.com/favicon.ico',4178624107,16,1,NULL,1634917808089,NULL);
231 INSERT INTO moz_icons VALUES(23,'https://duckduckgo.com/assets/icons/meta/DDG-iOS-icon_152x152.png?v=2',2781351171,144,0,NULL,1635025961392,NULL);
232 INSERT INTO moz_icons VALUES(24,'https://duckduckgo.com/favicon.ico',4139558766,16,1,NULL,1635025969003,NULL);
233 INSERT INTO moz_icons VALUES(25,'https://duckduckgo.com/favicon.ico',4139558766,32,1,NULL,1635025969003,NULL);
234 INSERT INTO moz_icons VALUES(29,'https://www.mozilla.org/media/img/favicons/firefox/browser/favicon-196x196.59e3822720be.png',3142301241,192,0,NULL,1634993957394,NULL);
235 INSERT INTO moz_icons VALUES(33,'https://www.youtube.com/s/desktop/89d6cbd0/img/favicon_144x144.png',2213531744,144,0,NULL,1635025873106,NULL);
236 INSERT INTO moz_icons VALUES(34,'https://www.youtube.com/s/desktop/89d6cbd0/img/favicon.ico',2155043602,16,0,NULL,1635025873107,NULL);
237 INSERT INTO moz_icons VALUES(42,'https://www.base64-image.de/favicon.ico',834103348,16,1,NULL,1635088213227,NULL);
238 INSERT INTO moz_icons VALUES(43,'fake-favicon-uri:file:///home/user/local-page.html',1234567890,16,0,NULL,1635088213228,NULL);
239 INSERT INTO moz_icons VALUES(44,'fake-favicon-uri:file:///home/user/bookmarked-page.html',1234567891,16,0,NULL,1635088213229,NULL);
240 INSERT INTO moz_icons VALUES(45,'https://deep.example.com/media/img/favicon.ico',9876543210,16,0,NULL,1635088213230,NULL);
241 CREATE TABLE moz_icons_to_pages ( page_id INTEGER NOT NULL, icon_id INTEGER NOT NULL, expire_ms INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (page_id, icon_id), FOREIGN KEY (page_id) REFERENCES moz_pages_w_icons ON DELETE CASCADE, FOREIGN KEY (icon_id) REFERENCES moz_icons ON DELETE CASCADE ) WITHOUT ROWID;
242 INSERT INTO moz_icons_to_pages VALUES(1,1,1605286324005);
243 INSERT INTO moz_icons_to_pages VALUES(2,2,1605286324005);
244 INSERT INTO moz_icons_to_pages VALUES(3,3,1605286324005);
245 INSERT INTO moz_icons_to_pages VALUES(4,4,1605286324005);
246 INSERT INTO moz_icons_to_pages VALUES(5,5,1605286324059);
247 INSERT INTO moz_icons_to_pages VALUES(6,6,1635025978652);
248 INSERT INTO moz_icons_to_pages VALUES(6,7,1635025978655);
249 INSERT INTO moz_icons_to_pages VALUES(14,23,1634993919592);
250 INSERT INTO moz_icons_to_pages VALUES(16,29,1634993957394);
251 INSERT INTO moz_icons_to_pages VALUES(17,33,1635025873106);
252 INSERT INTO moz_icons_to_pages VALUES(17,34,1635025873107);
253 INSERT INTO moz_icons_to_pages VALUES(21,6,1635025978652);
254 INSERT INTO moz_icons_to_pages VALUES(21,7,1635025978655);
255 INSERT INTO moz_icons_to_pages VALUES(22,43,1635088213228);
256 INSERT INTO moz_icons_to_pages VALUES(23,44,1635088213229);
257 INSERT INTO moz_icons_to_pages VALUES(24,45,1635088213230);
258 CREATE TABLE moz_pages_w_icons ( id INTEGER PRIMARY KEY, page_url TEXT NOT NULL, page_url_hash INTEGER NOT NULL );
259 INSERT INTO moz_pages_w_icons VALUES(1,'https://support.mozilla.org/en-US/products/firefox',47357795150914);
260 INSERT INTO moz_pages_w_icons VALUES(2,'https://support.mozilla.org/en-US/kb/customize-firefox-controls-buttons-and-toolbars?utm_source=firefox-browser&utm_medium=default-bookmarks&utm_campaign=customize',47359532431620);
261 INSERT INTO moz_pages_w_icons VALUES(3,'https://www.mozilla.org/en-US/contribute/',47358034485371);
262 INSERT INTO moz_pages_w_icons VALUES(4,'https://www.mozilla.org/en-US/about/',47358774953055);
263 INSERT INTO moz_pages_w_icons VALUES(5,'https://www.mozilla.org/en-US/firefox/central/',47356370932282);
264 INSERT INTO moz_pages_w_icons VALUES(6,'https://www.reddit.com/',47359719085711);
265 INSERT INTO moz_pages_w_icons VALUES(14,'https://duckduckgo.com/?t=ffab&q=firefox+version+history&ia=web',47359570459686);
266 INSERT INTO moz_pages_w_icons VALUES(16,'https://www.mozilla.org/en-US/firefox/78.0/releasenotes/',47357311834713);
267 INSERT INTO moz_pages_w_icons VALUES(17,'https://www.youtube.com/',47360296250519);
268 INSERT INTO moz_pages_w_icons VALUES(21,'https://www.reddit.com/r/bulgaria/?f=flair_name%3A%22IMAGE%22',47358238683930);
269 INSERT INTO moz_pages_w_icons VALUES(22,'file:///home/user/local-page.html',47359988123456);
270 INSERT INTO moz_pages_w_icons VALUES(23,'file:///home/user/other-page.html',47359988123457);
271 INSERT INTO moz_pages_w_icons VALUES(24,'https://deep.example.com/path/to/page',47359988123458);
272 """
273
274
275 class SpecialAssertions:
276
277 def assertTablesAreEmpty(self, path, tables):
278 """Asserts SQLite tables exists and are empty"""
279 if not os.path.lexists(path):
280 raise AssertionError(f'Path does not exist: {path}')
281 with contextlib.closing(sqlite3.connect(path)) as conn:
282 cursor = conn.cursor()
283 for table in tables:
284 cursor.execute(f'select 1 from {table} limit 1')
285 row = cursor.fetchone()
286 if row:
287 raise AssertionError(f'Table is not empty: {table}')
288
289
290 class SpecialTestCase(common.BleachbitTestCase, SpecialAssertions):
291
292 """Test case for module Special"""
293
294 def setUp(self):
295 """Create test browser files."""
296
297 super().setUp()
298
299 self.dir_base = self.mkdtemp(prefix='bleachbit-test-special')
300
301 dir_google_chrome_default = os.path.join(
302 self.dir_base, 'google-chrome/Default/')
303 os.makedirs(dir_google_chrome_default)
304
305 # google-chrome/Default/Bookmarks
306 bookmark_path = os.path.join(
307 dir_google_chrome_default, 'Bookmarks')
308 with open(bookmark_path, 'wb') as f:
309 f.write(CHROME_BOOKMARKS)
310
311 # google-chrome/Default/Web Data
312 FileUtilities.execute_sqlite3(os.path.join(
313 dir_google_chrome_default, 'Web Data'), CHROME_WEBDATA)
314
315 # google-chrome/Default/History
316 FileUtilities.execute_sqlite3(os.path.join(
317 dir_google_chrome_default, 'History'), CHROME_HISTORY_SQL)
318
319 # google-chrome/Default/databases/Databases.db
320 os.makedirs(os.path.join(dir_google_chrome_default, 'databases'))
321 FileUtilities.execute_sqlite3(
322 os.path.join(dir_google_chrome_default, 'databases/Databases.db'), CHROME_DATABASES_DB)
323
324 dir_firefox_default = os.path.join(
325 self.dir_base, 'firefox/default-release/')
326 os.makedirs(dir_firefox_default)
327
328 # firefox/xxxxx.default-release/places.sqlite
329 FileUtilities.execute_sqlite3(
330 os.path.join(dir_firefox_default, 'places.sqlite'), FIREFOX78_PLACES_SQL)
331
332 # firefox/xxxxx.default-release/favicons.sqlite
333 FileUtilities.execute_sqlite3(
334 os.path.join(dir_firefox_default, 'favicons.sqlite'), firefox78_favicons_sql)
335
336 def tearDown(self):
337 """Remove test browser files."""
338 super().tearDown()
339 from bleachbit.General import gc_collect
340 gc_collect()
341 shutil.rmtree(self.dir_base)
342
343 def sqlite_clean_helper(self, sql, fn, clean_func, check_func=None, setup_func=None):
344 """Helper for cleaning special SQLite cleaning
345
346 sql: string with SQL code to initialize an SQLite database
347 fn: filename of an existing SQLite database
348 clean_func: a function to clean the SQLite database
349 check_func (optional): a function to perform extra checks on the database
350 setup_func (optional): a function to initialize the database before executing the SQL
351 """
352
353 self.assertFalse(
354 sql and fn, "sql and fn are mutually exclusive ways to create the data")
355
356 if fn and sql:
357 raise RuntimeError(
358 'sqlite_clean_helper: supply either fn or sql but not both')
359 elif fn:
360 filename = os.path.normpath(os.path.join(self.dir_base, fn))
361 self.assertExists(filename)
362 # create sqlite file
363 elif sql:
364 # create test file
365 filename = self.mkstemp(prefix='bleachbit-test-sqlite')
366
367 # additional setup
368 if setup_func:
369 setup_func(filename)
370
371 # before SQL creation executed, cleaning should fail
372 self.assertRaises(sqlite3.DatabaseError, clean_func, filename)
373 # create
374 FileUtilities.execute_sqlite3(filename, sql)
375 self.assertExists(filename)
376 else:
377 raise RuntimeError('neither fn nor sql supplied')
378
379 # clean the file
380 old_shred = options.get('shred')
381 # options.set('shred', False, commit=False)
382 options.set_override('shred', False)
383 self.assertFalse(options.get('shred'))
384 clean_func(filename)
385 options.set_override('shred', True)
386 self.assertTrue(options.get('shred'))
387 clean_func(filename)
388 options.set_override('shred', old_shred)
389 self.assertExists(filename)
390
391 # check
392 if check_func:
393 check_func(self, filename)
394
395 # tear down
396 # FileUtilities.delete(filename)
397 # self.assertNotExists(filename)
398
399 def test_delete_chrome_autofill(self):
400 """Unit test for delete_chrome_autofill"""
401 fn = "google-chrome/Default/Web Data"
402
403 def check_autofill(testcase, filename):
404 testcase.assertTablesAreEmpty(
405 filename,
406 ['autofill', 'local_addresses',
407 'local_addresses_type_tokens', 'server_addresses']
408 )
409
410 self.sqlite_clean_helper(
411 None, fn, Special.delete_chrome_autofill, check_func=check_autofill)
412
413 def test_delete_chrome_databases_db(self):
414 """Unit test for delete_chrome_databases_db"""
415 self.sqlite_clean_helper(
416 None, "google-chrome/Default/databases/Databases.db",
417 Special.delete_chrome_databases_db)
418
419 def test_delete_chrome_history(self):
420 """Unit test for delete_chrome_history"""
421
422 def check_chrome_history(self, filename):
423 conn = sqlite3.connect(filename)
424 try:
425 c = conn.cursor()
426 c.execute('select id from urls')
427 ids = [row[0] for row in c]
428 # id 1 is sqlite.org which is not a bookmark and should be cleaned
429 # id 2 is www.bleachbit.org which is a bookmark and should
430 # be cleaned
431 self.assertEqual(ids, [2])
432
433 # these tables should always be empty after cleaning
434 self.assertTablesAreEmpty(filename, ['downloads', 'keyword_search_terms',
435 'segment_usage', 'segments', 'visits'])
436 finally:
437 conn.close()
438
439 self.sqlite_clean_helper(None, "google-chrome/Default/History",
440 Special.delete_chrome_history, check_chrome_history)
441
442 def test_delete_chrome_keywords(self):
443 """Unit test for delete_chrome_keywords"""
444
445 def check_chrome_keywords(self, filename):
446 conn = sqlite3.connect(filename)
447 try:
448 c = conn.cursor()
449 c.execute('select id from keywords')
450 ids = [row[0] for row in c]
451 self.assertEqual(ids, [2, 3, 4, 5, 6])
452 finally:
453 conn.close()
454
455 self.sqlite_clean_helper(None, "google-chrome/Default/Web Data",
456 Special.delete_chrome_keywords,
457 check_chrome_keywords)
458
459 def test_delete_office_registrymodifications(self):
460 """Unit test for delete_office_registrymodifications"""
461 xml_str = (
462 '<?xml version="1.0" encoding="UTF-8"?>\n'
463 '<oor:items xmlns:oor="http://openoffice.org/2001/registry">\n'
464 ' <item oor:path="/org.openoffice.Office.Histories/Histories/'
465 'PickList">\n'
466 ' <value>keep me out of it</value>\n'
467 ' </item>\n'
468 '</oor:items>\n')
469 fn = os.path.join(self.mkdtemp(prefix='bleachbit-office-xcu'),
470 'registrymodifications.xcu')
471 self.write_file(fn, text=xml_str)
472 Special.delete_office_registrymodifications(fn)
473 with open(fn, encoding='utf-8') as f:
474 contents = f.read()
475 self.assertNotIn('PickList', contents)
476
477 def test_delete_office_registrymodifications_rejects_dtd(self):
478 """A registrymodifications.xcu with a DTD is rejected (entity-expansion defense)"""
479 xml_str = (
480 '<?xml version="1.0"?>\n'
481 '<!DOCTYPE oor:items [ <!ENTITY x "y"> ]>\n'
482 '<oor:items xmlns:oor="http://openoffice.org/2001/registry"/>\n')
483 fn = os.path.join(self.mkdtemp(prefix='bleachbit-office-xcu-dtd'),
484 'registrymodifications.xcu')
485 self.write_file(fn, text=xml_str)
486 self.assertRaises(
487 ValueError, Special.delete_office_registrymodifications, fn)
488
489 def test_delete_office_registrymodifications_refuses_symlink(self):
490 """delete_office_registrymodifications() must not write through a symlink"""
491 xml_str = (
492 '<?xml version="1.0" encoding="UTF-8"?>\n'
493 '<oor:items xmlns:oor="http://openoffice.org/2001/registry">\n'
494 ' <item oor:path="/org.openoffice.Office.Histories/Histories/'
495 'PickList">\n'
496 ' <value>keep me out of it</value>\n'
497 ' </item>\n'
498 '</oor:items>\n')
499 fn = os.path.join(self.mkdtemp(prefix='bleachbit-office-xcu-link'),
500 'registrymodifications.xcu')
501 self.write_file(fn, text=xml_str)
502 with mock.patch('bleachbit.Special.os.path.islink',
503 side_effect=lambda p: p == fn):
504 with self.assertRaises(OSError):
505 Special.delete_office_registrymodifications(fn)
506 with open(fn, encoding='utf-8') as f:
507 contents = f.read()
508 self.assertIn('PickList', contents)
509
510 def test_delete_mozilla_url_history(self):
511 """Test for delete_mozilla_url_history"""
512 self.sqlite_clean_helper(
513 None, "firefox/default-release/places.sqlite",
514 Special.delete_mozilla_url_history)
515
516 # Pale Moon 28 comes from an older Firefox, and it does not have moz_origins or moz_meta in places.sqlite.
517 re_palemoon = '(CREATE TABLE|INSERT INTO) moz_(meta|origins)'
518 sql_palemoon = '\n'.join([line for line in FIREFOX78_PLACES_SQL.split(
519 '\n') if not re.search(re_palemoon, line)])
520 self.sqlite_clean_helper(
521 sql_palemoon, None, Special.delete_mozilla_url_history)
522
523 def test_delete_mozilla_no_places(self):
524 """Test for delete_mozilla_url_history without places.sqlite
525
526 See https://github.com/bleachbit/bleachbit/issues/1423
527 """
528 sql_no_places = FIREFOX78_PLACES_SQL + ";\ndrop table moz_places;"
529 self.sqlite_clean_helper(
530 sql_no_places, None, Special.delete_mozilla_url_history)
531
532 def test_delete_mozilla_favicons(self):
533 """Test for delete_mozilla_favicons"""
534
535 # Firefox favicons for domains are kept differently than those for specific pages:
536 # https://bugzilla.mozilla.org/show_bug.cgi?id=1468968
537 # so we need a more detailed unit test.
538
539 fn = "firefox/default-release/favicons.sqlite"
540 self.sqlite_clean_helper(
541 None, fn, Special.delete_mozilla_favicons)
542
543 filename = os.path.normpath(os.path.join(self.dir_base, fn))
544 with contextlib.closing(sqlite3.connect(filename)) as conn:
545 cursor = conn.cursor()
546 icon_entries = cursor.execute('SELECT * FROM moz_icons').fetchall()
547 icon_ids = map(lambda x: x[0], icon_entries)
548 cursor.close()
549
550 # not removed ids from moz_icons table
551 # Icons 3 and 29: on bookmarked domains with deep URL paths, kept
552 # regardless of path depth (fix for issue #1537).
553 # icon 44: bookmarked file:// page (exercises fake-favicon-uri: prefix
554 # stripping with a hostless scheme where lstrip would mangle the URL)
555 # icon 45: bookmarked page with deep-path favicon (exact URL match
556 # preserves the page mapping, so the icon survives)
557 expected_icon_ids = [3, 4, 5, 6, 7, 13, 14, 29, 42, 44, 45]
558 assert sorted(expected_icon_ids) == sorted(icon_ids)
559
560 def test_delete_mozilla_favicons_all_bookmarked(self):
561 """Test delete_mozilla_favicons when all icons are bookmarked.
562
563 Exercises the `if ids_to_delete:` guard added in PR #2186:
564 when every icon is bookmarked, the deletable-id list is empty and
565 the guard skips emitting no-op UPDATE/DELETE statements. (`IN ()`
566 is valid SQL in modern SQLite and matches no rows, so the guard is
567 an optimization, not a crash fix.)
568 """
569
570 tempdir = self.mkdir('all-bookmarked')
571 places_path = os.path.join(tempdir, 'places.sqlite')
572 favicons_path = os.path.join(tempdir, 'favicons.sqlite')
573
574 places_sql = """
575 CREATE TABLE moz_bookmarks (id INTEGER PRIMARY KEY, type INTEGER, fk INTEGER DEFAULT NULL, parent INTEGER, position INTEGER, title LONGVARCHAR, keyword_id INTEGER, folder_type TEXT, dateAdded INTEGER, lastModified INTEGER, guid TEXT, syncStatus INTEGER NOT NULL DEFAULT 0, syncChangeCounter INTEGER NOT NULL DEFAULT 1);
576 INSERT INTO moz_bookmarks VALUES(1,1,1,2,0,'My Bookmark',NULL,NULL,1604681523951000,1604681523951000,'aaaaaaaaaaaa',0,1);
577 CREATE TABLE moz_places (id INTEGER PRIMARY KEY, url LONGVARCHAR, title LONGVARCHAR, rev_host LONGVARCHAR, visit_count INTEGER DEFAULT 0, hidden INTEGER DEFAULT 0 NOT NULL, typed INTEGER DEFAULT 0 NOT NULL, frecency INTEGER DEFAULT -1 NOT NULL, last_visit_date INTEGER , guid TEXT, foreign_count INTEGER DEFAULT 0 NOT NULL, url_hash INTEGER DEFAULT 0 NOT NULL , description TEXT, preview_image_url TEXT, origin_id INTEGER REFERENCES moz_origins(id));
578 INSERT INTO moz_places VALUES(1,'https://example.com/',NULL,'moc.elpmaxe.',0,0,0,-1,NULL,'bbbbbbbbbbbb',1,123456789,NULL,NULL,1);
579 """
580
581 favicons_sql = """
582 CREATE TABLE moz_icons (id INTEGER PRIMARY KEY, icon_url TEXT NOT NULL, fixed_icon_url_hash INTEGER NOT NULL, width INTEGER NOT NULL DEFAULT 0, root INTEGER NOT NULL DEFAULT 0, color INTEGER, expire_ms INTEGER NOT NULL DEFAULT 0, data BLOB);
583 INSERT INTO moz_icons VALUES(1,'https://example.com/favicon.ico',123456789,16,1,NULL,1635088213227,NULL);
584 CREATE TABLE moz_icons_to_pages ( page_id INTEGER NOT NULL, icon_id INTEGER NOT NULL, expire_ms INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (page_id, icon_id), FOREIGN KEY (page_id) REFERENCES moz_pages_w_icons ON DELETE CASCADE, FOREIGN KEY (icon_id) REFERENCES moz_icons ON DELETE CASCADE ) WITHOUT ROWID;
585 INSERT INTO moz_icons_to_pages VALUES(1,1,1635088213227);
586 CREATE TABLE moz_pages_w_icons ( id INTEGER PRIMARY KEY, page_url TEXT NOT NULL, page_url_hash INTEGER NOT NULL );
587 INSERT INTO moz_pages_w_icons VALUES(1,'https://example.com/',123456789);
588 """
589
590 FileUtilities.execute_sqlite3(places_path, places_sql)
591 FileUtilities.execute_sqlite3(favicons_path, favicons_sql)
592
593 options.set_override('shred', False)
594 Special.delete_mozilla_favicons(favicons_path)
595 options.set_override('shred', True)
596 Special.delete_mozilla_favicons(favicons_path)
597
598 with contextlib.closing(sqlite3.connect(favicons_path)) as conn:
599 icon_ids = [r[0] for r in conn.execute(
600 'SELECT id FROM moz_icons').fetchall()]
601
602 # The single bookmarked icon must survive.
603 assert icon_ids == [1]
604
605 def test_delete_mozilla_favicons_issue_1537(self):
606 """Regression test for issue #1537.
607
608 When a bookmarked domain has a favicon with a deep URL path
609 (more than one slash) and the page mapping doesn't exactly
610 match the bookmark URL, the icon must still be kept because
611 the domain is bookmarked.
612
613 https://github.com/bleachbit/bleachbit/issues/1537
614 """
615
616 tempdir = self.mkdir('issue-1537')
617 places_path = os.path.join(tempdir, 'places.sqlite')
618 favicons_path = os.path.join(tempdir, 'favicons.sqlite')
619
620 # Bookmark only the domain root; the page URL in
621 # moz_pages_w_icons is a sub-page that won't exactly match.
622 places_sql = """
623 CREATE TABLE moz_bookmarks (id INTEGER PRIMARY KEY, type INTEGER, fk INTEGER DEFAULT NULL, parent INTEGER, position INTEGER, title LONGVARCHAR, keyword_id INTEGER, folder_type TEXT, dateAdded INTEGER, lastModified INTEGER, guid TEXT, syncStatus INTEGER NOT NULL DEFAULT 0, syncChangeCounter INTEGER NOT NULL DEFAULT 1);
624 INSERT INTO moz_bookmarks VALUES(1,1,1,2,0,'Example',NULL,NULL,1604681523951000,1604681523951000,'aaaaaaaaaaaa',0,1);
625 CREATE TABLE moz_places (id INTEGER PRIMARY KEY, url LONGVARCHAR, title LONGVARCHAR, rev_host LONGVARCHAR, visit_count INTEGER DEFAULT 0, hidden INTEGER DEFAULT 0 NOT NULL, typed INTEGER DEFAULT 0 NOT NULL, frecency INTEGER DEFAULT -1 NOT NULL, last_visit_date INTEGER , guid TEXT, foreign_count INTEGER DEFAULT 0 NOT NULL, url_hash INTEGER DEFAULT 0 NOT NULL , description TEXT, preview_image_url TEXT, origin_id INTEGER REFERENCES moz_origins(id));
626 INSERT INTO moz_places VALUES(1,'https://example.com/',NULL,'moc.elpmaxe.',0,0,0,-1,NULL,'bbbbbbbbbbbb',1,123456789,NULL,NULL,1);
627 """
628
629 favicons_sql = """
630 CREATE TABLE moz_icons (id INTEGER PRIMARY KEY, icon_url TEXT NOT NULL, fixed_icon_url_hash INTEGER NOT NULL, width INTEGER NOT NULL DEFAULT 0, root INTEGER NOT NULL DEFAULT 0, color INTEGER, expire_ms INTEGER NOT NULL DEFAULT 0, data BLOB);
631 INSERT INTO moz_icons VALUES(1,'https://example.com/media/img/favicon.ico',123456789,16,0,NULL,1635088213227,NULL);
632 CREATE TABLE moz_icons_to_pages ( page_id INTEGER NOT NULL, icon_id INTEGER NOT NULL, expire_ms INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (page_id, icon_id), FOREIGN KEY (page_id) REFERENCES moz_pages_w_icons ON DELETE CASCADE, FOREIGN KEY (icon_id) REFERENCES moz_icons ON DELETE CASCADE ) WITHOUT ROWID;
633 INSERT INTO moz_icons_to_pages VALUES(1,1,1635088213227);
634 CREATE TABLE moz_pages_w_icons ( id INTEGER PRIMARY KEY, page_url TEXT NOT NULL, page_url_hash INTEGER NOT NULL );
635 INSERT INTO moz_pages_w_icons VALUES(1,'https://example.com/sub/page',123456789);
636 """
637
638 FileUtilities.execute_sqlite3(places_path, places_sql)
639 FileUtilities.execute_sqlite3(favicons_path, favicons_sql)
640
641 options.set_override('shred', False)
642 Special.delete_mozilla_favicons(favicons_path)
643
644 with contextlib.closing(sqlite3.connect(favicons_path)) as conn:
645 icon_ids = [r[0] for r in conn.execute(
646 'SELECT id FROM moz_icons').fetchall()]
647
648 # The domain https://example.com is bookmarked, so the icon
649 # must be kept even though its page URL doesn't exactly match
650 # the bookmark and its path has 3 slashes.
651 assert icon_ids == [1], \
652 "Icon on bookmarked domain must be kept"
653
654 def test_delete_mozilla_favicons_rejects_non_int_ids(self):
655 """Non-integer icon IDs must raise ValueError to avoid SQL injection."""
656 tempdir = self.mkdir('non-int-ids')
657 places_path = os.path.join(tempdir, 'places.sqlite')
658 favicons_path = os.path.join(tempdir, 'favicons.sqlite')
659 places_sql = """
660 CREATE TABLE moz_bookmarks (id INTEGER PRIMARY KEY, type INTEGER, fk INTEGER DEFAULT NULL, parent INTEGER, position INTEGER, title LONGVARCHAR);
661 INSERT INTO moz_bookmarks VALUES(1,1,1,2,0,'Example');
662 CREATE TABLE moz_places (id INTEGER PRIMARY KEY, url LONGVARCHAR);
663 INSERT INTO moz_places VALUES(1,'https://example.com/');
664 """
665 favicons_sql = """
666 CREATE TABLE moz_icons (id INTEGER PRIMARY KEY, icon_url TEXT NOT NULL);
667 CREATE TABLE moz_icons_to_pages (page_id INTEGER NOT NULL, icon_id INTEGER NOT NULL, expire_ms INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (page_id, icon_id)) WITHOUT ROWID;
668 CREATE TABLE moz_pages_w_icons (id INTEGER PRIMARY KEY, page_url TEXT NOT NULL, page_url_hash INTEGER NOT NULL);
669 """
670 FileUtilities.execute_sqlite3(places_path, places_sql)
671 FileUtilities.execute_sqlite3(favicons_path, favicons_sql)
672
673 def fake_get(path, sql, row_factory=None, parameters=()):
674 if 'icon_url' in sql:
675 # First query: orphaned favicons. Inject a non-integer ID.
676 return [(1, 'https://example.com/'),
677 ('2; drop table moz_icons; --', 'https://other.example/')]
678 # Second query: bookmarked URLs.
679 return ['https://example.com/']
680
681 with mock.patch.object(Special, '_get_sqlite_values', fake_get):
682 with self.assertRaises(ValueError):
683 Special.delete_mozilla_favicons(favicons_path)
684
685 def test_remove_path_from_url(self):
686 """Test the function _remove_path_from_url"""
687 for tests in (('fake-favicon-uri:https://support.mozilla.org/en-US/products/firefox', 'https://support.mozilla.org'),
688 ('https://example.com/', 'https://example.com'),
689 ('https://example.com/path', 'https://example.com'),
690 ('https://example.com/path/', 'https://example.com'),
691 ('https://example.com/path/sub', 'https://example.com'),
692 ('file:///home/user/local-page.html', 'file:///home/user/local-page.html')):
693 self.assertEqual(Special._remove_path_from_url(tests[0]), tests[1])
694
695 def test_get_chrome_bookmark_ids(self):
696 """Unit test for get_chrome_bookmark_ids()"""
697 # does not exist
698 # Google Chrome 23 on Windows 8 does not create a bookmarks file on first startup
699 # (maybe because the network was disconnected or because user created no bookmarks).
700 self.assertEqual(
701 [], Special.get_chrome_bookmark_ids('does_not_exist'))
702
703 def test_get_chrome_bookmark_urls(self):
704 """Unit test for get_chrome_bookmark_urls()"""
705 path = self.write_file('bleachbit-test-sqlite', CHROME_BOOKMARKS)
706
707 self.assertExists(path)
708 urls = Special.get_chrome_bookmark_urls(path)
709 self.assertEqual(
710 set(urls), {'https://www.bleachbit.org/', 'http://www.slashdot.org/'})
711
712 os.unlink(path)
713
714 def test_get_sqlite_int(self):
715 """Unit test for get_sqlite_int()"""
716 sql = """CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,value LONGVARCHAR);
717 INSERT INTO "meta" VALUES('version','20');"""
718 # create test file
719 filename = os.path.join(self.tempdir, 'test_get_sqlite_int.sqlite')
720 FileUtilities.execute_sqlite3(filename, sql)
721 self.assertExists(filename)
722 # run the test
723 ver = Special.get_sqlite_int(
724 filename, "select value from meta where key='version'")
725 self.assertEqual(ver, [20])
726 os.unlink(filename)
727
728 def test_get_sqlite_values(self):
729 """Unit test for get_sqlite_values()"""
730 ddl = """CREATE TABLE foo(id int, value int);INSERT INTO foo VALUES(12, 34), (56, 78);"""
731 sql = 'select id, value from foo'
732 # Special characters check that the path is properly escaped as a
733 # SQLite URI, not misparsed as query/fragment separators.
734 basenames = ['test_get_sqlite_values.sqlite',
735 'space in name.sqlite', 'hash#in#name#.sqlite']
736 if not IS_WINDOWS:
737 basenames.append('question?mark.sqlite')
738 for basename in basenames:
739 with self.subTest(basename=basename):
740 filename = os.path.join(self.tempdir, basename)
741 FileUtilities.execute_sqlite3(filename, ddl)
742 self.assertExists(filename)
743 # pylint: disable=protected-access
744 ver = Special._get_sqlite_values(filename, sql)
745 self.assertEqual(ver, [(12, 34), (56, 78)])
746 ver = Special._get_sqlite_values(
747 filename, f'{sql} where id = 0')
748 self.assertEqual(ver, [])
749 with self.assertRaises(sqlite3.OperationalError):
750 Special._get_sqlite_values(
751 filename, 'select id, value from does_not_exist')
752 os.unlink(filename)
753 # If file is missing, raise exception and do not create the file.
754 non_existing_file = os.path.join(self.tempdir, 'non_existing_file')
755 with self.assertRaises(sqlite3.OperationalError):
756 Special._get_sqlite_values(non_existing_file, sql)
757 self.assertNotExists(non_existing_file)
758
759 def test_sqlite_uri(self):
760 """_sqlite_uri percent-encodes the path so '?' cannot defeat the mode"""
761 from bleachbit.Special import _sqlite_uri
762 uri = _sqlite_uri('/tmp/a?mode=rwc/x.db', 'ro')
763 self.assertTrue(uri.endswith('?mode=ro'))
764 self.assertNotIn('?mode=rwc', uri)
765 self.assertIn('%3F', uri) # the path's '?' is encoded, not a delimiter
766 # no mode -> no query string at all
767 self.assertNotIn('?', _sqlite_uri('/tmp/plain.db'))
768
769 def test_sqlite_table_exists(self):
770 """Unit test for sqlite_table_exists()"""
771 # Create test files with different filenames
772 # Add a space to check for proper escaping/encoding
773 test_filenames = [
774 os.path.join(self.tempdir, 'test_sqlite_table_exists.sqlite'),
775 os.path.join(self.tempdir, 'space in name.sqlite'),
776 os.path.join(self.tempdir, 'hash#in#name#.sqlite'),
777 os.path.join(self.tempdir, 'percent%in%name.sqlite'),
778 ]
779
780 # Windows does not support question mark in filenames.
781 if not IS_WINDOWS:
782 test_filenames.append(
783 os.path.join(self.tempdir, 'question?mark.sqlite'))
784
785 for filename in test_filenames:
786 with self.subTest(filename=filename):
787 # On Windows, use absolute path to test drive letter and slashes.
788 self.assertTrue(os.path.isabs(filename))
789 sql = "CREATE TABLE foo(id int)"
790 FileUtilities.execute_sqlite3(filename, sql)
791 self.assertExists(filename)
792
793 # run the test
794 # pylint: disable=protected-access
795 self.assertTrue(Special.sqlite_table_exists(filename, 'foo'))
796 self.assertFalse(Special.sqlite_table_exists(
797 filename, 'table_does_not_exist'))
798
799 os.unlink(filename)
800
801 # Test non-existing file — should return False, not raise
802 non_existing_file = os.path.join(self.tempdir, 'file_does_not_exist')
803 self.assertFalse(Special.sqlite_table_exists(
804 non_existing_file, 'table_does_not_exist'))
805 self.assertNotExists(non_existing_file)
806
807 def test_sqlite_table_exists_permission_denied(self):
808 """sqlite_table_exists raises PermissionError when the file exists
809 but cannot be opened (e.g. antivirus blocking, exclusive lock).
810
811 Norton Antivirus block access, causing SQLITE_CANTOPEN
812 https://github.com/bleachbit/bleachbit/issues/2288
813 """
814 # Create a valid SQLite database
815 filename = os.path.join(
816 self.tempdir, 'test_permission_denied.sqlite')
817 sql = "CREATE TABLE cookies(host_key TEXT)"
818 FileUtilities.execute_sqlite3(filename, sql)
819 self.assertExists(filename)
820
821 # Simulate SQLITE_CANTOPEN
822 # 14: no extended variant
823 # 782: SQLITE_CANTOPEN_FULLPATH shares low byte 14
824 cantopen_exc = sqlite3.OperationalError(
825 'unable to open database file')
826 for errorcode in (14, 782):
827 cantopen_exc.sqlite_errorcode = errorcode
828
829 with mock.patch('sqlite3.connect',
830 side_effect=cantopen_exc):
831 with self.assertRaises(PermissionError):
832 Special.sqlite_table_exists(filename, 'cookies')
833
834 # Non-existing file with same mock should still return False
835 non_existing = os.path.join(self.tempdir, 'no_such_file.db')
836 with mock.patch('sqlite3.connect',
837 side_effect=cantopen_exc):
838 self.assertFalse(
839 Special.sqlite_table_exists(non_existing, 'cookies'))
840
841 def test_sqlite_table_exists_other_operational_error(self):
842 """sqlite_table_exists returns False for OperationalError other
843 than SQLITE_CANTOPEN (e.g. SQLITE_BUSY)."""
844 filename = os.path.join(
845 self.tempdir, 'test_other_op_error.sqlite')
846 sql = "CREATE TABLE foo(id int)"
847 FileUtilities.execute_sqlite3(filename, sql)
848 self.assertExists(filename)
849
850 # SQLITE_BUSY (5) — should still return False, not raise
851 busy_exc = sqlite3.OperationalError('database is locked')
852 busy_exc.sqlite_errorcode = 5
853
854 with mock.patch('sqlite3.connect',
855 side_effect=busy_exc):
856 self.assertFalse(
857 Special.sqlite_table_exists(filename, 'foo'))
858
859 os.unlink(filename)
860
861 def test_sqlite_is_valid_database(self):
862 """Unit test for _sqlite_is_valid_database()"""
863 sql = "CREATE TABLE foo(id int)"
864 # Special characters check that the path is properly escaped as a
865 # SQLite URI, not misparsed as query/fragment separators.
866 basenames = ['test_sqlite_is_valid_database.sqlite',
867 'space in name.sqlite', 'hash#in#name#.sqlite']
868 if not IS_WINDOWS:
869 basenames.append('question?mark.sqlite')
870 for basename in basenames:
871 with self.subTest(basename=basename):
872 filename = os.path.join(self.tempdir, basename)
873 FileUtilities.execute_sqlite3(filename, sql)
874 self.assertExists(filename)
875 self.assertTrue(Special._sqlite_is_valid_database(filename))
876 os.unlink(filename)
877 # create test file
878 other_file = os.path.join(
879 self.tempdir, 'test_sqlite_is_valid_database_invalid.sqlite')
880 with open(other_file, 'w', encoding='utf-8') as f:
881 f.write('this is not a valid sqlite3 database file')
882 self.assertExists(other_file)
883 self.assertFalse(Special._sqlite_is_valid_database(other_file))
884 os.unlink(other_file)
885
886 def test_sqlite_loop(self):
887 """Repeat SQLite tests
888
889 This may raise a ResourceWarning on Python 3.13
890 """
891 for _ in range(5):
892 self.test_delete_chrome_autofill()
893 self.test_get_sqlite_int()
894 self.test_get_sqlite_values()
895 self.test_sqlite_table_exists()