From 43735ef5b29c35ec2e8ea9f18be8c0670c99fdeb Mon Sep 17 00:00:00 2001 From: vadims <118171981+vadimstruts@users.noreply.github.com> Date: Tue, 9 Jul 2024 12:34:31 +0200 Subject: [PATCH] Deprecate local node support and ipfs scheme (#23808) deprecated IPFS local node support and IPFS scheme https://github.com/brave/brave-browser/issues/37735 --------- Signed-off-by: Vadym Struts Co-authored-by: Nuo Xu --- android/BUILD.gn | 3 - android/brave_java_sources.gni | 1 - .../settings/BravePrivacySettings.java | 11 - .../BravePrivacySettingsIPFSUtils.java | 34 - .../res/xml/brave_privacy_preferences.xml | 6 - .../settings/BravePrivacySettingsTest.java | 2 +- app/brave_command_ids.h | 14 - app/brave_generated_resources.grd | 123 +- app/brave_settings_strings.grdp | 172 -- app/generate_command_metadata.py | 7 - app/theme/BUILD.gn | 2 - app/theme/brave_theme_resources.grd | 3 - app/vector_icons/BUILD.gn | 1 - app/vector_icons/open_in_ipfs.icon | 36 - browser/BUILD.gn | 2 - browser/about_flags.cc | 24 - browser/android/preferences/BUILD.gn | 1 - .../preferences/brave_pref_service_bridge.cc | 6 - .../brave_autocomplete_scheme_classifier.cc | 13 - browser/autocomplete/sources.gni | 6 - browser/brave_browser_process.h | 8 - browser/brave_browser_process_impl.cc | 26 - browser/brave_browser_process_impl.h | 11 - browser/brave_content_browser_client.cc | 27 - ...rave_content_browser_client_browsertest.cc | 1 - browser/brave_prefs_browsertest.cc | 19 - browser/brave_profile_prefs.cc | 16 +- browser/brave_rewards/rewards_tab_helper.cc | 13 - browser/brave_rewards/sources.gni | 6 - browser/brave_tab_helpers.cc | 10 - browser/brave_wallet/BUILD.gn | 9 - .../brave_wallet_auto_pin_service_factory.cc | 104 - .../brave_wallet_auto_pin_service_factory.h | 57 - .../brave_wallet_pin_service_factory.cc | 105 - .../brave_wallet_pin_service_factory.h | 54 - ...browser_context_keyed_service_factories.cc | 23 - .../brave_browsing_data_remover_delegate.cc | 83 - .../brave_browsing_data_remover_delegate.h | 9 - browser/browsing_data/sources.gni | 6 - browser/extensions/BUILD.gn | 10 - .../api/brave_extensions_api_client.cc | 5 - browser/extensions/api/ipfs_api.cc | 612 ------ browser/extensions/api/ipfs_api.h | 255 --- browser/extensions/api/ipfs_apitest.cc | 325 --- .../api/settings_private/brave_prefs_util.cc | 26 - .../extensions/brave_extension_management.cc | 28 - .../extensions/brave_extension_management.h | 9 - .../brave_global_confirm_infobar_delegate.cc | 41 - .../brave_global_confirm_infobar_delegate.h | 56 - .../infobars/brave_global_infobar_service.cc | 35 - .../infobars/brave_global_infobar_service.h | 36 - .../brave_global_infobar_service_factory.cc | 38 - .../brave_global_infobar_service_factory.h | 36 - ...rave_ipfs_always_start_infobar_delegate.cc | 96 - ...brave_ipfs_always_start_infobar_delegate.h | 61 - .../brave_ipfs_fallback_infobar_delegate.cc | 108 - .../brave_ipfs_fallback_infobar_delegate.h | 69 - .../infobars/brave_ipfs_infobar_delegate.cc | 143 -- .../infobars/brave_ipfs_infobar_delegate.h | 73 - browser/infobars/sources.gni | 25 +- browser/ipfs/content_browser_client_helper.cc | 165 -- browser/ipfs/content_browser_client_helper.h | 40 - .../content_browser_client_helper_unittest.cc | 397 ---- browser/ipfs/import/ipfs_import_controller.cc | 366 ---- browser/ipfs/import/ipfs_import_controller.h | 99 - .../ipfs_import_controller_browsertest.cc | 299 --- browser/ipfs/import/save_package_observer.cc | 82 - browser/ipfs/import/save_package_observer.h | 47 - .../save_package_observer_browsertest.cc | 98 - .../ipfs/ipfs_blob_context_getter_factory.cc | 31 - .../ipfs/ipfs_blob_context_getter_factory.h | 33 - ...fs_blob_context_getter_factory_unittest.cc | 83 - browser/ipfs/ipfs_dns_resolver_impl.cc | 80 - browser/ipfs/ipfs_dns_resolver_impl.h | 53 - browser/ipfs/ipfs_host_resolver.cc | 121 -- browser/ipfs/ipfs_host_resolver.h | 77 - browser/ipfs/ipfs_host_resolver_unittest.cc | 268 --- .../ipfs/ipfs_local_pin_service_factory.cc | 57 - browser/ipfs/ipfs_local_pin_service_factory.h | 46 - browser/ipfs/ipfs_policy_browsertest.cc | 173 -- browser/ipfs/ipfs_service_factory.cc | 118 -- browser/ipfs/ipfs_service_factory.h | 42 - browser/ipfs/ipfs_service_impl_delegate.cc | 43 - browser/ipfs/ipfs_service_impl_delegate.h | 41 - .../ipfs/ipfs_subframe_navigation_throttle.cc | 43 - .../ipfs/ipfs_subframe_navigation_throttle.h | 42 - browser/ipfs/ipfs_tab_helper.cc | 553 ----- browser/ipfs/ipfs_tab_helper.h | 189 -- browser/ipfs/ipfs_tab_helper_browsertest.cc | 1154 ----------- browser/ipfs/ipfs_tab_helper_unittest.cc | 727 ------- browser/ipfs/sources.gni | 71 - browser/ipfs/test/BUILD.gn | 84 - .../brave_ipfs_client_updater_browsertest.cc | 145 -- .../test/ipfs_dns_resolver_impl_unittest.cc | 45 - .../ipfs_navigation_throttle_browsertest.cc | 225 --- .../test/ipfs_navigation_throttle_unittest.cc | 475 ----- .../ipfs/test/ipfs_network_utils_unittest.cc | 145 -- .../ipfs_not_connected_page_browsertest.cc | 170 -- .../test/ipfs_onboarding_page_browsertest.cc | 294 --- browser/ipfs/test/ipfs_service_browsertest.cc | 1783 ----------------- .../test/ipns_keys_manager_browsertest.cc | 260 --- .../net/brave_network_delegate_browsertest.cc | 27 - browser/net/brave_request_handler.cc | 13 - ...centralized_dns_network_delegate_helper.cc | 6 +- ...ed_dns_network_delegate_helper_unittest.cc | 12 +- .../ipfs_redirect_network_delegate_helper.cc | 90 - .../ipfs_redirect_network_delegate_helper.h | 23 - ...ect_network_delegate_helper_browsertest.cc | 115 -- ...direct_network_delegate_helper_unittest.cc | 300 --- browser/net/sources.gni | 13 - browser/net/url_context.cc | 25 - browser/net/url_context.h | 2 - browser/policy/brave_simple_policy_map.h | 8 - browser/profiles/BUILD.gn | 1 - browser/profiles/brave_profile_manager.cc | 19 - .../brave_profile_manager_browsertest.cc | 46 +- .../brave_ipfs_page/add_ipfs_peer_dialog.html | 22 - .../brave_ipfs_page/add_ipfs_peer_dialog.ts | 101 - .../brave_ipfs_page/add_p2p_key_dialog.html | 25 - .../brave_ipfs_page/add_p2p_key_dialog.ts | 108 - .../brave_ipfs_browser_proxy.ts | 154 -- .../brave_ipfs_page/brave_ipfs_page.html | 151 -- .../brave_ipfs_page/brave_ipfs_page.ts | 191 -- .../change_ipfs_gateway_dialog.html | 20 - .../change_ipfs_gateway_dialog.ts | 115 -- .../brave_ipfs_page/ipfs_peers_subpage.html | 73 - .../brave_ipfs_page/ipfs_peers_subpage.ts | 174 -- .../brave_ipfs_page/p2p_keys_subpage.html | 109 - .../brave_ipfs_page/p2p_keys_subpage.ts | 253 --- .../rotate_p2p_key_dialog.html | 32 - .../brave_ipfs_page/rotate_p2p_key_dialog.ts | 138 -- .../settings/brave_overrides/basic_page.ts | 16 - .../brave_overrides/page_visibility.ts | 1 - browser/resources/settings/brave_routes.ts | 5 - .../brave_wallet_browser_proxy.ts | 14 - .../brave_wallet_page/brave_wallet_page.html | 16 - .../brave_wallet_page/brave_wallet_page.ts | 54 - browser/resources/settings/settings.gni | 1 - browser/resources/settings/sources.gni | 9 - browser/sources.gni | 8 +- browser/tor/test/BUILD.gn | 1 - .../test/tor_profile_manager_browsertest.cc | 8 - browser/ui/BUILD.gn | 29 - .../android/strings/android_brave_strings.grd | 6 - .../ui/brave_browser_command_controller.cc | 7 - browser/ui/brave_pages.cc | 5 - browser/ui/browser_commands.cc | 18 - browser/ui/browser_commands.h | 1 - browser/ui/toolbar/app_menu_icons.cc | 1 - browser/ui/toolbar/brave_app_menu_model.cc | 212 +- browser/ui/toolbar/brave_app_menu_model.h | 22 - .../brave_app_menu_model_browsertest.cc | 113 -- .../brave_location_bar_model_delegate.cc | 2 - .../infobars/brave_global_infobar_manager.cc | 152 -- .../infobars/brave_global_infobar_manager.h | 49 - .../location_bar/brave_location_bar_view.cc | 73 - .../location_bar/brave_location_bar_view.h | 14 - .../views/location_bar/ipfs_location_view.cc | 162 -- .../views/location_bar/ipfs_location_view.h | 38 - .../android/android_wallet_page_ui.cc | 6 - .../android/android_wallet_page_ui.h | 4 - .../common_handler/wallet_handler.cc | 4 +- .../ui/webui/brave_wallet/wallet_page_ui.cc | 16 - .../ui/webui/brave_wallet/wallet_page_ui.h | 4 - .../ui/webui/brave_wallet/wallet_panel_ui.cc | 18 - .../ui/webui/brave_wallet/wallet_panel_ui.h | 4 - .../webui/brave_web_ui_controller_factory.cc | 19 - browser/ui/webui/brave_webui_source.cc | 1 - browser/ui/webui/ipfs_dom_handler_unittest.cc | 66 - browser/ui/webui/ipfs_ui.cc | 361 ---- browser/ui/webui/ipfs_ui.h | 89 - .../brave_default_extensions_handler.cc | 242 --- .../brave_default_extensions_handler.h | 46 +- ...ave_settings_localized_strings_provider.cc | 78 - .../ui/webui/settings/brave_wallet_handler.cc | 53 +- .../ui/webui/settings/brave_wallet_handler.h | 8 - .../java/templates/BraveConfig.template | 1 - chromium_presubmit_config.json5 | 1 - .../base/threading/thread_restrictions.h | 4 - chromium_src/base/win/default_apps_util.cc | 13 - chromium_src/check_chromium_src_config.json5 | 5 - .../download/download_ui_controller.cc | 18 - .../browser/extensions/extension_util.cc | 45 - .../chrome/browser/prefs/browser_prefs.cc | 4 + .../browser/profiles/profile_io_data.cc | 2 - .../render_view_context_menu.cc | 173 -- .../render_view_context_menu.h | 9 - .../ui/page_info/chrome_page_info_delegate.cc | 19 - .../page_info/chrome_page_info_ui_delegate.cc | 21 - .../page_info/chrome_page_info_ui_delegate.h | 19 - .../views/location_bar/location_icon_view.cc | 5 - .../ui/views/page_info/page_info_main_view.cc | 34 - .../views/page_info/page_info_view_factory.cc | 80 - .../views/page_info/page_info_view_factory.h | 23 - .../permissions/chrome_api_permissions.cc | 58 - .../chrome_permission_message_rules.cc | 27 - .../chrome/common/webui_url_constants.cc | 6 - .../chrome/installer/util/shell_util.cc | 11 - chromium_src/chrome/test/sources.gni | 1 - .../component_updater_service.h | 3 - .../error_page/common/localized_error.cc | 22 - .../infobars/core/infobar_delegate.h | 14 +- .../components/page_info/page_info_ui.cc | 31 - .../components/page_info/page_info_ui.h | 24 - .../policy/tools/generate_policy_source.py | 27 +- .../content/renderer/render_thread_impl.cc | 6 - .../extensions/common/api/_api_features.json | 8 - .../common/api/_manifest_features.json | 4 - chromium_src/extensions/common/constants.h | 16 - .../common/mojom/api_permission_id.mojom | 4 +- .../browser/shared/model/prefs/BUILD.gn | 6 - .../shared/model/prefs/browser_prefs.mm | 8 - .../net/base/lookup_string_in_fixed_set.cc | 15 - chromium_src/net/base/net_error_list.h | 6 - .../services/network/public/cpp/url_util.cc | 29 - common/extensions/api/BUILD.gn | 13 - common/extensions/api/_api_features.json | 2 - common/extensions/api/_ipfs_api_features.json | 107 - .../api/_ipfs_permission_features.json | 19 - common/extensions/api/ipfs.json | 449 ----- components/brave_rewards/browser/BUILD.gn | 5 - .../brave_rewards/browser/publisher_utils.cc | 16 - components/brave_wallet/browser/BUILD.gn | 15 +- .../browser/brave_wallet_auto_pin_service.cc | 370 ---- .../browser/brave_wallet_auto_pin_service.h | 132 -- .../brave_wallet_auto_pin_service_unittest.cc | 731 ------- .../browser/brave_wallet_constants.h | 57 - .../browser/brave_wallet_ipfs_service.cc | 46 - .../browser/brave_wallet_ipfs_service.h | 13 - .../browser/brave_wallet_pin_service.cc | 1025 ---------- .../browser/brave_wallet_pin_service.h | 220 -- .../brave_wallet_pin_service_unittest.cc | 1380 ------------- .../browser/brave_wallet_prefs.cc | 26 +- .../browser/eth_response_parser_unittest.cc | 1 - .../json_rpc_response_parser_unittest.cc | 1 - .../browser/json_rpc_service_unittest.cc | 27 +- .../browser/nft_metadata_fetcher.cc | 17 +- .../browser/nft_metadata_fetcher_unittest.cc | 2 - components/brave_wallet/browser/pref_names.h | 2 - .../brave_wallet/browser/sns_resolver_task.cc | 8 +- components/brave_wallet/browser/test/BUILD.gn | 9 - .../unstoppable_domains_dns_resolve.cc | 7 +- ...nstoppable_domains_dns_resolve_unittest.cc | 6 +- .../brave_wallet/common/brave_wallet.mojom | 121 -- .../brave_wallet/common/common_utils.cc | 4 - components/brave_wallet/common/common_utils.h | 1 - components/brave_wallet/common/features.cc | 9 - components/brave_wallet/common/features.h | 1 - .../common/async/__mocks__/bridge.ts | 9 - .../common/async/base-query-cache.ts | 47 +- .../common/constants/local-storage-keys.ts | 4 +- .../brave_wallet_ui/common/constants/mocks.ts | 9 - .../brave_wallet_ui/common/hooks/nft-pin.ts | 106 - .../common/selectors/wallet-selectors.ts | 2 - .../common/slices/api-base.slice.ts | 1 - .../common/slices/api.slice.ts | 10 - .../common/slices/endpoints/nfts.endpoints.ts | 314 +-- .../common/slices/wallet.slice.ts | 3 - .../common/wallet_api_proxy.ts | 18 - .../common/wallet_api_proxy_observers.ts | 36 - .../info-tooltip/info-tooltip.style.ts | 49 - .../components/info-tooltip/info-tooltip.tsx | 27 - .../components/nft-list/nft-list.styles.ts | 55 - .../components/nft-list/nft-list.tsx | 85 - .../desktop/inspect-nfts/inspect-nfts.tsx | 138 -- .../inspect-nfts/inspects-nfts.styles.ts | 2 +- .../local-ipfs-node/local-ipfs-node.styles.ts | 227 --- .../local-ipfs-node/local-ipfs-node.tsx | 125 -- .../nft-ipfs-banner/nft-ipfs-banner.style.ts | 93 - .../nft-ipfs-banner/nft-ipfs-banner.tsx | 106 - .../nft-pinning-status-animation.style.ts | 60 - .../nft-pinning-status-animation.tsx | 82 - .../error-tooltip/error-tooltip.tsx | 32 - .../nft-pinning-status/nft-pinning-status.tsx | 75 - .../components/desktop/views/crypto/index.tsx | 72 +- .../desktop/views/nfts/components/nfts.tsx | 30 +- .../ipfs-node-status.style.ts | 36 - .../ipfs-node-status/ipfs-node-status.tsx | 31 - .../nft-grid-view/nft-grid-view-item.tsx | 9 +- .../create_placeholder_icon.test.tsx | 53 - .../shared/create-placeholder-icon/index.tsx | 21 +- components/brave_wallet_ui/constants/types.ts | 6 - .../nft-details/nft-screen.styles.ts | 16 - .../nft/components/nft-details/nft-screen.tsx | 122 -- .../page/reducers/page_reducer.ts | 9 - .../page/selectors/page-selectors.ts | 1 - components/brave_wallet_ui/page/store.ts | 6 - .../page/wallet_page_api_proxy.ts | 2 - components/brave_wallet_ui/panel/store.ts | 6 - .../panel/wallet_panel_api_proxy.ts | 2 - components/brave_wallet_ui/stories/locale.ts | 52 - .../stories/mock-data/mock-page-state.ts | 1 - .../stories/mock-data/mock-wallet-state.ts | 1 - .../stories/wallet-components.tsx | 78 - .../brave_wallet_ui/utils/routes-utils.ts | 4 +- components/child_process_monitor/BUILD.gn | 6 +- components/constants/BUILD.gn | 5 +- components/constants/pref_names.h | 1 - components/constants/webui_url_constants.h | 5 - components/decentralized_dns/core/BUILD.gn | 1 + .../definitions/chrome_brave_wallet.d.ts | 3 - components/definitions/chrome_ipfs.d.ts | 3 - components/ipfs/BUILD.gn | 87 +- components/ipfs/DEPS | 13 +- components/ipfs/addresses_config.cc | 13 - components/ipfs/addresses_config.h | 25 - components/ipfs/blob_context_getter_factory.h | 41 - components/ipfs/brave_ipfs_client_updater.cc | 152 -- components/ipfs/brave_ipfs_client_updater.h | 162 -- components/ipfs/buildflags/BUILD.gn | 16 - components/ipfs/buildflags/buildflags.gni | 16 - components/ipfs/features.cc | 22 - components/ipfs/features.h | 19 - components/ipfs/import/imported_data.cc | 13 - components/ipfs/import/imported_data.h | 43 - .../ipfs/import/ipfs_import_worker_base.cc | 301 --- .../ipfs/import/ipfs_import_worker_base.h | 102 - .../ipfs/import/ipfs_link_import_worker.cc | 101 - .../ipfs/import/ipfs_link_import_worker.h | 52 - components/ipfs/ipfs_component_cleaner.cc | 60 + components/ipfs/ipfs_component_cleaner.h | 20 + components/ipfs/ipfs_constants.h | 68 - components/ipfs/ipfs_cookie_store_unittest.cc | 82 - components/ipfs/ipfs_dns_resolver.cc | 25 - components/ipfs/ipfs_dns_resolver.h | 40 - .../ipfs_interstitial_controller_client.cc | 59 - .../ipfs_interstitial_controller_client.h | 51 - components/ipfs/ipfs_json_parser.cc | 605 ------ components/ipfs/ipfs_json_parser.h | 66 - components/ipfs/ipfs_json_parser_unittest.cc | 565 ------ components/ipfs/ipfs_navigation_throttle.cc | 282 --- components/ipfs/ipfs_navigation_throttle.h | 80 - components/ipfs/ipfs_network_utils.cc | 339 ---- components/ipfs/ipfs_network_utils.h | 80 - .../ipfs/ipfs_node_traffic_recognizer.cc | 52 - .../ipfs/ipfs_node_traffic_recognizer.h | 20 - .../ipfs_node_traffic_recognizer_unittest.cc | 54 - components/ipfs/ipfs_not_connected_page.cc | 92 - components/ipfs/ipfs_not_connected_page.h | 66 - components/ipfs/ipfs_onboarding_page.cc | 283 --- components/ipfs/ipfs_onboarding_page.h | 124 -- components/ipfs/ipfs_p3a.cc | 155 -- components/ipfs/ipfs_p3a.h | 65 - components/ipfs/ipfs_p3a_unittest.cc | 124 -- components/ipfs/ipfs_ports.cc | 34 - components/ipfs/ipfs_ports.h | 21 - components/ipfs/ipfs_ports_unittest.cc | 35 - .../ipfs/{pref_names.h => ipfs_prefs.cc} | 76 +- components/ipfs/ipfs_prefs.h | 20 + components/ipfs/ipfs_service.cc | 1217 ----------- components/ipfs/ipfs_service.h | 301 --- components/ipfs/ipfs_service_delegate.h | 21 - components/ipfs/ipfs_service_observer.h | 32 - components/ipfs/ipfs_tab_helper_delegate.h | 24 - components/ipfs/ipfs_utils.cc | 499 +---- components/ipfs/ipfs_utils.h | 66 +- components/ipfs/ipfs_utils_unittest.cc | 895 ++------- components/ipfs/keys/ipns_keys_manager.cc | 319 --- components/ipfs/keys/ipns_keys_manager.h | 115 -- .../ipfs/keys/ipns_keys_manager_unittest.cc | 98 - components/ipfs/node_info.cc | 13 - components/ipfs/node_info.h | 24 - components/ipfs/pin/ipfs_base_pin_service.cc | 139 -- components/ipfs/pin/ipfs_base_pin_service.h | 73 - .../pin/ipfs_base_pin_service_unittest.cc | 182 -- components/ipfs/pin/ipfs_local_pin_service.cc | 468 ----- components/ipfs/pin/ipfs_local_pin_service.h | 211 -- .../pin/ipfs_local_pin_service_unittest.cc | 627 ------ components/ipfs/pin/ipfs_pin_rpc_types.cc | 18 - components/ipfs/pin/ipfs_pin_rpc_types.h | 31 - components/ipfs/repo_stats.cc | 13 - components/ipfs/repo_stats.h | 28 - components/ipfs/resources/BUILD.gn | 53 - .../ipfs/resources/interstitial_ipfs.css | 14 - .../ipfs/resources/ipfs_interstitial.html | 34 - .../ipfs/resources/ipfs_interstitial.js | 36 - .../onboarding/assets/background.svg | 19 - .../onboarding/assets/brave-ipfs.svg | 1 - .../resources/onboarding/assets/error.svg | 3 - .../resources/onboarding/assets/retry.svg | 3 - .../resources/onboarding/ipfs_onboarding.css | 161 -- .../resources/onboarding/ipfs_onboarding.html | 69 - .../resources/onboarding/ipfs_onboarding.js | 118 -- .../onboarding/ipfs_onboarding.test.js | 49 - components/ipfs/service_sandbox_type.h | 24 - components/ipfs/test/BUILD.gn | 52 +- components/ipfs_ui/BUILD.gn | 23 - components/ipfs_ui/actions/ipfs_actions.ts | 63 - .../ipfs_ui/components/addressesConfig.tsx | 39 - components/ipfs_ui/components/app.tsx | 125 -- .../ipfs_ui/components/connectedPeers.tsx | 41 - .../ipfs_ui/components/daemonStatus.tsx | 70 - components/ipfs_ui/components/nodeInfo.tsx | 41 - components/ipfs_ui/components/repoStats.tsx | 60 - .../ipfs_ui/components/uninstalledView.tsx | 70 - components/ipfs_ui/constants/ipfs_types.ts | 26 - components/ipfs_ui/ipfs.html | 18 - components/ipfs_ui/ipfs.tsx | 110 - components/ipfs_ui/reducers/index.ts | 13 - components/ipfs_ui/reducers/ipfs_reducer.ts | 156 -- components/ipfs_ui/storage.ts | 80 - components/ipfs_ui/store.ts | 11 - components/ipfs_ui/style.ts | 55 - components/p3a/metric_names.h | 7 - components/page_info/BUILD.gn | 15 - components/resources/BUILD.gn | 13 - .../resources/brave_components_resources.grd | 1 - .../resources/brave_components_strings.grd | 14 - components/resources/ipfs_resources.grdp | 14 - components/resources/ipfs_strings.grdp | 168 -- components/resources/wallet_strings.grdp | 29 - components/services/ipfs/BUILD.gn | 20 - components/services/ipfs/DEPS | 3 - components/services/ipfs/ipfs_service_impl.cc | 209 -- components/services/ipfs/ipfs_service_impl.h | 49 - .../ipfs/ipfs_service_impl_android.cc | 33 - .../services/ipfs/ipfs_service_utils.cc | 124 -- components/services/ipfs/ipfs_service_utils.h | 27 - .../ipfs/ipfs_service_utils_unittest.cc | 240 --- .../services/ipfs/public/mojom/BUILD.gn | 10 - .../ipfs/public/mojom/ipfs_service.mojom | 25 - components/services/ipfs/test/BUILD.gn | 23 - components/vector_icons/BUILD.gn | 1 - components/webui/BUILD.gn | 1 - components/webui/webui_resources.cc | 34 - .../App/iOS/Delegates/AppState.swift | 1 - .../App/iOS/Supporting Files/Info.plist | 2 - ios/brave-ios/Package.swift | 4 - .../Interstitial Pages/Images/BraveIPFS.svg | 1 - .../Images/IPFSBackground.svg | 19 - .../Pages/IPFSPreference.html | 55 - .../Styles/IPFSPreference.css | 137 -- .../BVC+IPFSScheme.swift | 37 - .../BVC+ToolbarDelegate.swift | 73 +- .../BVC+WKNavigationDelegate.swift | 17 +- .../BVC+Web3NameService.swift | 6 +- .../BrowserViewController.swift | 27 - .../Browser/Handlers/IPFSSchemeHandler.swift | 53 - .../Browser/Helpers/ErrorPageHelper.swift | 1 - .../IPFSErrorPageHandler.swift | 57 - .../Frontend/Browser/NavigationRouter.swift | 3 +- .../Sources/Brave/Frontend/Browser/Tab.swift | 7 +- .../Internal/Web3IPFSScriptHandler.swift | 49 - .../Settings/IPFSCustomGatewayView.swift | 150 -- .../Settings/Web3SettingsView.swift | 68 - .../Sources/BraveWallet/WalletConstants.swift | 6 - .../BraveWallet/WalletPreferences.swift | 26 - .../Sources/BraveWallet/WalletStrings.swift | 122 -- ios/browser/api/features/BUILD.gn | 2 - ios/browser/api/features/features.h | 2 - ios/browser/api/features/features.mm | 11 - ios/browser/api/ipfs/ipfs_api+private.h | 3 - ios/browser/api/ipfs/ipfs_api.h | 3 - ios/browser/api/ipfs/ipfs_api.mm | 33 +- ios/browser/flags/BUILD.gn | 1 - ios/browser/flags/about_flags.mm | 24 - patches/base-win-default_apps_util.cc.patch | 12 - ...browser-resources-settings-router.ts.patch | 2 +- ...s-location_bar-location_icon_view.cc.patch | 12 - ...taller-linux-common-desktop.template.patch | 2 +- .../chrome-installer-util-shell_util.cc.patch | 11 - ...error_page-common-localized_error.cc.patch | 12 - patches/components-page_info-BUILD.gn.patch | 12 - resources/resource_ids.spec | 5 - test/BUILD.gn | 17 - test/base/testing_brave_browser_process.cc | 11 - test/base/testing_brave_browser_process.h | 3 - .../ipfs-client-updater-linux.pem | 28 - .../go-ipfs_v0.4.17_linux-amd64 | 0 .../ipfs-client-updater-linux/manifest.json | 7 - .../ipfs-client-updater-mac.pem | 28 - .../go-ipfs_v0.6.0_darwin-amd64 | 0 .../ipfs-client-updater-mac/manifest.json | 7 - .../ipfs-client-updater-win.pem | 28 - .../go-ipfs_v0.4.17_windows-amd64 | 0 .../ipfs-client-updater-win/manifest.json | 7 - test/data/ipfs_cookie_iframe.html | 5 - utility/brave_content_utility_client.cc | 16 - utility/importer/sources.gni | 5 - utility/sources.gni | 9 - 480 files changed, 597 insertions(+), 38342 deletions(-) delete mode 100644 android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettingsIPFSUtils.java delete mode 100644 app/vector_icons/open_in_ipfs.icon delete mode 100644 browser/brave_wallet/brave_wallet_auto_pin_service_factory.cc delete mode 100644 browser/brave_wallet/brave_wallet_auto_pin_service_factory.h delete mode 100644 browser/brave_wallet/brave_wallet_pin_service_factory.cc delete mode 100644 browser/brave_wallet/brave_wallet_pin_service_factory.h delete mode 100644 browser/extensions/api/ipfs_api.cc delete mode 100644 browser/extensions/api/ipfs_api.h delete mode 100644 browser/extensions/api/ipfs_apitest.cc delete mode 100644 browser/infobars/brave_global_confirm_infobar_delegate.cc delete mode 100644 browser/infobars/brave_global_confirm_infobar_delegate.h delete mode 100644 browser/infobars/brave_global_infobar_service.cc delete mode 100644 browser/infobars/brave_global_infobar_service.h delete mode 100644 browser/infobars/brave_global_infobar_service_factory.cc delete mode 100644 browser/infobars/brave_global_infobar_service_factory.h delete mode 100644 browser/infobars/brave_ipfs_always_start_infobar_delegate.cc delete mode 100644 browser/infobars/brave_ipfs_always_start_infobar_delegate.h delete mode 100644 browser/infobars/brave_ipfs_fallback_infobar_delegate.cc delete mode 100644 browser/infobars/brave_ipfs_fallback_infobar_delegate.h delete mode 100644 browser/infobars/brave_ipfs_infobar_delegate.cc delete mode 100644 browser/infobars/brave_ipfs_infobar_delegate.h delete mode 100644 browser/ipfs/content_browser_client_helper.cc delete mode 100644 browser/ipfs/content_browser_client_helper.h delete mode 100644 browser/ipfs/content_browser_client_helper_unittest.cc delete mode 100644 browser/ipfs/import/ipfs_import_controller.cc delete mode 100644 browser/ipfs/import/ipfs_import_controller.h delete mode 100644 browser/ipfs/import/ipfs_import_controller_browsertest.cc delete mode 100644 browser/ipfs/import/save_package_observer.cc delete mode 100644 browser/ipfs/import/save_package_observer.h delete mode 100644 browser/ipfs/import/save_package_observer_browsertest.cc delete mode 100644 browser/ipfs/ipfs_blob_context_getter_factory.cc delete mode 100644 browser/ipfs/ipfs_blob_context_getter_factory.h delete mode 100644 browser/ipfs/ipfs_blob_context_getter_factory_unittest.cc delete mode 100644 browser/ipfs/ipfs_dns_resolver_impl.cc delete mode 100644 browser/ipfs/ipfs_dns_resolver_impl.h delete mode 100644 browser/ipfs/ipfs_host_resolver.cc delete mode 100644 browser/ipfs/ipfs_host_resolver.h delete mode 100644 browser/ipfs/ipfs_host_resolver_unittest.cc delete mode 100644 browser/ipfs/ipfs_local_pin_service_factory.cc delete mode 100644 browser/ipfs/ipfs_local_pin_service_factory.h delete mode 100644 browser/ipfs/ipfs_policy_browsertest.cc delete mode 100644 browser/ipfs/ipfs_service_factory.cc delete mode 100644 browser/ipfs/ipfs_service_factory.h delete mode 100644 browser/ipfs/ipfs_service_impl_delegate.cc delete mode 100644 browser/ipfs/ipfs_service_impl_delegate.h delete mode 100644 browser/ipfs/ipfs_subframe_navigation_throttle.cc delete mode 100644 browser/ipfs/ipfs_subframe_navigation_throttle.h delete mode 100644 browser/ipfs/ipfs_tab_helper.cc delete mode 100644 browser/ipfs/ipfs_tab_helper.h delete mode 100644 browser/ipfs/ipfs_tab_helper_browsertest.cc delete mode 100644 browser/ipfs/ipfs_tab_helper_unittest.cc delete mode 100644 browser/ipfs/sources.gni delete mode 100644 browser/ipfs/test/BUILD.gn delete mode 100644 browser/ipfs/test/brave_ipfs_client_updater_browsertest.cc delete mode 100644 browser/ipfs/test/ipfs_dns_resolver_impl_unittest.cc delete mode 100644 browser/ipfs/test/ipfs_navigation_throttle_browsertest.cc delete mode 100644 browser/ipfs/test/ipfs_navigation_throttle_unittest.cc delete mode 100644 browser/ipfs/test/ipfs_network_utils_unittest.cc delete mode 100644 browser/ipfs/test/ipfs_not_connected_page_browsertest.cc delete mode 100644 browser/ipfs/test/ipfs_onboarding_page_browsertest.cc delete mode 100644 browser/ipfs/test/ipfs_service_browsertest.cc delete mode 100644 browser/ipfs/test/ipns_keys_manager_browsertest.cc delete mode 100644 browser/net/ipfs_redirect_network_delegate_helper.cc delete mode 100644 browser/net/ipfs_redirect_network_delegate_helper.h delete mode 100644 browser/net/ipfs_redirect_network_delegate_helper_browsertest.cc delete mode 100644 browser/net/ipfs_redirect_network_delegate_helper_unittest.cc delete mode 100644 browser/resources/settings/brave_ipfs_page/add_ipfs_peer_dialog.html delete mode 100644 browser/resources/settings/brave_ipfs_page/add_ipfs_peer_dialog.ts delete mode 100644 browser/resources/settings/brave_ipfs_page/add_p2p_key_dialog.html delete mode 100644 browser/resources/settings/brave_ipfs_page/add_p2p_key_dialog.ts delete mode 100644 browser/resources/settings/brave_ipfs_page/brave_ipfs_browser_proxy.ts delete mode 100644 browser/resources/settings/brave_ipfs_page/brave_ipfs_page.html delete mode 100644 browser/resources/settings/brave_ipfs_page/brave_ipfs_page.ts delete mode 100644 browser/resources/settings/brave_ipfs_page/change_ipfs_gateway_dialog.html delete mode 100644 browser/resources/settings/brave_ipfs_page/change_ipfs_gateway_dialog.ts delete mode 100644 browser/resources/settings/brave_ipfs_page/ipfs_peers_subpage.html delete mode 100644 browser/resources/settings/brave_ipfs_page/ipfs_peers_subpage.ts delete mode 100644 browser/resources/settings/brave_ipfs_page/p2p_keys_subpage.html delete mode 100644 browser/resources/settings/brave_ipfs_page/p2p_keys_subpage.ts delete mode 100644 browser/resources/settings/brave_ipfs_page/rotate_p2p_key_dialog.html delete mode 100644 browser/resources/settings/brave_ipfs_page/rotate_p2p_key_dialog.ts delete mode 100644 browser/ui/views/infobars/brave_global_infobar_manager.cc delete mode 100644 browser/ui/views/infobars/brave_global_infobar_manager.h delete mode 100644 browser/ui/views/location_bar/ipfs_location_view.cc delete mode 100644 browser/ui/views/location_bar/ipfs_location_view.h delete mode 100644 browser/ui/webui/ipfs_dom_handler_unittest.cc delete mode 100644 browser/ui/webui/ipfs_ui.cc delete mode 100644 browser/ui/webui/ipfs_ui.h delete mode 100644 chromium_src/base/win/default_apps_util.cc delete mode 100644 chromium_src/chrome/browser/extensions/extension_util.cc delete mode 100644 chromium_src/chrome/browser/ui/page_info/chrome_page_info_ui_delegate.cc delete mode 100644 chromium_src/chrome/browser/ui/page_info/chrome_page_info_ui_delegate.h delete mode 100644 chromium_src/chrome/browser/ui/views/page_info/page_info_main_view.cc delete mode 100644 chromium_src/chrome/browser/ui/views/page_info/page_info_view_factory.h delete mode 100644 chromium_src/chrome/common/extensions/permissions/chrome_api_permissions.cc delete mode 100644 chromium_src/chrome/common/extensions/permissions/chrome_permission_message_rules.cc delete mode 100644 chromium_src/components/page_info/page_info_ui.cc delete mode 100644 chromium_src/components/page_info/page_info_ui.h delete mode 100644 chromium_src/services/network/public/cpp/url_util.cc delete mode 100644 common/extensions/api/_ipfs_api_features.json delete mode 100644 common/extensions/api/_ipfs_permission_features.json delete mode 100644 common/extensions/api/ipfs.json delete mode 100644 components/brave_wallet/browser/brave_wallet_auto_pin_service.cc delete mode 100644 components/brave_wallet/browser/brave_wallet_auto_pin_service.h delete mode 100644 components/brave_wallet/browser/brave_wallet_auto_pin_service_unittest.cc delete mode 100644 components/brave_wallet/browser/brave_wallet_pin_service.cc delete mode 100644 components/brave_wallet/browser/brave_wallet_pin_service.h delete mode 100644 components/brave_wallet/browser/brave_wallet_pin_service_unittest.cc delete mode 100644 components/brave_wallet_ui/common/hooks/nft-pin.ts delete mode 100644 components/brave_wallet_ui/components/desktop/inspect-nfts/components/info-tooltip/info-tooltip.style.ts delete mode 100644 components/brave_wallet_ui/components/desktop/inspect-nfts/components/info-tooltip/info-tooltip.tsx delete mode 100644 components/brave_wallet_ui/components/desktop/inspect-nfts/components/nft-list/nft-list.styles.ts delete mode 100644 components/brave_wallet_ui/components/desktop/inspect-nfts/components/nft-list/nft-list.tsx delete mode 100644 components/brave_wallet_ui/components/desktop/inspect-nfts/inspect-nfts.tsx delete mode 100644 components/brave_wallet_ui/components/desktop/local-ipfs-node/local-ipfs-node.styles.ts delete mode 100644 components/brave_wallet_ui/components/desktop/local-ipfs-node/local-ipfs-node.tsx delete mode 100644 components/brave_wallet_ui/components/desktop/nft-ipfs-banner/nft-ipfs-banner.style.ts delete mode 100644 components/brave_wallet_ui/components/desktop/nft-ipfs-banner/nft-ipfs-banner.tsx delete mode 100644 components/brave_wallet_ui/components/desktop/nft-pinning-status-animation/nft-pinning-status-animation.style.ts delete mode 100644 components/brave_wallet_ui/components/desktop/nft-pinning-status-animation/nft-pinning-status-animation.tsx delete mode 100644 components/brave_wallet_ui/components/desktop/nft-pinning-status/components/error-tooltip/error-tooltip.tsx delete mode 100644 components/brave_wallet_ui/components/desktop/nft-pinning-status/nft-pinning-status.tsx delete mode 100644 components/brave_wallet_ui/components/desktop/views/portfolio/components/ipfs-node-status/ipfs-node-status.style.ts delete mode 100644 components/brave_wallet_ui/components/desktop/views/portfolio/components/ipfs-node-status/ipfs-node-status.tsx delete mode 100644 components/brave_wallet_ui/components/shared/create-placeholder-icon/create_placeholder_icon.test.tsx delete mode 100644 components/definitions/chrome_ipfs.d.ts delete mode 100644 components/ipfs/addresses_config.cc delete mode 100644 components/ipfs/addresses_config.h delete mode 100644 components/ipfs/blob_context_getter_factory.h delete mode 100644 components/ipfs/brave_ipfs_client_updater.cc delete mode 100644 components/ipfs/brave_ipfs_client_updater.h delete mode 100644 components/ipfs/buildflags/BUILD.gn delete mode 100644 components/ipfs/buildflags/buildflags.gni delete mode 100644 components/ipfs/features.cc delete mode 100644 components/ipfs/features.h delete mode 100644 components/ipfs/import/imported_data.cc delete mode 100644 components/ipfs/import/imported_data.h delete mode 100644 components/ipfs/import/ipfs_import_worker_base.cc delete mode 100644 components/ipfs/import/ipfs_import_worker_base.h delete mode 100644 components/ipfs/import/ipfs_link_import_worker.cc delete mode 100644 components/ipfs/import/ipfs_link_import_worker.h create mode 100644 components/ipfs/ipfs_component_cleaner.cc create mode 100644 components/ipfs/ipfs_component_cleaner.h delete mode 100644 components/ipfs/ipfs_constants.h delete mode 100644 components/ipfs/ipfs_cookie_store_unittest.cc delete mode 100644 components/ipfs/ipfs_dns_resolver.cc delete mode 100644 components/ipfs/ipfs_dns_resolver.h delete mode 100644 components/ipfs/ipfs_interstitial_controller_client.cc delete mode 100644 components/ipfs/ipfs_interstitial_controller_client.h delete mode 100644 components/ipfs/ipfs_json_parser.cc delete mode 100644 components/ipfs/ipfs_json_parser.h delete mode 100644 components/ipfs/ipfs_json_parser_unittest.cc delete mode 100644 components/ipfs/ipfs_navigation_throttle.cc delete mode 100644 components/ipfs/ipfs_navigation_throttle.h delete mode 100644 components/ipfs/ipfs_network_utils.cc delete mode 100644 components/ipfs/ipfs_network_utils.h delete mode 100644 components/ipfs/ipfs_node_traffic_recognizer.cc delete mode 100644 components/ipfs/ipfs_node_traffic_recognizer.h delete mode 100644 components/ipfs/ipfs_node_traffic_recognizer_unittest.cc delete mode 100644 components/ipfs/ipfs_not_connected_page.cc delete mode 100644 components/ipfs/ipfs_not_connected_page.h delete mode 100644 components/ipfs/ipfs_onboarding_page.cc delete mode 100644 components/ipfs/ipfs_onboarding_page.h delete mode 100644 components/ipfs/ipfs_p3a.cc delete mode 100644 components/ipfs/ipfs_p3a.h delete mode 100644 components/ipfs/ipfs_p3a_unittest.cc delete mode 100644 components/ipfs/ipfs_ports.cc delete mode 100644 components/ipfs/ipfs_ports.h delete mode 100644 components/ipfs/ipfs_ports_unittest.cc rename components/ipfs/{pref_names.h => ipfs_prefs.cc} (50%) create mode 100644 components/ipfs/ipfs_prefs.h delete mode 100644 components/ipfs/ipfs_service.cc delete mode 100644 components/ipfs/ipfs_service.h delete mode 100644 components/ipfs/ipfs_service_delegate.h delete mode 100644 components/ipfs/ipfs_service_observer.h delete mode 100644 components/ipfs/ipfs_tab_helper_delegate.h delete mode 100644 components/ipfs/keys/ipns_keys_manager.cc delete mode 100644 components/ipfs/keys/ipns_keys_manager.h delete mode 100644 components/ipfs/keys/ipns_keys_manager_unittest.cc delete mode 100644 components/ipfs/node_info.cc delete mode 100644 components/ipfs/node_info.h delete mode 100644 components/ipfs/pin/ipfs_base_pin_service.cc delete mode 100644 components/ipfs/pin/ipfs_base_pin_service.h delete mode 100644 components/ipfs/pin/ipfs_base_pin_service_unittest.cc delete mode 100644 components/ipfs/pin/ipfs_local_pin_service.cc delete mode 100644 components/ipfs/pin/ipfs_local_pin_service.h delete mode 100644 components/ipfs/pin/ipfs_local_pin_service_unittest.cc delete mode 100644 components/ipfs/pin/ipfs_pin_rpc_types.cc delete mode 100644 components/ipfs/pin/ipfs_pin_rpc_types.h delete mode 100644 components/ipfs/repo_stats.cc delete mode 100644 components/ipfs/repo_stats.h delete mode 100644 components/ipfs/resources/BUILD.gn delete mode 100644 components/ipfs/resources/interstitial_ipfs.css delete mode 100644 components/ipfs/resources/ipfs_interstitial.html delete mode 100644 components/ipfs/resources/ipfs_interstitial.js delete mode 100644 components/ipfs/resources/onboarding/assets/background.svg delete mode 100644 components/ipfs/resources/onboarding/assets/brave-ipfs.svg delete mode 100644 components/ipfs/resources/onboarding/assets/error.svg delete mode 100644 components/ipfs/resources/onboarding/assets/retry.svg delete mode 100644 components/ipfs/resources/onboarding/ipfs_onboarding.css delete mode 100644 components/ipfs/resources/onboarding/ipfs_onboarding.html delete mode 100644 components/ipfs/resources/onboarding/ipfs_onboarding.js delete mode 100644 components/ipfs/resources/onboarding/ipfs_onboarding.test.js delete mode 100644 components/ipfs/service_sandbox_type.h delete mode 100644 components/ipfs_ui/BUILD.gn delete mode 100644 components/ipfs_ui/actions/ipfs_actions.ts delete mode 100644 components/ipfs_ui/components/addressesConfig.tsx delete mode 100644 components/ipfs_ui/components/app.tsx delete mode 100644 components/ipfs_ui/components/connectedPeers.tsx delete mode 100644 components/ipfs_ui/components/daemonStatus.tsx delete mode 100644 components/ipfs_ui/components/nodeInfo.tsx delete mode 100644 components/ipfs_ui/components/repoStats.tsx delete mode 100644 components/ipfs_ui/components/uninstalledView.tsx delete mode 100644 components/ipfs_ui/constants/ipfs_types.ts delete mode 100644 components/ipfs_ui/ipfs.html delete mode 100644 components/ipfs_ui/ipfs.tsx delete mode 100644 components/ipfs_ui/reducers/index.ts delete mode 100644 components/ipfs_ui/reducers/ipfs_reducer.ts delete mode 100644 components/ipfs_ui/storage.ts delete mode 100644 components/ipfs_ui/store.ts delete mode 100644 components/ipfs_ui/style.ts delete mode 100644 components/page_info/BUILD.gn delete mode 100644 components/resources/ipfs_resources.grdp delete mode 100644 components/resources/ipfs_strings.grdp delete mode 100644 components/services/ipfs/BUILD.gn delete mode 100644 components/services/ipfs/DEPS delete mode 100644 components/services/ipfs/ipfs_service_impl.cc delete mode 100644 components/services/ipfs/ipfs_service_impl.h delete mode 100644 components/services/ipfs/ipfs_service_impl_android.cc delete mode 100644 components/services/ipfs/ipfs_service_utils.cc delete mode 100644 components/services/ipfs/ipfs_service_utils.h delete mode 100644 components/services/ipfs/ipfs_service_utils_unittest.cc delete mode 100644 components/services/ipfs/public/mojom/BUILD.gn delete mode 100644 components/services/ipfs/public/mojom/ipfs_service.mojom delete mode 100644 components/services/ipfs/test/BUILD.gn delete mode 100644 ios/brave-ios/Sources/Brave/Assets/Interstitial Pages/Images/BraveIPFS.svg delete mode 100644 ios/brave-ios/Sources/Brave/Assets/Interstitial Pages/Images/IPFSBackground.svg delete mode 100644 ios/brave-ios/Sources/Brave/Assets/Interstitial Pages/Pages/IPFSPreference.html delete mode 100644 ios/brave-ios/Sources/Brave/Assets/Interstitial Pages/Styles/IPFSPreference.css delete mode 100644 ios/brave-ios/Sources/Brave/Frontend/Browser/BrowserViewController/BVC+IPFSScheme.swift delete mode 100644 ios/brave-ios/Sources/Brave/Frontend/Browser/Handlers/IPFSSchemeHandler.swift delete mode 100644 ios/brave-ios/Sources/Brave/Frontend/Browser/Interstitial Pages/IPFSErrorPageHandler.swift delete mode 100644 ios/brave-ios/Sources/Brave/Frontend/UserContent/UserScripts/Scripts_Dynamic/ScriptHandlers/Internal/Web3IPFSScriptHandler.swift delete mode 100644 ios/brave-ios/Sources/BraveWallet/Settings/IPFSCustomGatewayView.swift delete mode 100644 patches/base-win-default_apps_util.cc.patch delete mode 100644 patches/chrome-browser-ui-views-location_bar-location_icon_view.cc.patch delete mode 100644 patches/components-error_page-common-localized_error.cc.patch delete mode 100644 patches/components-page_info-BUILD.gn.patch delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-linux.pem delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-linux/go-ipfs_v0.4.17_linux-amd64 delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-linux/manifest.json delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-mac.pem delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-mac/go-ipfs_v0.6.0_darwin-amd64 delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-mac/manifest.json delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-win.pem delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-win/go-ipfs_v0.4.17_windows-amd64 delete mode 100644 test/data/ipfs-client-updater/ipfs-client-updater-win/manifest.json delete mode 100644 test/data/ipfs_cookie_iframe.html diff --git a/android/BUILD.gn b/android/BUILD.gn index 878875f741bf..117250e02569 100644 --- a/android/BUILD.gn +++ b/android/BUILD.gn @@ -4,7 +4,6 @@ # You can obtain one at https://mozilla.org/MPL/2.0/. import("//brave/components/ai_chat/core/common/buildflags/buildflags.gni") -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//brave/components/p3a/buildflags.gni") import("//brave/components/webcompat_reporter/buildflags/buildflags.gni") import("//build/config/android/rules.gni") @@ -17,7 +16,6 @@ java_cpp_enum("brave_android_java_enums_srcjar") { sources = [ "//brave/chromium_src/chrome/browser/notifications/notification_handler_impl.h", "//brave/components/decentralized_dns/core/constants.h", - "//brave/components/ipfs/ipfs_constants.h", ] } @@ -26,7 +24,6 @@ java_cpp_template("brave_config_java") { defines = [ "BRAVE_ANDROID_DEVELOPER_OPTIONS_CODE=\"$brave_android_developer_options_code\"", "BRAVE_ANDROID_P3A_ENABLED=$brave_p3a_enabled", - "BRAVE_ANDROID_ENABLE_IPFS=$enable_ipfs", "BRAVE_ANDROID_WEBCOMPAT_REPORT_ENDPOINT=\"$webcompat_report_api_endpoint\"", "BRAVE_ANDROID_AI_CHAT_ENABLED=$enable_ai_chat", ] diff --git a/android/brave_java_sources.gni b/android/brave_java_sources.gni index 57b9ecd4c7cf..b4faced46ee7 100644 --- a/android/brave_java_sources.gni +++ b/android/brave_java_sources.gni @@ -303,7 +303,6 @@ brave_java_sources = [ "../../brave/android/java/org/chromium/chrome/browser/preferences/website/BraveShieldsContentSettingsObserver.java", "../../brave/android/java/org/chromium/chrome/browser/privacy/secure_dns/BraveSecureDnsProviderPreference.java", "../../brave/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettings.java", - "../../brave/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettingsIPFSUtils.java", "../../brave/android/java/org/chromium/chrome/browser/profiles/ProfileUtils.java", "../../brave/android/java/org/chromium/chrome/browser/qrreader/BarcodeTracker.java", "../../brave/android/java/org/chromium/chrome/browser/qrreader/BarcodeTrackerFactory.java", diff --git a/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettings.java b/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettings.java index 5223584d7081..322a5e7c0007 100644 --- a/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettings.java +++ b/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettings.java @@ -76,7 +76,6 @@ public class BravePrivacySettings extends PrivacySettings implements ConnectionE private static final String PREF_DE_AMP = "de_amp"; private static final String PREF_DEBOUNCE = "debounce"; - private static final String PREF_IPFS_GATEWAY = "ipfs_gateway"; private static final String PREF_BLOCK_COOKIE_CONSENT_NOTICES = "block_cookie_consent_notices"; private static final String PREF_BLOCK_SWITCH_TO_APP_NOTICES = "block_switch_to_app_notices"; private static final String PREF_AD_BLOCK = "ad_block"; @@ -143,7 +142,6 @@ public class BravePrivacySettings extends PrivacySettings implements ConnectionE PREF_ENS, PREF_SNS, PREF_REQUEST_OTR, - PREF_IPFS_GATEWAY, PREF_SECURE_DNS, PREF_BLOCK_COOKIE_CONSENT_NOTICES, PREF_BLOCK_SWITCH_TO_APP_NOTICES, @@ -181,7 +179,6 @@ public class BravePrivacySettings extends PrivacySettings implements ConnectionE private ChromeSwitchPreference mSendP3A; private ChromeSwitchPreference mSendCrashReports; private ChromeSwitchPreference mBraveStatsUsagePing; - private ChromeSwitchPreference mIpfsGatewayPref; private ChromeSwitchPreference mBlockCookieConsentNoticesPref; private ChromeSwitchPreference mBlockSwitchToAppNoticesPref; private PreferenceCategory mSocialBlockingCategory; @@ -259,9 +256,6 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { mUstoppableDomains = (Preference) findPreference(PREF_UNSTOPPABLE_DOMAINS); mUstoppableDomains.setOnPreferenceChangeListener(this); - mIpfsGatewayPref = (ChromeSwitchPreference) findPreference(PREF_IPFS_GATEWAY); - mIpfsGatewayPref.setOnPreferenceChangeListener(this); - mBlockCookieConsentNoticesPref = (ChromeSwitchPreference) findPreference(PREF_BLOCK_COOKIE_CONSENT_NOTICES); mBlockCookieConsentNoticesPref.setOnPreferenceChangeListener(this); @@ -442,8 +436,6 @@ public boolean onPreferenceChange(Preference preference, Object newValue) { } else if (PREF_DEBOUNCE.equals(key)) { UserPrefs.get(ProfileManager.getLastUsedRegularProfile()) .setBoolean(BravePref.DEBOUNCE_ENABLED, (boolean) newValue); - } else if (PREF_IPFS_GATEWAY.equals(key)) { - BravePrivacySettingsIPFSUtils.setIPFSGatewayPref((boolean) newValue); } else if (PREF_BLOCK_COOKIE_CONSENT_NOTICES.equals(key)) { if (mFilterListAndroidHandler != null) { mFilterListAndroidHandler.enableFilter( @@ -611,9 +603,6 @@ private void updateBravePreferences() { UserPrefs.get(ProfileManager.getLastUsedRegularProfile()) .getBoolean(Pref.HTTPS_ONLY_MODE_ENABLED)); - // IPFS Gateway - mIpfsGatewayPref.setChecked(BravePrivacySettingsIPFSUtils.getIPFSGatewayPref()); - if (blockAdTrackersPref.equals(BraveShieldsContentSettings.BLOCK_RESOURCE)) { mAdsTrakersBlockPref.setCheckedIndex(0); mAdsTrakersBlockPref.setSummary( diff --git a/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettingsIPFSUtils.java b/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettingsIPFSUtils.java deleted file mode 100644 index 85ce4bb70940..000000000000 --- a/android/java/org/chromium/chrome/browser/privacy/settings/BravePrivacySettingsIPFSUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -package org.chromium.chrome.browser.privacy.settings; - -import org.chromium.chrome.browser.BraveConfig; -import org.chromium.chrome.browser.preferences.BravePref; -import org.chromium.chrome.browser.profiles.ProfileManager; -import org.chromium.components.user_prefs.UserPrefs; - -public class BravePrivacySettingsIPFSUtils { - public static void setIPFSGatewayPref(boolean preference) { - if (BraveConfig.IPFS_ENABLED) { - UserPrefs.get(ProfileManager.getLastUsedRegularProfile()) - .setInteger( - BravePref.IPFS_RESOLVE_METHOD, - preference - ? IPFSResolveMethodTypes.IPFS_ASK - : IPFSResolveMethodTypes.IPFS_DISABLED); - } - } - - public static boolean getIPFSGatewayPref() { - if (BraveConfig.IPFS_ENABLED) { - return UserPrefs.get(ProfileManager.getLastUsedRegularProfile()) - .getInteger(BravePref.IPFS_RESOLVE_METHOD) - != IPFSResolveMethodTypes.IPFS_DISABLED; - } else { - return false; - } - } -} diff --git a/android/java/res/xml/brave_privacy_preferences.xml b/android/java/res/xml/brave_privacy_preferences.xml index b931c9f49fba..bcbb84f3883c 100644 --- a/android/java/res/xml/brave_privacy_preferences.xml +++ b/android/java/res/xml/brave_privacy_preferences.xml @@ -135,12 +135,6 @@ app:dialog_subtitle="@string/request_otr_text" app:dialog_entries="@array/requestOTRTexts" app:dialog_default_index="1" /> - $2brave://settings/ext Check details - - - IPFS - - - Publish and retrieve files from IPFS - - - Read and modify IPFS settings - .onion @@ -362,37 +352,8 @@ Or change later at $2brave://settings/ext Force Paste - - Import to IPFS - - - This page - - - Selected image - - - Selected video - - - Selected audio - - - Linked content - - - Publish with IPNS key - - - IPFS - + - - Import Selected Text to IPFS - - - Import and Copy Link to IPFS Snapshot - New Private Window with Tor @@ -402,41 +363,8 @@ Or change later at $2brave://settings/ext Open Link in Brave Private Window with Tor - - Import and Share a File - - - Open Files - - - Import and Share a Directory - - - With a File - - - With a Directory - - - Update IPNS - - - Import selected text to IPFS - - - Import and copy link to IPFS snapshot - - - Import and share a file - - - Open files - - - Update IPNS - New private window with Tor @@ -446,15 +374,6 @@ Or change later at $2brave://settings/ext Open link in Brave private window with Tor - - Import and share a directory - - - With a File - - - With a Directory - @@ -907,55 +826,15 @@ Or change later at $2brave://settings/ext Don't ask again - Wallet - - IPFS - Web3 Web3 Domains - - Learn more about IPFS and privacy - - - This page is available on the IPFS network. Would you like to load IPFS pages using Brave's built-in support (via ipfs:// or ipns://)? - - - Always - - - Only This Time - - - No Thanks - - - Learn how this affects my privacy - - - There was an error loading the IPFS URL. Would you like to redirect to the original URL? - - - Redirect - - - No thanks - - - Would you like to always start an IPFS node on browser startup? - - - Enable - - - Cancel - Brave Wallet Utility Service diff --git a/app/brave_settings_strings.grdp b/app/brave_settings_strings.grdp index 0dbaaa522c53..dffc29fd450a 100644 --- a/app/brave_settings_strings.grdp +++ b/app/brave_settings_strings.grdp @@ -1137,41 +1137,21 @@ Clearing transactions may be useful for developers or when clearing state on a local server - - Automatically pin NFTs - - - NFTs which are added to the Brave Wallet may be automatically pinned to the local IPFS node. - Note: IPFS daemon may be started for the pinning purposes so your local node will share cached data and pinned NFTs to the IPFS network. - Reset and clear wallet data - - Clear pinned NFTs - - - Pinned NFTs are hosted to the IPFS network when local IPFS node is launched. - You have $12 pinned NFTs at the moment. - Are you sure you want to reset all of your wallet transaction and nonce information? This option is mostly used by developers running a local test server. Type "$1Yes" to confirm. Are you sure you want to reset your wallet? If your wallet is not backed up, resetting will cause you to lose all account data (including any associated funds). Type "$1Yes" to confirm. - - Are you sure you want to clear your pinned NFTs? Some of NFTs may be lost forever if there is no other hosters in the IPFS network. Type "$1Yes" to confirm. - Your wallet was reset. Your wallet transaction information was reset. - - Your pinned NFTs were reset. - Yes @@ -1291,158 +1271,6 @@ Do you want to update the existing network? - - - Method to resolve IPFS resources - - - Ask - - - Gateway - - - Brave local IPFS node - - - Disabled - - - <a target="_blank" href="$1">Learn more</a> about Brave local IPFS node and gateway privacy considerations. - - - IPFS public gateway address - - - IPFS public gateway address for NFT - - - Change - - - IPFS public gateway fallback - - - Automatically fall back to public IPFS gateway if your Brave local IPFS node cannot be reached. - - - Always start an IPFS node on browser startup? - - - Automatically redirect requests for IPFS network resources to the configured gateway. - - - Requests for IPFS resources hosted on third-party IPFS gateways or DNSLINK resources will be routed via the selected local or remote gateway. - Note: If local node is selected, resource will be requested directly from your computer and cached data may be provided to the IPFS network for some time. - - - Uses the IPFS Companion extension for enhanced IPFS support in Brave, including access to common IPFS tasks from your browser bar. - - - Maximum IPFS cache size (GB) - - - A soft upper limit for the size of the IPFS repository's datastore. - - - Modify the peers list - - - Add new peer connection string - - - Set up your IPNS keys - - - Sign content by the corresponding private key and publish it to IPNS - - - Keys available for publishing - - - Enter a name for the new key - - - This name cannot be used - - - Rotate key - - - Unable to stop Brave local IPFS node - - - Unable to launch Brave local IPFS node - - - Restart node to apply changes - - - Restart node - - - Rotate - - - /ip4/46.21.210.45/udp/14406/quic/p2p/12D3KooWBdmLJjhpgJ9KZgLM3f894ff9xyBfPvPjFNn7MKJpyrC2 - - - This name is not valid - - - Export key - - - Remove key - - - Set up ipfs peers description - - - Do you really want to delete $1MyCustomPeerId? - - - Do you really want to delete $1MyCustomKey? - - - Node is not launched - - - IPFS service launch error, more information is available on the <a target="_blank" style="text-decoration: underline;" href="chrome://ipfs-internals/">diagnostic page</a> - - - '$1MyCustomKey' key import failed - - - '$1MyCustomKey' key export failed - - - Note: Network requests may not use browser proxy and DNS settings. - - - Import - - - Generate - - - Start node - - - - - Set IPFS gateway - - - Gateway address - - - Invalid gateway address - - - Only a valid IPFS gateway with Origin isolation enabled can be used in Brave - - Cycle through the most recently used tabs with Ctrl-Tab diff --git a/app/generate_command_metadata.py b/app/generate_command_metadata.py index 5f8c3307d9ae..826f54159539 100644 --- a/app/generate_command_metadata.py +++ b/app/generate_command_metadata.py @@ -176,13 +176,6 @@ # Not useful menu commands - mostly these are submenu commands, which do # nothing unless the parent menu is open. - "IDC_APP_MENU_IPFS", - "IDC_APP_MENU_IPFS_PUBLISH_LOCAL_FILE", - "IDC_APP_MENU_IPFS_PUBLISH_LOCAL_FOLDER", - "IDC_APP_MENU_IPFS_SHARE_LOCAL_FILE", - "IDC_APP_MENU_IPFS_SHARE_LOCAL_FOLDER" - "IDC_APP_MENU_IPFS_OPEN_FILES", - "IDC_APP_MENU_IPFS_UPDATE_IPNS", "IDC_SIDEBAR_SHOW_OPTION_MENU", "IDC_BRAVE_BOOKMARK_BAR_SUBMENU", "IDC_SIDEBAR_SHOW_OPTION_ALWAYS", diff --git a/app/theme/BUILD.gn b/app/theme/BUILD.gn index 6da1082be790..cc4056cfd1be 100644 --- a/app/theme/BUILD.gn +++ b/app/theme/BUILD.gn @@ -4,7 +4,6 @@ # You can obtain one at https://mozilla.org/MPL/2.0/. import("//brave/components/brave_player/common/buildflags/buildflags.gni") -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//brave/components/playlist/common/buildflags/buildflags.gni") import("//brave/resources/brave_grit.gni") import("//chrome/common/features.gni") @@ -17,7 +16,6 @@ brave_grit("brave_theme_resources") { defines += [ "enable_ai_chat=$enable_ai_chat", "enable_brave_player=$enable_brave_player", - "enable_ipfs=$enable_ipfs", "enable_playlist_webui=$enable_playlist_webui", ] outputs = [ diff --git a/app/theme/brave_theme_resources.grd b/app/theme/brave_theme_resources.grd index 4d23b7873584..c36118efec1b 100644 --- a/app/theme/brave_theme_resources.grd +++ b/app/theme/brave_theme_resources.grd @@ -55,9 +55,6 @@ - - - diff --git a/app/vector_icons/BUILD.gn b/app/vector_icons/BUILD.gn index c253b8764092..b2bb31d69191 100644 --- a/app/vector_icons/BUILD.gn +++ b/app/vector_icons/BUILD.gn @@ -23,7 +23,6 @@ aggregate_vector_icons("brave_vector_icons") { "brave_tooltips_stopwatch.icon", "brave_translate.icon", "download_unlock.icon", - "open_in_ipfs.icon", "sidebar_toolbar_button.icon", "sidebar_toolbar_button_right.icon", "web_discovery_infobar_close_button.icon", diff --git a/app/vector_icons/open_in_ipfs.icon b/app/vector_icons/open_in_ipfs.icon deleted file mode 100644 index 881a1b94d752..000000000000 --- a/app/vector_icons/open_in_ipfs.icon +++ /dev/null @@ -1,36 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -CANVAS_DIMENSIONS, 12, -MOVE_TO, 6.07f, 1.96f, -H_LINE_TO, 1.01f, -R_V_LINE_TO, 9.08f, -R_H_LINE_TO, 9.1f, -V_LINE_TO, 6, -R_CUBIC_TO, 0, -0.28f, 0.1f, -0.49f, 0.38f, -0.49f, -R_ARC_TO, 0.5f, 0.5f, 0, 0, 1, 0.5f, 0.5f, -V_LINE_TO, 11.5f, -R_ARC_TO, 0.5f, 0.5f, 0, 0, 1, -0.5f, 0.5f, -H_LINE_TO, 0.47f, -CUBIC_TO, 0.19f, 12, 0, 11.82f, 0, 11.54f, -V_LINE_TO, 1.46f, -R_CUBIC_TO, 0, -0.28f, 0.19f, -0.44f, 0.47f, -0.44f, -R_H_LINE_TO, 5.51f, -R_ARC_TO, 0.5f, 0.5f, 0, 0, 1, 0.5f, 0.5f, -R_CUBIC_TO, 0, 0.28f, -0.14f, 0.45f, -0.41f, 0.45f, -CLOSE, -MOVE_TO, 6.5f, 5, -R_CUBIC_TO, 0, -0.13f, 0.05f, -0.26f, 0.15f, -0.35f, -LINE_TO, 10.3f, 0.99f, -LINE_TO, 7.5f, 1, -R_ARC_TO, 0.5f, 0.5f, 0, 0, 1, 0, -1, -R_H_LINE_TO, 4, -ARC_TO, 0.5f, 0.5f, 0, 0, 1, 12, 0.5f, -R_V_LINE_TO, 4, -R_ARC_TO, 0.5f, 0.5f, 0, 0, 1, -0.5f, 0.5f, -R_CUBIC_TO, -0.28f, 0, -0.47f, -0.21f, -0.47f, -0.49f, -R_V_LINE_TO, -2.84f, -R_LINE_TO, -3.68f, 3.68f, -ARC_TO, 0.5f, 0.5f, 0, 0, 1, 6.5f, 5, -CLOSE diff --git a/browser/BUILD.gn b/browser/BUILD.gn index 9f9084d3ba07..c7f7c3946e77 100644 --- a/browser/BUILD.gn +++ b/browser/BUILD.gn @@ -32,7 +32,6 @@ source_set("browser_process") { "//brave/browser/ethereum_remote_client/buildflags", "//brave/components/brave_vpn/common/buildflags", "//brave/components/greaselion/browser/buildflags", - "//brave/components/ipfs/buildflags", "//brave/components/request_otr/common/buildflags", "//brave/components/speedreader/common/buildflags", "//brave/components/tor/buildflags", @@ -51,7 +50,6 @@ group("browser") { # these are layering violation and need to be fixed "//brave/components/brave_rewards/browser:testutil", "//brave/components/brave_rewards/test:brave_rewards_unit_tests", - "//brave/components/ipfs/test:*", ] if (enable_sparkle) { diff --git a/browser/about_flags.cc b/browser/about_flags.cc index c915183a1887..6efc229baef6 100644 --- a/browser/about_flags.cc +++ b/browser/about_flags.cc @@ -31,7 +31,6 @@ #include "brave/components/de_amp/common/features.h" #include "brave/components/debounce/core/common/features.h" #include "brave/components/google_sign_in_permission/features.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/ntp_background_images/browser/features.h" #include "brave/components/playlist/common/buildflags/buildflags.h" #include "brave/components/psst/common/features.h" @@ -67,10 +66,6 @@ #include "brave/components/speedreader/common/features.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/features.h" -#endif - #if BUILDFLAG(ENABLE_PLAYLIST) #include "brave/components/playlist/common/features.h" #endif @@ -206,26 +201,8 @@ FEATURE_VALUE_TYPE(brave_rewards::features::kGeminiFeature), \ })) -#define BRAVE_IPFS_FEATURE_ENTRIES \ - IF_BUILDFLAG(ENABLE_IPFS, \ - EXPAND_FEATURE_ENTRIES({ \ - "brave-ipfs", \ - "Enable IPFS", \ - "Enable native support of IPFS.", \ - kOsDesktop | kOsAndroid, \ - FEATURE_VALUE_TYPE(ipfs::features::kIpfsFeature), \ - })) - #define BRAVE_NATIVE_WALLET_FEATURE_ENTRIES \ EXPAND_FEATURE_ENTRIES( \ - { \ - "enable-nft-pinning", \ - "Enable NFT pinning", \ - "Enable NFT pinning for Brave Wallet", \ - kOsDesktop, \ - FEATURE_VALUE_TYPE( \ - brave_wallet::features::kBraveWalletNftPinningFeature), \ - }, \ { \ "native-brave-wallet", \ "Enable Brave Wallet", \ @@ -1012,7 +989,6 @@ kOsWin | kOsLinux | kOsMac, \ FEATURE_VALUE_TYPE(features::kBraveWebViewRoundedCorners), \ }) \ - BRAVE_IPFS_FEATURE_ENTRIES \ BRAVE_NATIVE_WALLET_FEATURE_ENTRIES \ BRAVE_NEWS_FEATURE_ENTRIES \ CRYPTO_WALLETS_FEATURE_ENTRIES \ diff --git a/browser/android/preferences/BUILD.gn b/browser/android/preferences/BUILD.gn index 17a3651be378..657853af9a8d 100644 --- a/browser/android/preferences/BUILD.gn +++ b/browser/android/preferences/BUILD.gn @@ -45,7 +45,6 @@ java_cpp_strings("java_pref_names_srcjar") { "//brave/components/de_amp/common/pref_names.h", "//brave/components/debounce/core/common/pref_names.h", "//brave/components/decentralized_dns/core/pref_names.h", - "//brave/components/ipfs/pref_names.h", "//brave/components/ntp_background_images/common/pref_names.h", "//brave/components/omnibox/browser/brave_omnibox_prefs.cc", "//brave/components/omnibox/browser/brave_omnibox_prefs.h", diff --git a/browser/android/preferences/brave_pref_service_bridge.cc b/browser/android/preferences/brave_pref_service_bridge.cc index 627c8fa71515..e251714231b5 100644 --- a/browser/android/preferences/brave_pref_service_bridge.cc +++ b/browser/android/preferences/brave_pref_service_bridge.cc @@ -17,7 +17,6 @@ #include "brave/components/constants/pref_names.h" #include "brave/components/de_amp/common/pref_names.h" #include "brave/components/decentralized_dns/core/pref_names.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" @@ -31,11 +30,6 @@ #include "third_party/blink/public/common/peerconnection/webrtc_ip_handling_policy.h" #include "url/gurl.h" -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/pref_names.h" -#endif - using base::android::ConvertUTF8ToJavaString; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; diff --git a/browser/autocomplete/brave_autocomplete_scheme_classifier.cc b/browser/autocomplete/brave_autocomplete_scheme_classifier.cc index f3443bf9de0a..ae61e4f19b9f 100644 --- a/browser/autocomplete/brave_autocomplete_scheme_classifier.cc +++ b/browser/autocomplete/brave_autocomplete_scheme_classifier.cc @@ -9,17 +9,12 @@ #include "base/strings/string_util.h" #include "brave/components/constants/url_constants.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "chrome/browser/profiles/profile.h" #if BUILDFLAG(ENABLE_BRAVE_WEBTORRENT) #include "brave/components/brave_webtorrent/browser/webtorrent_util.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/ipfs_constants.h" -#endif - BraveAutocompleteSchemeClassifier::BraveAutocompleteSchemeClassifier( Profile* profile) : ChromeAutocompleteSchemeClassifier(profile) { @@ -51,13 +46,5 @@ BraveAutocompleteSchemeClassifier::GetInputTypeForScheme( } #endif -#if BUILDFLAG(ENABLE_IPFS) - if (base::IsStringASCII(scheme) && - (base::EqualsCaseInsensitiveASCII(scheme, ipfs::kIPFSScheme) || - base::EqualsCaseInsensitiveASCII(scheme, ipfs::kIPNSScheme))) { - return metrics::OmniboxInputType::URL; - } -#endif - return ChromeAutocompleteSchemeClassifier::GetInputTypeForScheme(scheme); } diff --git a/browser/autocomplete/sources.gni b/browser/autocomplete/sources.gni index d6bc5672f370..ad47566b53ab 100644 --- a/browser/autocomplete/sources.gni +++ b/browser/autocomplete/sources.gni @@ -4,7 +4,6 @@ # You can obtain one at http://mozilla.org/MPL/2.0/. */ import("//brave/components/brave_webtorrent/browser/buildflags/buildflags.gni") -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//extensions/buildflags/buildflags.gni") brave_browser_autocomplete_sources = [ @@ -16,7 +15,6 @@ brave_browser_autocomplete_deps = [ "//base", "//brave/common", "//brave/components/brave_webtorrent/browser/buildflags", - "//brave/components/ipfs/buildflags", "//chrome/browser/profiles:profile", ] @@ -24,7 +22,3 @@ if (enable_extensions && enable_brave_webtorrent) { brave_browser_autocomplete_deps += [ "//brave/components/brave_webtorrent/browser" ] } - -if (enable_ipfs) { - brave_browser_autocomplete_deps += [ "//brave/components/ipfs" ] -} diff --git a/browser/brave_browser_process.h b/browser/brave_browser_process.h index 9edd99ea7b3f..139212996dbf 100644 --- a/browser/brave_browser_process.h +++ b/browser/brave_browser_process.h @@ -13,7 +13,6 @@ #include "brave/components/brave_vpn/common/buildflags/buildflags.h" #include "brave/components/greaselion/browser/buildflags/buildflags.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/request_otr/common/buildflags/buildflags.h" #include "brave/components/speedreader/common/buildflags/buildflags.h" #include "brave/components/tor/buildflags/buildflags.h" @@ -85,10 +84,6 @@ class BraveTorClientUpdater; class BraveTorPluggableTransportUpdater; } // namespace tor -namespace ipfs { -class BraveIpfsClientUpdater; -} - namespace speedreader { class SpeedreaderRewriterService; } @@ -126,9 +121,6 @@ class BraveBrowserProcess { virtual tor::BraveTorClientUpdater* tor_client_updater() = 0; virtual tor::BraveTorPluggableTransportUpdater* tor_pluggable_transport_updater() = 0; -#endif -#if BUILDFLAG(ENABLE_IPFS) - virtual ipfs::BraveIpfsClientUpdater* ipfs_client_updater() = 0; #endif virtual p3a::P3AService* p3a_service() = 0; virtual brave::BraveReferralsService* brave_referrals_service() = 0; diff --git a/browser/brave_browser_process_impl.cc b/browser/brave_browser_process_impl.cc index 478ec01519a9..7aad9612bcc2 100644 --- a/browser/brave_browser_process_impl.cc +++ b/browser/brave_browser_process_impl.cc @@ -72,11 +72,6 @@ #include "brave/components/tor/pref_names.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/brave_ipfs_client_updater.h" -#include "brave/components/ipfs/ipfs_constants.h" -#endif - #if BUILDFLAG(ENABLE_SPEEDREADER) #include "brave/components/speedreader/speedreader_rewriter_service.h" #endif @@ -147,12 +142,6 @@ BraveBrowserProcessImpl::BraveBrowserProcessImpl(StartupData* startup_data) void BraveBrowserProcessImpl::Init() { BrowserProcessImpl::Init(); -#if BUILDFLAG(ENABLE_IPFS) - content::ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme( - ipfs::kIPFSScheme); - content::ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme( - ipfs::kIPNSScheme); -#endif UpdateBraveDarkMode(); pref_change_registrar_.Add( kBraveDarkMode, @@ -486,21 +475,6 @@ BraveBrowserProcessImpl::speedreader_rewriter_service() { } #endif // BUILDFLAG(ENABLE_SPEEDREADER) -#if BUILDFLAG(ENABLE_IPFS) -ipfs::BraveIpfsClientUpdater* BraveBrowserProcessImpl::ipfs_client_updater() { - if (ipfs_client_updater_) { - return ipfs_client_updater_.get(); - } - - base::FilePath user_data_dir; - base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); - - ipfs_client_updater_ = ipfs::BraveIpfsClientUpdaterFactory( - brave_component_updater_delegate(), user_data_dir); - return ipfs_client_updater_.get(); -} -#endif // BUILDFLAG(ENABLE_IPFS) - #if BUILDFLAG(ENABLE_BRAVE_VPN) brave_vpn::BraveVPNConnectionManager* BraveBrowserProcessImpl::brave_vpn_connection_manager() { diff --git a/browser/brave_browser_process_impl.h b/browser/brave_browser_process_impl.h index 4132c81fee91..61f51f5e9baf 100644 --- a/browser/brave_browser_process_impl.h +++ b/browser/brave_browser_process_impl.h @@ -13,7 +13,6 @@ #include "brave/components/brave_component_updater/browser/brave_component.h" #include "brave/components/brave_vpn/common/buildflags/buildflags.h" #include "brave/components/greaselion/browser/buildflags/buildflags.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/speedreader/common/buildflags/buildflags.h" #include "brave/components/tor/brave_tor_pluggable_transport_updater.h" #include "brave/components/tor/buildflags/buildflags.h" @@ -81,10 +80,6 @@ class BraveTorClientUpdater; class BraveTorPluggableTransportUpdater; } // namespace tor -namespace ipfs { -class BraveIpfsClientUpdater; -} - namespace speedreader { class SpeedreaderRewriterService; } @@ -131,9 +126,6 @@ class BraveBrowserProcessImpl : public BraveBrowserProcess, tor::BraveTorClientUpdater* tor_client_updater() override; tor::BraveTorPluggableTransportUpdater* tor_pluggable_transport_updater() override; -#endif -#if BUILDFLAG(ENABLE_IPFS) - ipfs::BraveIpfsClientUpdater* ipfs_client_updater() override; #endif p3a::P3AService* p3a_service() override; brave::BraveReferralsService* brave_referrals_service() override; @@ -207,9 +199,6 @@ class BraveBrowserProcessImpl : public BraveBrowserProcess, std::unique_ptr tor_client_updater_; std::unique_ptr tor_pluggable_transport_updater_; -#endif -#if BUILDFLAG(ENABLE_IPFS) - std::unique_ptr ipfs_client_updater_; #endif scoped_refptr p3a_service_; scoped_refptr histogram_braveizer_; diff --git a/browser/brave_content_browser_client.cc b/browser/brave_content_browser_client.cc index 3c9799b8aedc..d240a254ae78 100644 --- a/browser/brave_content_browser_client.cc +++ b/browser/brave_content_browser_client.cc @@ -72,7 +72,6 @@ #include "brave/components/decentralized_dns/content/decentralized_dns_navigation_throttle.h" #include "brave/components/google_sign_in_permission/google_sign_in_permission_throttle.h" #include "brave/components/google_sign_in_permission/google_sign_in_permission_util.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/playlist/common/buildflags/buildflags.h" #include "brave/components/playlist/common/features.h" #include "brave/components/request_otr/common/buildflags/buildflags.h" @@ -178,14 +177,6 @@ using extensions::ChromeContentBrowserClientExtensionsPart; #include "brave/components/brave_webtorrent/browser/magnet_protocol_handler.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/browser/ipfs/content_browser_client_helper.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/browser/ipfs/ipfs_subframe_navigation_throttle.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_navigation_throttle.h" -#endif - #if BUILDFLAG(ENABLE_TOR) #include "brave/browser/tor/tor_profile_service_factory.h" #include "brave/components/tor/onion_location_navigation_throttle.h" @@ -508,10 +499,6 @@ void BraveContentBrowserClient::BrowserURLHandlerCreated( content::BrowserURLHandler::null_handler()); handler->AddHandlerPair(&webtorrent::HandleTorrentURLRewrite, &webtorrent::HandleTorrentURLReverseRewrite); -#endif -#if BUILDFLAG(ENABLE_IPFS) - handler->AddHandlerPair(&ipfs::HandleIPFSURLRewrite, - &ipfs::HandleIPFSURLReverseRewrite); #endif handler->AddHandlerPair(&HandleURLRewrite, &HandleURLReverseOverrideRewrite); ChromeContentBrowserClient::BrowserURLHandlerCreated(handler); @@ -1207,20 +1194,6 @@ BraveContentBrowserClient::CreateThrottlesForNavigation( } #endif -#if BUILDFLAG(ENABLE_IPFS) - throttles.insert( - throttles.begin(), - ipfs::IpfsSubframeNavigationThrottle::CreateThrottleFor(handle)); - std::unique_ptr ipfs_navigation_throttle = - ipfs::IpfsNavigationThrottle::MaybeCreateThrottleFor( - handle, ipfs::IpfsServiceFactory::GetForContext(context), - user_prefs::UserPrefs::Get(context), - g_browser_process->GetApplicationLocale()); - if (ipfs_navigation_throttle) { - throttles.push_back(std::move(ipfs_navigation_throttle)); - } -#endif - std::unique_ptr decentralized_dns_navigation_throttle = decentralized_dns::DecentralizedDnsNavigationThrottle:: diff --git a/browser/brave_content_browser_client_browsertest.cc b/browser/brave_content_browser_client_browsertest.cc index d9e42b7f8ff4..149d6b5a7e6f 100644 --- a/browser/brave_content_browser_client_browsertest.cc +++ b/browser/brave_content_browser_client_browsertest.cc @@ -188,7 +188,6 @@ IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, CanLoadChromeURL) { IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, CanLoadCustomBravePages) { std::vector pages{ - "ipfs-internals", "rewards", }; diff --git a/browser/brave_prefs_browsertest.cc b/browser/brave_prefs_browsertest.cc index 36cb5716b100..9f3f1209657c 100644 --- a/browser/brave_prefs_browsertest.cc +++ b/browser/brave_prefs_browsertest.cc @@ -15,7 +15,6 @@ #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" #include "brave/components/brave_wayback_machine/buildflags/buildflags.h" #include "brave/components/constants/pref_names.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/ntp_background_images/buildflags/buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" @@ -35,11 +34,6 @@ #include "components/sync/base/pref_names.h" #include "content/public/test/browser_test.h" -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/pref_names.h" -#endif - #if BUILDFLAG(ETHEREUM_REMOTE_CLIENT_ENABLED) #include "brave/browser/ethereum_remote_client/pref_names.h" #endif @@ -104,19 +98,6 @@ IN_PROC_BROWSER_TEST_F(BraveProfilePrefsBrowserTest, MiscBravePrefs) { kHangoutsEnabled)); EXPECT_TRUE(chrome_test_utils::GetProfile(this)->GetPrefs()->GetBoolean( brave_rewards::prefs::kShowLocationBarButton)); -#if BUILDFLAG(ENABLE_IPFS) - EXPECT_EQ(chrome_test_utils::GetProfile(this)->GetPrefs()->GetInteger( - kIPFSResolveMethod), - static_cast((ipfs::IPFSResolveMethodTypes::IPFS_ASK))); - EXPECT_TRUE(chrome_test_utils::GetProfile(this) - ->GetPrefs() - ->GetFilePath(kIPFSBinaryPath) - .empty()); - EXPECT_FALSE(chrome_test_utils::GetProfile(this)->GetPrefs()->GetBoolean( - kIPFSAutoRedirectToConfiguredGateway)); -#endif - EXPECT_FALSE(chrome_test_utils::GetProfile(this)->GetPrefs()->GetBoolean( - kIPFSCompanionEnabled)); #if BUILDFLAG(ETHEREUM_REMOTE_CLIENT_ENABLED) EXPECT_FALSE(chrome_test_utils::GetProfile(this)->GetPrefs()->GetBoolean( kERCOptedIntoCryptoWallets)); diff --git a/browser/brave_profile_prefs.cc b/browser/brave_profile_prefs.cc index 28398f78e9ad..6e595f20a55b 100644 --- a/browser/brave_profile_prefs.cc +++ b/browser/brave_profile_prefs.cc @@ -40,7 +40,7 @@ #include "brave/components/constants/pref_names.h" #include "brave/components/de_amp/common/pref_names.h" #include "brave/components/debounce/core/browser/debounce_service.h" -#include "brave/components/ipfs/buildflags/buildflags.h" +#include "brave/components/ipfs/ipfs_prefs.h" #include "brave/components/ntp_background_images/browser/view_counter_service.h" #include "brave/components/ntp_background_images/buildflags/buildflags.h" #include "brave/components/omnibox/browser/brave_omnibox_prefs.h" @@ -83,10 +83,6 @@ #include "brave/browser/ethereum_remote_client/pref_names.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/ipfs_service.h" -#endif - #if !BUILDFLAG(USE_GCM_FROM_PLATFORM) #include "brave/browser/gcm_driver/brave_gcm_utils.h" #endif @@ -213,6 +209,9 @@ void RegisterProfilePrefsForMigration( ai_chat::prefs::RegisterProfilePrefsForMigration(registry); #endif brave_shields::RegisterShieldsP3AProfilePrefsForMigration(registry); + + // Added 2024-05 + ipfs::RegisterDeprecatedIpfsPrefs(registry); } void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { @@ -263,10 +262,6 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { registry->RegisterBooleanPref(brave_shields::prefs::kLinkedInEmbedControlType, false); -#if BUILDFLAG(ENABLE_IPFS) - ipfs::IpfsService::RegisterProfilePrefs(registry); -#endif - // WebTorrent #if BUILDFLAG(ENABLE_BRAVE_WEBTORRENT) webtorrent::RegisterProfilePrefs(registry); @@ -367,9 +362,6 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { registry->RegisterBooleanPref(kImportDialogExtensions, true); registry->RegisterBooleanPref(kImportDialogPayments, true); - // IPFS companion extension - registry->RegisterBooleanPref(kIPFSCompanionEnabled, false); - // New Tab Page registry->RegisterBooleanPref(kNewTabPageShowClock, true); registry->RegisterStringPref(kNewTabPageClockFormat, ""); diff --git a/browser/brave_rewards/rewards_tab_helper.cc b/browser/brave_rewards/rewards_tab_helper.cc index 021c81754af6..dadeecd7c0e7 100644 --- a/browser/brave_rewards/rewards_tab_helper.cc +++ b/browser/brave_rewards/rewards_tab_helper.cc @@ -8,7 +8,6 @@ #include "brave/browser/brave_rewards/rewards_service_factory.h" #include "brave/components/brave_rewards/browser/publisher_utils.h" #include "brave/components/brave_rewards/browser/rewards_service.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "chrome/browser/profiles/profile.h" #include "components/sessions/content/session_tab_helper.h" #include "content/public/browser/navigation_entry.h" @@ -18,10 +17,6 @@ #include "content/public/browser/web_contents_user_data.h" #include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h" -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/ipfs_constants.h" -#endif - #if !BUILDFLAG(IS_ANDROID) #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" @@ -82,14 +77,6 @@ void RewardsTabHelper::DidFinishLoad( return; } -#if BUILDFLAG(ENABLE_IPFS) - auto ipns_url = GetWebContents().GetVisibleURL(); - if (ipns_url.SchemeIs(ipfs::kIPNSScheme)) { - rewards_service_->OnLoad(tab_id_, ipns_url); - return; - } -#endif - rewards_service_->OnLoad(tab_id_, validated_url); } diff --git a/browser/brave_rewards/sources.gni b/browser/brave_rewards/sources.gni index ef85ce7bedb8..5b793485de24 100644 --- a/browser/brave_rewards/sources.gni +++ b/browser/brave_rewards/sources.gni @@ -4,7 +4,6 @@ # You can obtain one at http://mozilla.org/MPL/2.0/. import("//brave/components/greaselion/browser/buildflags/buildflags.gni") -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//extensions/buildflags/buildflags.gni") brave_browser_brave_rewards_sources = [ @@ -24,7 +23,6 @@ brave_browser_brave_rewards_deps = [ "//brave/components/brave_rewards/browser", "//brave/components/brave_rewards/common", "//brave/components/brave_rewards/core:headers", - "//brave/components/ipfs/buildflags", "//chrome/browser:browser_process", "//chrome/browser/profiles:profile", "//chrome/browser/ui", @@ -57,10 +55,6 @@ if (enable_extensions) { ] } -if (enable_ipfs) { - brave_browser_brave_rewards_deps += [ "//brave/components/ipfs" ] -} - if (is_android) { brave_browser_brave_rewards_sources += [ "//brave/browser/brave_rewards/android/brave_rewards_native_worker.cc", diff --git a/browser/brave_tab_helpers.cc b/browser/brave_tab_helpers.cc index a08a6a6e01f5..83b4fdb6ed42 100644 --- a/browser/brave_tab_helpers.cc +++ b/browser/brave_tab_helpers.cc @@ -28,7 +28,6 @@ #include "brave/components/brave_perf_predictor/browser/perf_predictor_tab_helper.h" #include "brave/components/brave_wayback_machine/buildflags/buildflags.h" #include "brave/components/greaselion/browser/buildflags/buildflags.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/playlist/common/buildflags/buildflags.h" #include "brave/components/psst/browser/content/psst_tab_helper.h" #include "brave/components/request_otr/common/buildflags/buildflags.h" @@ -83,11 +82,6 @@ #include "brave/components/tor/tor_tab_helper.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/browser/ipfs/ipfs_tab_helper.h" -#endif - #if BUILDFLAG(ENABLE_EXTENSIONS) #include "brave/browser/web_discovery/web_discovery_tab_helper.h" #endif @@ -179,10 +173,6 @@ void AttachTabHelpers(content::WebContents* web_contents) { tor::OnionLocationTabHelper::CreateForWebContents(web_contents); #endif -#if BUILDFLAG(ENABLE_IPFS) - ipfs::IPFSTabHelper::MaybeCreateForWebContents(web_contents); -#endif - BraveNewsTabHelper::MaybeCreateForWebContents(web_contents); #if defined(TOOLKIT_VIEWS) diff --git a/browser/brave_wallet/BUILD.gn b/browser/brave_wallet/BUILD.gn index 206f72f3252e..4acda81da65e 100644 --- a/browser/brave_wallet/BUILD.gn +++ b/browser/brave_wallet/BUILD.gn @@ -4,7 +4,6 @@ # You can obtain one at https://mozilla.org/MPL/2.0/. import("//brave/browser/ethereum_remote_client/buildflags/buildflags.gni") -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//extensions/buildflags/buildflags.gni") import("//testing/test.gni") @@ -27,14 +26,6 @@ source_set("brave_wallet") { "swap_service_factory.cc", "swap_service_factory.h", ] - if (enable_ipfs_local_node) { - sources += [ - "brave_wallet_auto_pin_service_factory.cc", - "brave_wallet_auto_pin_service_factory.h", - "brave_wallet_pin_service_factory.cc", - "brave_wallet_pin_service_factory.h", - ] - } if (!is_android) { sources += [ "wallet_notification_helper.h" ] } diff --git a/browser/brave_wallet/brave_wallet_auto_pin_service_factory.cc b/browser/brave_wallet/brave_wallet_auto_pin_service_factory.cc deleted file mode 100644 index bbe5894f120d..000000000000 --- a/browser/brave_wallet/brave_wallet_auto_pin_service_factory.cc +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) 2023 The Brave Authors. All rights reserved. -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at https://mozilla.org/MPL/2.0/. - -#include "brave/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h" - -#include -#include - -#include "base/no_destructor.h" -#include "brave/browser/brave_wallet/brave_wallet_context_utils.h" -#include "brave/browser/brave_wallet/brave_wallet_pin_service_factory.h" -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" -// TODO(cypt4) : Refactor brave/browser/ipfs into separate component (#27486) -#include "brave/browser/ipfs/ipfs_service_factory.h" // nogncheck - -#include "brave/components/brave_wallet/browser/brave_wallet_pin_service.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" -#include "brave/components/brave_wallet/common/common_utils.h" - -#include "chrome/browser/profiles/incognito_helpers.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/user_prefs/user_prefs.h" - -namespace brave_wallet { - -// static -BraveWalletAutoPinServiceFactory* -BraveWalletAutoPinServiceFactory::GetInstance() { - static base::NoDestructor instance; - return instance.get(); -} - -// static -mojo::PendingRemote -BraveWalletAutoPinServiceFactory::GetForContext( - content::BrowserContext* context) { - if (!IsAllowedForContext(context)) { - return mojo::PendingRemote(); - } - - auto* service = GetServiceForContext(context); - - if (!service) { - return mojo::PendingRemote(); - } - - return service->MakeRemote(); -} - -// static -BraveWalletAutoPinService* -BraveWalletAutoPinServiceFactory::GetServiceForContext( - content::BrowserContext* context) { - if (!IsAllowedForContext(context)) { - return nullptr; - } - if (!ipfs::IpfsServiceFactory::IsIpfsEnabled(context)) { - return nullptr; - } - if (!brave_wallet::IsNftPinningEnabled()) { - return nullptr; - } - return static_cast( - GetInstance()->GetServiceForBrowserContext(context, true)); -} - -// static -void BraveWalletAutoPinServiceFactory::BindForContext( - content::BrowserContext* context, - mojo::PendingReceiver receiver) { - auto* service = - BraveWalletAutoPinServiceFactory::GetServiceForContext(context); - if (service) { - service->Bind(std::move(receiver)); - } -} - -BraveWalletAutoPinServiceFactory::BraveWalletAutoPinServiceFactory() - : BrowserContextKeyedServiceFactory( - "BraveWalletAutoPinService", - BrowserContextDependencyManager::GetInstance()) { - DependsOn(BraveWalletServiceFactory::GetInstance()); - DependsOn(BraveWalletPinServiceFactory::GetInstance()); -} - -BraveWalletAutoPinServiceFactory::~BraveWalletAutoPinServiceFactory() = default; - -KeyedService* BraveWalletAutoPinServiceFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - return new BraveWalletAutoPinService( - user_prefs::UserPrefs::Get(context), - BraveWalletServiceFactory::GetServiceForContext(context), - BraveWalletPinServiceFactory::GetServiceForContext(context)); -} - -content::BrowserContext* -BraveWalletAutoPinServiceFactory::GetBrowserContextToUse( - content::BrowserContext* context) const { - return chrome::GetBrowserContextRedirectedInIncognito(context); -} - -} // namespace brave_wallet diff --git a/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h b/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h deleted file mode 100644 index be51355ba1b2..000000000000 --- a/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2023 The Brave Authors. All rights reserved. -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at https://mozilla.org/MPL/2.0/. - -#ifndef BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_AUTO_PIN_SERVICE_FACTORY_H_ -#define BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_AUTO_PIN_SERVICE_FACTORY_H_ - -#include "brave/components/brave_wallet/browser/brave_wallet_auto_pin_service.h" -#include "brave/components/brave_wallet/common/brave_wallet.mojom.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" -#include "components/keyed_service/core/keyed_service.h" -#include "content/public/browser/browser_context.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" - -namespace base { -template -class NoDestructor; -} // namespace base - -namespace brave_wallet { - -class BraveWalletAutoPinService; - -class BraveWalletAutoPinServiceFactory - : public BrowserContextKeyedServiceFactory { - public: - static mojo::PendingRemote GetForContext( - content::BrowserContext* context); - static BraveWalletAutoPinService* GetServiceForContext( - content::BrowserContext* context); - static BraveWalletAutoPinServiceFactory* GetInstance(); - static void BindForContext( - content::BrowserContext* context, - mojo::PendingReceiver receiver); - - private: - friend base::NoDestructor; - - BraveWalletAutoPinServiceFactory(); - ~BraveWalletAutoPinServiceFactory() override; - - BraveWalletAutoPinServiceFactory(const BraveWalletAutoPinServiceFactory&) = - delete; - BraveWalletAutoPinServiceFactory& operator=( - const BraveWalletAutoPinServiceFactory&) = delete; - - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; - content::BrowserContext* GetBrowserContextToUse( - content::BrowserContext* context) const override; -}; - -} // namespace brave_wallet - -#endif // BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_AUTO_PIN_SERVICE_FACTORY_H_ diff --git a/browser/brave_wallet/brave_wallet_pin_service_factory.cc b/browser/brave_wallet/brave_wallet_pin_service_factory.cc deleted file mode 100644 index 71315f74d486..000000000000 --- a/browser/brave_wallet/brave_wallet_pin_service_factory.cc +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2023 The Brave Authors. All rights reserved. -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at https://mozilla.org/MPL/2.0/. - -#include "brave/browser/brave_wallet/brave_wallet_pin_service_factory.h" - -#include -#include - -#include "base/no_destructor.h" -#include "brave/browser/brave_wallet/brave_wallet_context_utils.h" -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" -// TODO(cypt4) : Refactor brave/browser into separate component (#27486) -#include "brave/browser/ipfs/ipfs_local_pin_service_factory.h" // nogncheck -#include "brave/browser/ipfs/ipfs_service_factory.h" // nogncheck -#include "brave/components/brave_wallet/browser/brave_wallet_pin_service.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service_delegate.h" -#include "brave/components/brave_wallet/common/common_utils.h" -#include "chrome/browser/profiles/incognito_helpers.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/storage_partition.h" - -namespace brave_wallet { - -// static -BraveWalletPinServiceFactory* BraveWalletPinServiceFactory::GetInstance() { - static base::NoDestructor instance; - return instance.get(); -} - -// static -mojo::PendingRemote -BraveWalletPinServiceFactory::GetForContext(content::BrowserContext* context) { - if (!IsAllowedForContext(context)) { - return mojo::PendingRemote(); - } - - auto* service = GetServiceForContext(context); - if (!service) { - return mojo::PendingRemote(); - } - - return service->MakeRemote(); -} - -// static -BraveWalletPinService* BraveWalletPinServiceFactory::GetServiceForContext( - content::BrowserContext* context) { - if (!IsAllowedForContext(context)) { - return nullptr; - } - if (!ipfs::IpfsServiceFactory::IsIpfsEnabled(context)) { - return nullptr; - } - if (!brave_wallet::IsNftPinningEnabled()) { - return nullptr; - } - return static_cast( - GetInstance()->GetServiceForBrowserContext(context, true)); -} - -// static -void BraveWalletPinServiceFactory::BindForContext( - content::BrowserContext* context, - mojo::PendingReceiver receiver) { - auto* service = BraveWalletPinServiceFactory::GetServiceForContext(context); - if (service) { - service->Bind(std::move(receiver)); - } -} - -BraveWalletPinServiceFactory::BraveWalletPinServiceFactory() - : BrowserContextKeyedServiceFactory( - "BraveWalletPinService", - BrowserContextDependencyManager::GetInstance()) { - DependsOn(brave_wallet::BraveWalletServiceFactory::GetInstance()); - DependsOn(ipfs::IpfsLocalPinServiceFactory::GetInstance()); - DependsOn(ipfs::IpfsServiceFactory::GetInstance()); -} - -BraveWalletPinServiceFactory::~BraveWalletPinServiceFactory() = default; - -KeyedService* BraveWalletPinServiceFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - return new BraveWalletPinService( - user_prefs::UserPrefs::Get(context), - BraveWalletServiceFactory::GetServiceForContext(context) - ->json_rpc_service(), - ipfs::IpfsLocalPinServiceFactory::GetServiceForContext(context), - ipfs::IpfsServiceFactory::GetForContext(context), - std::make_unique( - user_prefs::UserPrefs::Get(context), - context->GetDefaultStoragePartition() - ->GetURLLoaderFactoryForBrowserProcess())); -} - -content::BrowserContext* BraveWalletPinServiceFactory::GetBrowserContextToUse( - content::BrowserContext* context) const { - return chrome::GetBrowserContextRedirectedInIncognito(context); -} - -} // namespace brave_wallet diff --git a/browser/brave_wallet/brave_wallet_pin_service_factory.h b/browser/brave_wallet/brave_wallet_pin_service_factory.h deleted file mode 100644 index 7e9cd1b813a6..000000000000 --- a/browser/brave_wallet/brave_wallet_pin_service_factory.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2023 The Brave Authors. All rights reserved. -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at https://mozilla.org/MPL/2.0/. - -#ifndef BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_PIN_SERVICE_FACTORY_H_ -#define BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_PIN_SERVICE_FACTORY_H_ - -#include "brave/components/brave_wallet/common/brave_wallet.mojom.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" -#include "components/keyed_service/core/keyed_service.h" -#include "content/public/browser/browser_context.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" - -namespace base { -template -class NoDestructor; -} // namespace base - -namespace brave_wallet { - -class BraveWalletPinService; - -class BraveWalletPinServiceFactory : public BrowserContextKeyedServiceFactory { - public: - static mojo::PendingRemote GetForContext( - content::BrowserContext* context); - static BraveWalletPinService* GetServiceForContext( - content::BrowserContext* context); - static BraveWalletPinServiceFactory* GetInstance(); - static void BindForContext( - content::BrowserContext* context, - mojo::PendingReceiver receiver); - - private: - friend base::NoDestructor; - - BraveWalletPinServiceFactory(); - ~BraveWalletPinServiceFactory() override; - - BraveWalletPinServiceFactory(const BraveWalletPinServiceFactory&) = delete; - BraveWalletPinServiceFactory& operator=(const BraveWalletPinServiceFactory&) = - delete; - - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; - content::BrowserContext* GetBrowserContextToUse( - content::BrowserContext* context) const override; -}; - -} // namespace brave_wallet - -#endif // BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_PIN_SERVICE_FACTORY_H_ diff --git a/browser/browser_context_keyed_service_factories.cc b/browser/browser_context_keyed_service_factories.cc index 5f00475ef7c9..0de43132ca42 100644 --- a/browser/browser_context_keyed_service_factories.cc +++ b/browser/browser_context_keyed_service_factories.cc @@ -36,7 +36,6 @@ #include "brave/components/brave_wallet/common/common_utils.h" #include "brave/components/commander/common/buildflags/buildflags.h" #include "brave/components/greaselion/browser/buildflags/buildflags.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/playlist/common/buildflags/buildflags.h" #include "brave/components/request_otr/common/buildflags/buildflags.h" #include "brave/components/speedreader/common/buildflags/buildflags.h" @@ -55,7 +54,6 @@ #endif #if !BUILDFLAG(IS_ANDROID) -#include "brave/browser/infobars/brave_global_infobar_service_factory.h" #include "brave/browser/ui/bookmark/bookmark_prefs_service_factory.h" #include "brave/browser/ui/commands/accelerator_service_factory.h" #include "brave/browser/ui/tabs/features.h" @@ -71,15 +69,6 @@ #include "brave/browser/ethereum_remote_client/ethereum_remote_client_service_factory.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/browser/ipfs/ipfs_service_factory.h" -#endif - -#if BUILDFLAG(ENABLE_IPFS_LOCAL_NODE) -#include "brave/browser/brave_wallet/brave_wallet_auto_pin_service_factory.h" -#include "brave/browser/brave_wallet/brave_wallet_pin_service_factory.h" -#endif - #if BUILDFLAG(ENABLE_TOR) #include "brave/browser/tor/tor_profile_service_factory.h" #endif @@ -167,16 +156,8 @@ void EnsureBrowserContextKeyedServiceFactoriesBuilt() { EthereumRemoteClientServiceFactory::GetInstance(); #endif -#if BUILDFLAG(ENABLE_IPFS) - ipfs::IpfsServiceFactory::GetInstance(); -#endif brave_wallet::BraveWalletIpfsServiceFactory::GetInstance(); -#if BUILDFLAG(ENABLE_IPFS_LOCAL_NODE) - brave_wallet::BraveWalletAutoPinServiceFactory::GetInstance(); - brave_wallet::BraveWalletPinServiceFactory::GetInstance(); -#endif - EphemeralStorageServiceFactory::GetInstance(); PermissionLifetimeManagerFactory::GetInstance(); #if BUILDFLAG(ENABLE_BRAVE_VPN) || BUILDFLAG(ENABLE_AI_CHAT) @@ -209,10 +190,6 @@ void EnsureBrowserContextKeyedServiceFactoriesBuilt() { #if BUILDFLAG(ENABLE_SPEEDREADER) speedreader::SpeedreaderServiceFactory::GetInstance(); #endif - -#if !BUILDFLAG(IS_ANDROID) - BraveGlobalInfobarServiceFactory::GetInstance(); -#endif #if BUILDFLAG(ENABLE_AI_CHAT) ai_chat::ModelServiceFactory::GetInstance(); #endif diff --git a/browser/browsing_data/brave_browsing_data_remover_delegate.cc b/browser/browsing_data/brave_browsing_data_remover_delegate.cc index 4b1e137c3086..7c02f6ba00ea 100644 --- a/browser/browsing_data/brave_browsing_data_remover_delegate.cc +++ b/browser/browsing_data/brave_browsing_data_remover_delegate.cc @@ -19,19 +19,6 @@ #include "chrome/common/buildflags.h" #include "components/content_settings/core/browser/host_content_settings_map.h" -#if BUILDFLAG(ENABLE_IPFS) -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/process/launch.h" -#include "base/process/process.h" -#include "base/task/task_traits.h" -#include "base/task/thread_pool.h" -#include "base/threading/thread_restrictions.h" -#include "base/time/time.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/ipfs/ipfs_service.h" -#endif - #if BUILDFLAG(ENABLE_AI_CHAT) #include "brave/components/ai_chat/core/browser/utils.h" #include "brave/components/ai_chat/core/common/features.h" @@ -66,10 +53,6 @@ void BraveBrowsingDataRemoverDelegate::RemoveEmbedderData( if (remove_mask & chrome_browsing_data_remover::DATA_TYPE_CONTENT_SETTINGS) ClearShieldsSettings(delete_begin, delete_end); -#if BUILDFLAG(ENABLE_IPFS) - if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_CACHE) - ClearIPFSCache(); -#endif // Brave News feed cache if (remove_mask & chrome_browsing_data_remover::DATA_TYPE_HISTORY) { brave_news::BraveNewsControllerFactory::GetForContext(profile_) @@ -120,69 +103,3 @@ void BraveBrowsingDataRemoverDelegate::ClearAiChatHistory(base::Time begin_time, // It is prepared for future implementation. } #endif // BUILDFLAG(ENABLE_AI_CHAT) - -#if BUILDFLAG(ENABLE_IPFS) -void BraveBrowsingDataRemoverDelegate::WaitForIPFSRepoGC( - base::Process process) { - bool exited = false; - - { - base::ScopedAllowBaseSyncPrimitives scoped_allow_base_sync_primitives; - - // Because we set maximum IPFS storage size as 1GB in Brave, ipfs repo gc - // command should be finished in just a few seconds and we do not expect - // this child process would hang forever. To be safe, we will wait for 30 - // seconds max here. - exited = process.WaitForExitWithTimeout(base::Seconds(30), nullptr); - } - - if (!exited) - process.Terminate(0, false /* wait */); -} - -// Run ipfs repo gc command to clear IPFS cache when IPFS executable path is -// available. Because the command does not support time ranged cleanup, we will -// always clear the whole cache expect for pinned files when clearing browsing -// data. -void BraveBrowsingDataRemoverDelegate::ClearIPFSCache() { - auto* service = - ipfs::IpfsServiceFactory::GetInstance()->GetForContext(profile_); - if (!service) - return; - - base::FilePath path = service->GetIpfsExecutablePath(); - if (path.empty()) - return; - - base::CommandLine cmdline(path); - cmdline.AppendArg("repo"); - cmdline.AppendArg("gc"); - - base::FilePath data_path = service->GetDataPath(); - base::LaunchOptions options; -#if BUILDFLAG(IS_WIN) - options.environment[L"IPFS_PATH"] = data_path.value(); -#else - options.environment["IPFS_PATH"] = data_path.value(); -#endif -#if BUILDFLAG(IS_LINUX) - options.kill_on_parent_death = true; -#endif -#if BUILDFLAG(IS_WIN) - options.start_hidden = true; -#endif - - base::Process process = base::LaunchProcess(cmdline, options); - if (!process.IsValid()) { - return; - } - - base::ThreadPool::PostTaskAndReply( - FROM_HERE, - {base::TaskPriority::USER_VISIBLE, base::MayBlock(), - base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, - base::BindOnce(&BraveBrowsingDataRemoverDelegate::WaitForIPFSRepoGC, - weak_ptr_factory_.GetWeakPtr(), std::move(process)), - CreateTaskCompletionClosure(TracingDataType::kIPFSCache)); -} -#endif // BUILDFLAG(ENABLE_IPFS) diff --git a/browser/browsing_data/brave_browsing_data_remover_delegate.h b/browser/browsing_data/brave_browsing_data_remover_delegate.h index 9b788ab1a440..606b2c84b0e7 100644 --- a/browser/browsing_data/brave_browsing_data_remover_delegate.h +++ b/browser/browsing_data/brave_browsing_data_remover_delegate.h @@ -11,13 +11,8 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "brave/components/ai_chat/core/common/buildflags/buildflags.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h" -namespace base { -class Process; -} // namespace base - namespace content_settings { class BravePrefProvider; } // namespace content_settings @@ -53,10 +48,6 @@ class BraveBrowsingDataRemoverDelegate #if BUILDFLAG(ENABLE_AI_CHAT) void ClearAiChatHistory(base::Time begin_time, base::Time end_time); #endif // BUILDFLAG(ENABLE_AI_CHAT) -#if BUILDFLAG(ENABLE_IPFS) - void ClearIPFSCache(); - void WaitForIPFSRepoGC(base::Process process); -#endif raw_ptr profile_ = nullptr; base::WeakPtrFactory weak_ptr_factory_{ diff --git a/browser/browsing_data/sources.gni b/browser/browsing_data/sources.gni index b813152724ff..fb8c2d5f35ef 100644 --- a/browser/browsing_data/sources.gni +++ b/browser/browsing_data/sources.gni @@ -3,7 +3,6 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//extensions/buildflags/buildflags.gni") brave_browser_browsing_data_sources = [ @@ -15,7 +14,6 @@ brave_browser_browsing_data_sources = [ brave_browser_browsing_data_deps = [ "//base", - "//brave/components/ipfs/buildflags", "//chrome/browser:browser_process", "//chrome/browser/browsing_data:constants", "//chrome/browser/profiles:profile", @@ -33,7 +31,3 @@ if (enable_extensions) { "//extensions/browser", ] } - -if (enable_ipfs) { - brave_browser_browsing_data_deps += [ "//brave/components/ipfs" ] -} diff --git a/browser/extensions/BUILD.gn b/browser/extensions/BUILD.gn index d7c86c2e2dc9..52754505870a 100644 --- a/browser/extensions/BUILD.gn +++ b/browser/extensions/BUILD.gn @@ -6,7 +6,6 @@ import("//brave/browser/ethereum_remote_client/buildflags/buildflags.gni") import("//brave/components/brave_wayback_machine/buildflags/buildflags.gni") import("//brave/components/brave_webtorrent/browser/buildflags/buildflags.gni") -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//brave/components/speedreader/common/buildflags/buildflags.gni") import("//brave/components/tor/buildflags/buildflags.gni") import("//build/config/features.gni") @@ -80,7 +79,6 @@ source_set("extensions") { "//brave/components/constants", "//brave/components/de_amp/common", "//brave/components/decentralized_dns/content", - "//brave/components/ipfs/buildflags", "//brave/components/ntp_widget_utils/browser", "//brave/components/sidebar/browser", "//brave/components/tor/buildflags", @@ -126,14 +124,6 @@ source_set("extensions") { ] } - if (enable_ipfs) { - sources += [ - "api/ipfs_api.cc", - "api/ipfs_api.h", - ] - deps += [ "//brave/components/ipfs" ] - } - if (enable_brave_webtorrent) { deps += [ "//brave/components/brave_webtorrent/browser" ] sources += [ diff --git a/browser/extensions/api/brave_extensions_api_client.cc b/browser/extensions/api/brave_extensions_api_client.cc index f8146895a319..372bea99a8fc 100644 --- a/browser/extensions/api/brave_extensions_api_client.cc +++ b/browser/extensions/api/brave_extensions_api_client.cc @@ -7,7 +7,6 @@ #include -#include "brave/components/ipfs/ipfs_node_traffic_recognizer.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/url_pattern.h" #include "url/origin.h" @@ -29,10 +28,6 @@ bool BraveExtensionsAPIClient::ShouldHideBrowserNetworkRequest( return true; // protected URL } - if (ipfs::IpfsNodeTrafficRecognizer::IsKuboRelatedUrl(request.url)) { - return true; - } - return ChromeExtensionsAPIClient::ShouldHideBrowserNetworkRequest(context, request); } diff --git a/browser/extensions/api/ipfs_api.cc b/browser/extensions/api/ipfs_api.cc deleted file mode 100644 index c52dee71fa64..000000000000 --- a/browser/extensions/api/ipfs_api.cc +++ /dev/null @@ -1,612 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/extensions/api/ipfs_api.h" - -#include -#include -#include -#include -#include - -#include "base/files/file_util.h" -#include "base/json/json_writer.h" -#include "base/task/thread_pool.h" -#include "base/values.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/common/extensions/api/ipfs.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_json_parser.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/keys/ipns_keys_manager.h" -#include "brave/components/ipfs/pref_names.h" -#include "brave/components/l10n/common/localization_util.h" -#include "brave/grit/brave_generated_resources.h" -#include "chrome/common/channel_info.h" -#include "components/prefs/pref_service.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" - -using ipfs::IPFSResolveMethodTypes; - -namespace { - -ipfs::IpfsService* GetIpfsService(content::BrowserContext* context) { - return ipfs::IpfsServiceFactory::GetInstance()->GetForContext(context); -} - -base::Value::Dict MakeSelectValue(const std::u16string& name, - IPFSResolveMethodTypes value) { - base::Value::Dict item; - item.Set("value", base::Value(static_cast(value))); - item.Set("name", base::Value(name)); - return item; -} - -base::Value::Dict MakeValue(const std::string& name, const std::string& value) { - base::Value::Dict item; - item.Set("value", base::Value(value)); - item.Set("name", base::Value(name)); - return item; -} - -std::string MakeResponseFromMap(const ipfs::IpnsKeysManager::KeysMap& keys) { - base::Value::List list; - for (const auto& key : keys) { - list.Append(MakeValue(key.first, key.second)); - } - std::string json_string; - base::JSONWriter::Write(list, &json_string); - return json_string; -} - -std::string MakePeersResponseFromVector( - const std::vector& source) { - base::Value::List list; - for (const auto& item : source) { - std::string id; - std::string address; - if (!ipfs::ParsePeerConnectionString(item, &id, &address)) - continue; - list.Append(MakeValue(id, address)); - } - std::string json_string; - base::JSONWriter::Write(list, &json_string); - return json_string; -} - -bool WriteFileOnFileThread(const base::FilePath& path, - const std::string& value) { - return base::WriteFile(path, value); -} - -} // namespace - -namespace extensions::api { - -ExtensionFunction::ResponseAction IpfsRemoveIpfsPeerFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) - return RespondNow(Error("IPFS not enabled")); - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return RespondNow(Error("Could not obtain IPFS service")); - } - std::optional params = - ipfs::RemoveIpfsPeer::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - ipfs_service->GetConfig( - base::BindOnce(&IpfsRemoveIpfsPeerFunction::OnConfigLoaded, - base::RetainedRef(this), params->id, params->address)); - return RespondLater(); -} - -void IpfsRemoveIpfsPeerFunction::OnConfigLoaded(const std::string& peer_id, - const std::string& address, - bool success, - const std::string& config) { - if (!success) { - return Respond(Error("Unable to load config")); - } - std::string new_config = - IPFSJSONParser::RemovePeerFromConfigJSON(config, peer_id, address); - if (new_config.empty()) { - VLOG(1) << "New config is empty, probably passed incorrect values"; - return Respond(WithArguments(false)); - } - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return Respond(Error("Could not obtain IPFS service")); - } - auto config_path = ipfs_service->GetConfigFilePath(); - auto write_callback = - base::BindOnce(&WriteFileOnFileThread, config_path, new_config); - base::ThreadPool::PostTaskAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, std::move(write_callback), - base::BindOnce(&IpfsRemoveIpfsPeerFunction::OnConfigUpdated, - base::RetainedRef(this))); -} - -void IpfsRemoveIpfsPeerFunction::OnConfigUpdated(bool success) { - Respond(WithArguments(success)); -} - -ExtensionFunction::ResponseAction IpfsAddIpfsPeerFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) - return RespondNow(Error("IPFS not enabled")); - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return RespondNow(Error("Could not obtain IPFS service")); - } - std::optional params = - ipfs::AddIpfsPeer::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - ipfs_service->GetConfig( - base::BindOnce(&IpfsAddIpfsPeerFunction::OnConfigLoaded, - base::RetainedRef(this), params->value)); - return RespondLater(); -} - -void IpfsAddIpfsPeerFunction::OnConfigLoaded(const std::string& peer, - bool success, - const std::string& config) { - if (!success) { - return Respond(Error("Unable to load config")); - } - std::string new_config = IPFSJSONParser::PutNewPeerToConfigJSON(config, peer); - if (new_config.empty()) { - VLOG(1) << "New config is empty, probably passed incorrect values"; - return Respond(WithArguments(false)); - } - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return Respond(Error("Could not obtain IPFS service")); - } - auto config_path = ipfs_service->GetConfigFilePath(); - auto write_callback = - base::BindOnce(&WriteFileOnFileThread, config_path, new_config); - base::ThreadPool::PostTaskAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, std::move(write_callback), - base::BindOnce(&IpfsAddIpfsPeerFunction::OnConfigUpdated, - base::RetainedRef(this))); -} - -void IpfsAddIpfsPeerFunction::OnConfigUpdated(bool success) { - Respond(WithArguments(success)); -} - -ExtensionFunction::ResponseAction IpfsGetIpfsPeersListFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) - return RespondNow(Error("IPFS not enabled")); - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return RespondNow(Error("Could not obtain IPFS service")); - } - if (!ipfs_service->IsIPFSExecutableAvailable()) { - return RespondNow(Error("Could not obtain IPFS executable")); - } - ipfs_service->GetConfig(base::BindOnce( - &IpfsGetIpfsPeersListFunction::OnConfigLoaded, base::RetainedRef(this))); - return RespondLater(); -} - -void IpfsGetIpfsPeersListFunction::OnConfigLoaded(bool success, - const std::string& config) { - if (!success) { - return Respond(Error("Unable to load config")); - } - std::vector peers; - if (!IPFSJSONParser::GetPeersFromConfigJSON(config, &peers)) { - VLOG(1) << "Unable to parse peers in config"; - } - Respond(WithArguments(MakePeersResponseFromVector(peers))); -} - -ExtensionFunction::ResponseAction IpfsRemoveIpnsKeyFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) - return RespondNow(Error("IPFS not enabled")); - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return RespondNow(Error("Could not obtain IPFS service")); - } - ::ipfs::IpnsKeysManager* key_manager = ipfs_service->GetIpnsKeysManager(); - if (!ipfs_service->IsDaemonLaunched() || !key_manager) { - return RespondNow(Error("IPFS node is not launched")); - } - std::optional params = - ipfs::RemoveIpnsKey::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - key_manager->RemoveKey( - params->name, base::BindOnce(&IpfsRemoveIpnsKeyFunction::OnKeyRemoved, - base::RetainedRef(this), key_manager)); - return did_respond() ? AlreadyResponded() : RespondLater(); -} - -void IpfsRemoveIpnsKeyFunction::OnKeyRemoved(::ipfs::IpnsKeysManager* manager, - const std::string& name, - bool success) { - DCHECK(manager); - if (!success) { - return Respond(Error("Unable to remove key")); - } - return Respond(WithArguments(name)); -} - -ExtensionFunction::ResponseAction IpfsRotateKeyFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) - return RespondNow(Error("IPFS not enabled")); - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return RespondNow(Error("Could not obtain IPFS service")); - } - std::optional params = - ipfs::RotateKey::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - ipfs_service->RotateKey(params->name, - base::BindOnce(&IpfsRotateKeyFunction::OnKeyRotated, - base::RetainedRef(this))); - return did_respond() ? AlreadyResponded() : RespondLater(); -} - -void IpfsRotateKeyFunction::OnKeyRotated(bool success) { - return Respond(WithArguments(success)); -} - -ExtensionFunction::ResponseAction IpfsAddIpnsKeyFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) - return RespondNow(Error("IPFS not enabled")); - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return RespondNow(Error("Could not obtain IPFS service")); - } - ::ipfs::IpnsKeysManager* key_manager = ipfs_service->GetIpnsKeysManager(); - if (!ipfs_service->IsDaemonLaunched() || !key_manager) { - return RespondNow(Error("IPFS node is not launched")); - } - std::optional params = - ipfs::AddIpnsKey::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - key_manager->GenerateNewKey( - params->name, base::BindOnce(&IpfsAddIpnsKeyFunction::OnKeyCreated, - base::RetainedRef(this), key_manager)); - return did_respond() ? AlreadyResponded() : RespondLater(); -} - -void IpfsAddIpnsKeyFunction::OnKeyCreated(::ipfs::IpnsKeysManager* manager, - bool success, - const std::string& name, - const std::string& value) { - DCHECK(manager); - if (!success) { - return Respond(Error("Unable to create key")); - } - std::string json_string; - base::JSONWriter::Write(MakeValue(name, value), &json_string); - return Respond(WithArguments(json_string)); -} - -ExtensionFunction::ResponseAction IpfsGetIpnsKeysListFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) - return RespondNow(Error("IPFS not enabled")); - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return RespondNow(Error("Could not obtain IPFS service")); - } - ::ipfs::IpnsKeysManager* key_manager = ipfs_service->GetIpnsKeysManager(); - if (!ipfs_service->IsDaemonLaunched() || !key_manager) { - return RespondNow(Error("IPFS node is not launched")); - } - const auto& keys = key_manager->GetKeys(); - if (!keys.size()) { - key_manager->LoadKeys( - base::BindOnce(&IpfsGetIpnsKeysListFunction::OnKeysLoaded, - base::RetainedRef(this), key_manager)); - return RespondLater(); - } - return RespondNow(WithArguments(MakeResponseFromMap(keys))); -} - -void IpfsGetIpnsKeysListFunction::OnKeysLoaded(::ipfs::IpnsKeysManager* manager, - bool success) { - DCHECK(manager); - if (!success) { - return Respond(Error("Unable to load keys")); - } - return Respond(WithArguments(MakeResponseFromMap(manager->GetKeys()))); -} - -ExtensionFunction::ResponseAction IpfsGetResolveMethodListFunction::Run() { - base::Value::List list; - list.Append(MakeSelectValue( - brave_l10n::GetLocalizedResourceUTF16String(IDS_IPFS_RESOLVE_OPTION_ASK), - IPFSResolveMethodTypes::IPFS_ASK)); - list.Append(MakeSelectValue(brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_RESOLVE_OPTION_GATEWAY), - IPFSResolveMethodTypes::IPFS_GATEWAY)); - - list.Append(MakeSelectValue(brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_RESOLVE_OPTION_LOCAL), - IPFSResolveMethodTypes::IPFS_LOCAL)); - - list.Append(MakeSelectValue(brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_RESOLVE_OPTION_DISABLED), - IPFSResolveMethodTypes::IPFS_DISABLED)); - std::string json_string; - base::JSONWriter::Write(list, &json_string); - return RespondNow(WithArguments(json_string)); -} - -ExtensionFunction::ResponseAction IpfsGetIPFSEnabledFunction::Run() { - bool enabled = ::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context()); - return RespondNow(WithArguments(enabled)); -} - -ExtensionFunction::ResponseAction IpfsGetResolveMethodTypeFunction::Run() { - std::string value = "invalid"; - if (::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - switch (GetIpfsService(browser_context())->GetIPFSResolveMethodType()) { - case IPFSResolveMethodTypes::IPFS_ASK: - value = "ask"; - break; - case IPFSResolveMethodTypes::IPFS_GATEWAY: - value = "gateway"; - break; - case IPFSResolveMethodTypes::IPFS_LOCAL: - value = "local"; - break; - case IPFSResolveMethodTypes::IPFS_DISABLED: - value = "disabled"; - break; - } - } - return RespondNow(WithArguments(value)); -} - -ExtensionFunction::ResponseAction IpfsLaunchFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - - if (!GetIpfsService(browser_context())) { - return RespondNow(Error("Could not obtain IPFS service")); - } - - if (!GetIpfsService(browser_context())->IsIPFSExecutableAvailable()) { - return RespondNow(WithArguments(false)); - } - - GetIpfsService(browser_context()) - ->LaunchDaemon(base::BindOnce(&IpfsLaunchFunction::OnLaunch, - base::RetainedRef(this))); - return did_respond() ? AlreadyResponded() : RespondLater(); -} - -void IpfsLaunchFunction::OnLaunch(bool launched) { - Respond(WithArguments(launched)); -} - -ExtensionFunction::ResponseAction IpfsShutdownFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - GetIpfsService(browser_context()) - ->ShutdownDaemon(base::BindOnce(&IpfsShutdownFunction::OnShutdown, - base::RetainedRef(this))); - return did_respond() ? AlreadyResponded() : RespondLater(); -} - -void IpfsShutdownFunction::OnShutdown(bool shutdown) { - Respond(WithArguments(shutdown)); -} - -ExtensionFunction::ResponseAction IpfsGetConfigFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - GetIpfsService(browser_context()) - ->GetConfig(base::BindOnce(&IpfsGetConfigFunction::OnGetConfig, - base::RetainedRef(this))); - return RespondLater(); -} - -void IpfsGetConfigFunction::OnGetConfig(bool success, - const std::string& value) { - Respond(WithArguments(success, value)); -} - -ExtensionFunction::ResponseAction IpfsGetExecutableAvailableFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - bool avail = GetIpfsService(browser_context())->IsIPFSExecutableAvailable(); - return RespondNow(WithArguments(avail)); -} - -ExtensionFunction::ResponseAction IpfsResolveIPFSURIFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - - std::optional params = - ipfs::ResolveIPFSURI::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - GURL uri(params->uri); - GURL ipfs_gateway_url; - PrefService* prefs = user_prefs::UserPrefs::Get(browser_context()); - if (!::ipfs::ResolveIPFSURI(prefs, chrome::GetChannel(), uri, - &ipfs_gateway_url) || - !ipfs_gateway_url.is_valid()) { - return RespondNow(Error("Could not translate IPFS URI")); - } - - return RespondNow(WithArguments(ipfs_gateway_url.spec())); -} - -ExtensionFunction::ResponseAction IpfsValidateGatewayUrlFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) - return RespondNow(Error("IPFS not enabled")); - ::ipfs::IpfsService* ipfs_service = GetIpfsService(browser_context()); - if (!ipfs_service) { - return RespondNow(Error("Could not obtain IPFS service")); - } - std::optional params = - ipfs::ValidateGatewayUrl::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - - ipfs_service->ValidateGateway( - GURL(params->url), - base::BindOnce(&IpfsValidateGatewayUrlFunction::OnGatewayValidated, - base::RetainedRef(this))); - return did_respond() ? AlreadyResponded() : RespondLater(); -} - -void IpfsValidateGatewayUrlFunction::OnGatewayValidated(bool success) { - return Respond(WithArguments(success)); -} - -ExtensionFunction::ResponseAction IpfsGetSettingsFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - PrefService* prefs = user_prefs::UserPrefs::Get(browser_context()); - - base::Value::Dict response; - response.Set("gateway_auto_fallback_enabled", - prefs->GetBoolean(kIPFSAutoFallbackToGateway)); - response.Set("auto_redirect_to_configured_gateway", - prefs->GetBoolean(kIPFSAutoRedirectToConfiguredGateway)); - response.Set("storage_max", prefs->GetInteger(kIpfsStorageMax)); - response.Set("gateway_url", prefs->GetString(kIPFSPublicGatewayAddress)); - response.Set("nft_gateway_url", - prefs->GetString(kIPFSPublicNFTGatewayAddress)); - - std::string resolve_method_str; - IPFSResolveMethodTypes resolve_method = static_cast( - prefs->GetInteger(kIPFSResolveMethod)); - switch (resolve_method) { - case IPFSResolveMethodTypes::IPFS_LOCAL: - resolve_method_str = "local"; - break; - case IPFSResolveMethodTypes::IPFS_GATEWAY: - resolve_method_str = "gateway"; - break; - case IPFSResolveMethodTypes::IPFS_ASK: - resolve_method_str = "ask"; - break; - case IPFSResolveMethodTypes::IPFS_DISABLED: - resolve_method_str = "disabled"; - break; - } - response.Set("resolve_method", resolve_method_str); - - std::string json_string; - base::JSONWriter::Write(response, &json_string); - - return RespondNow(WithArguments(json_string)); -} - -ExtensionFunction::ResponseAction IpfsSetPublicGatewayFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - - PrefService* prefs = user_prefs::UserPrefs::Get(browser_context()); - - std::optional params = - ipfs::SetPublicGateway::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - - GURL url(params->url); - if (!url.is_valid()) { - return RespondNow(Error("Wrong url format")); - } - - prefs->SetString(kIPFSPublicGatewayAddress, params->url); - return RespondNow(WithArguments(true)); -} - -ExtensionFunction::ResponseAction IpfsSetPublicNFTGatewayFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - - PrefService* prefs = user_prefs::UserPrefs::Get(browser_context()); - - std::optional params = - ipfs::SetPublicNFTGateway::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - - GURL url(params->url); - if (!url.is_valid()) { - return RespondNow(Error("Wrong url format")); - } - - prefs->SetString(kIPFSPublicNFTGatewayAddress, params->url); - return RespondNow(WithArguments(true)); -} - -ExtensionFunction::ResponseAction IpfsSetResolveMethodFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - - PrefService* prefs = user_prefs::UserPrefs::Get(browser_context()); - - std::optional params = - ipfs::SetResolveMethod::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - - IPFSResolveMethodTypes resolve_method; - if (params->resolve_method == "ask") { - resolve_method = IPFSResolveMethodTypes::IPFS_ASK; - } else if (params->resolve_method == "local") { - resolve_method = IPFSResolveMethodTypes::IPFS_LOCAL; - } else if (params->resolve_method == "gateway") { - resolve_method = IPFSResolveMethodTypes::IPFS_GATEWAY; - } else if (params->resolve_method == "disabled") { - resolve_method = IPFSResolveMethodTypes::IPFS_DISABLED; - } else { - return RespondNow(Error("Wrong arguments")); - } - - prefs->SetInteger(kIPFSResolveMethod, static_cast(resolve_method)); - return RespondNow(WithArguments(true)); -} - -ExtensionFunction::ResponseAction -IpfsSetAutoRedirectToConfiguredGatewayEnabledFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - - PrefService* prefs = user_prefs::UserPrefs::Get(browser_context()); - - std::optional - params = ipfs::SetAutoRedirectToConfiguredGatewayEnabled::Params::Create( - args()); - EXTENSION_FUNCTION_VALIDATE(params); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, params->value); - return RespondNow(WithArguments(true)); -} - -ExtensionFunction::ResponseAction IpfsSetGatewayFallbackEnabledFunction::Run() { - if (!::ipfs::IpfsServiceFactory::IsIpfsEnabled(browser_context())) { - return RespondNow(Error("IPFS not enabled")); - } - - PrefService* prefs = user_prefs::UserPrefs::Get(browser_context()); - - std::optional params = - ipfs::SetGatewayFallbackEnabled::Params::Create(args()); - EXTENSION_FUNCTION_VALIDATE(params); - - prefs->SetBoolean(kIPFSAutoFallbackToGateway, params->value); - return RespondNow(WithArguments(true)); -} - -} // namespace extensions::api diff --git a/browser/extensions/api/ipfs_api.h b/browser/extensions/api/ipfs_api.h deleted file mode 100644 index 5c3420dbc9fc..000000000000 --- a/browser/extensions/api/ipfs_api.h +++ /dev/null @@ -1,255 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_EXTENSIONS_API_IPFS_API_H_ -#define BRAVE_BROWSER_EXTENSIONS_API_IPFS_API_H_ - -#include - -#include "extensions/browser/extension_function.h" - -class Profile; - -namespace ipfs { -class IpnsKeysManager; -} // namespace ipfs - -namespace extensions { -namespace api { - -class IpfsGetIpfsPeersListFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.getIpfsPeersList", UNKNOWN) - - protected: - void OnConfigLoaded(bool success, const std::string& config); - ~IpfsGetIpfsPeersListFunction() override {} - ResponseAction Run() override; -}; - -class IpfsAddIpfsPeerFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.addIpfsPeer", UNKNOWN) - - protected: - void OnPeerAdded(bool result, const std::string& value); - void OnConfigLoaded(const std::string& peer, - bool success, - const std::string& config); - void OnConfigUpdated(bool success); - - ~IpfsAddIpfsPeerFunction() override {} - ResponseAction Run() override; -}; - -class IpfsRemoveIpfsPeerFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.removeIpfsPeer", UNKNOWN) - - protected: - void OnPeerAdded(bool result, const std::string& value); - void OnConfigLoaded(const std::string& peer_id, - const std::string& address, - bool success, - const std::string& config); - void OnConfigUpdated(bool success); - - ~IpfsRemoveIpfsPeerFunction() override {} - ResponseAction Run() override; -}; - -class IpfsRemoveIpnsKeyFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.removeIpnsKey", UNKNOWN) - - protected: - void OnKeyRemoved(::ipfs::IpnsKeysManager* manager, const std::string&, bool); - - ~IpfsRemoveIpnsKeyFunction() override {} - ResponseAction Run() override; -}; - -class IpfsGetResolveMethodListFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.getResolveMethodList", UNKNOWN) - - protected: - ~IpfsGetResolveMethodListFunction() override {} - ResponseAction Run() override; -}; - -class IpfsRotateKeyFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.rotateKey", UNKNOWN) - - protected: - void OnKeyRotated(bool result); - - ~IpfsRotateKeyFunction() override {} - ResponseAction Run() override; -}; - -class IpfsAddIpnsKeyFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.addIpnsKey", UNKNOWN) - - protected: - void OnKeyCreated(::ipfs::IpnsKeysManager* manager, - bool result, - const std::string& name, - const std::string& value); - - ~IpfsAddIpnsKeyFunction() override {} - ResponseAction Run() override; -}; - -class IpfsGetIpnsKeysListFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.getIpnsKeysList", UNKNOWN) - - protected: - void OnKeysLoaded(::ipfs::IpnsKeysManager* manager, bool success); - - ~IpfsGetIpnsKeysListFunction() override {} - ResponseAction Run() override; -}; - -class IpfsGetIPFSEnabledFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.getIPFSEnabled", UNKNOWN) - - protected: - ~IpfsGetIPFSEnabledFunction() override {} - ResponseAction Run() override; -}; - -class IpfsGetResolveMethodTypeFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.getResolveMethodType", UNKNOWN) - - protected: - ~IpfsGetResolveMethodTypeFunction() override {} - ResponseAction Run() override; -}; - -class IpfsLaunchFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.launch", UNKNOWN) - - protected: - void OnLaunch(bool); - ~IpfsLaunchFunction() override {} - ResponseAction Run() override; -}; - -class IpfsShutdownFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.shutdown", UNKNOWN) - - protected: - void OnShutdown(bool); - ~IpfsShutdownFunction() override {} - ResponseAction Run() override; -}; - -class IpfsGetConfigFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.getConfig", UNKNOWN) - - protected: - void OnGetConfig(bool, const std::string& config); - ~IpfsGetConfigFunction() override {} - ResponseAction Run() override; -}; - -class IpfsGetExecutableAvailableFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.getExecutableAvailable", UNKNOWN) - - protected: - ~IpfsGetExecutableAvailableFunction() override {} - ResponseAction Run() override; -}; - -class IpfsResolveIPFSURIFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.resolveIPFSURI", UNKNOWN) - - protected: - ~IpfsResolveIPFSURIFunction() override {} - ResponseAction Run() override; -}; - -class IpfsValidateGatewayUrlFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.validateGatewayUrl", UNKNOWN) - - protected: - void OnGatewayValidated(bool success); - - ~IpfsValidateGatewayUrlFunction() override {} - ResponseAction Run() override; -}; - -class IpfsGetSettingsFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.getSettings", UNKNOWN) - - protected: - ~IpfsGetSettingsFunction() override {} - ResponseAction Run() override; -}; - -class IpfsSetPublicGatewayFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.setPublicGateway", UNKNOWN) - - protected: - ~IpfsSetPublicGatewayFunction() override {} - ResponseAction Run() override; -}; - -class IpfsSetPublicNFTGatewayFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.setPublicNFTGateway", UNKNOWN) - - protected: - ~IpfsSetPublicNFTGatewayFunction() override {} - ResponseAction Run() override; -}; - -class IpfsSetResolveMethodFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.setResolveMethod", UNKNOWN) - - protected: - ~IpfsSetResolveMethodFunction() override {} - ResponseAction Run() override; -}; - -class IpfsSetAutoRedirectToConfiguredGatewayEnabledFunction - : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.setAutoRedirectToConfiguredGatewayEnabled", - UNKNOWN) - - protected: - ~IpfsSetAutoRedirectToConfiguredGatewayEnabledFunction() override {} - ResponseAction Run() override; -}; - -class IpfsSetGatewayFallbackEnabledFunction : public ExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("ipfs.setGatewayFallbackEnabled", UNKNOWN) - - protected: - ~IpfsSetGatewayFallbackEnabledFunction() override {} - ResponseAction Run() override; -}; - -} // namespace api -} // namespace extensions - -#endif // BRAVE_BROWSER_EXTENSIONS_API_IPFS_API_H_ diff --git a/browser/extensions/api/ipfs_apitest.cc b/browser/extensions/api/ipfs_apitest.cc deleted file mode 100644 index 72b3121e2101..000000000000 --- a/browser/extensions/api/ipfs_apitest.cc +++ /dev/null @@ -1,325 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "base/files/file_util.h" -#include "base/path_service.h" -#include "base/test/scoped_feature_list.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/constants/brave_paths.h" -#include "brave/components/constants/pref_names.h" -#include "brave/components/ipfs/features.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "components/prefs/pref_service.h" -#include "content/public/test/browser_test.h" -#include "extensions/common/constants.h" -#include "extensions/test/result_catcher.h" - -namespace extensions { -namespace { - -// Actual config option string doesn't matter for tests -const char ipfs_config[] = "{ \"Identity\": {} }"; - -class IpfsExtensionApiTest : public ExtensionApiTest { - public: - IpfsExtensionApiTest() { - feature_list_.InitAndEnableFeature(ipfs::features::kIpfsFeature); - } - void SetUpOnMainThread() override { - ExtensionApiTest::SetUpOnMainThread(); - base::PathService::Get(brave::DIR_TEST_DATA, &extension_dir_); - extension_dir_ = extension_dir_.AppendASCII("extensions/api_test"); - } - void WriteConfigToFile() { - base::ScopedAllowBlockingForTesting allow_blocking; - ipfs::IpfsService* service = - ipfs::IpfsServiceFactory::GetInstance()->GetForContext(profile()); - base::FilePath path = service->GetConfigFilePath(); - ASSERT_TRUE(base::CreateDirectory(path.DirName())); - ASSERT_TRUE(base::WriteFile(path, ipfs_config)); - } - PrefService* GetPrefs() { return browser()->profile()->GetPrefs(); } - base::FilePath extension_dir_; - base::test::ScopedFeatureList feature_list_; -}; - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, IpfsCompanionHasAcces) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - ASSERT_TRUE(extension); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, "testBasics()")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, ExecutableAvailChangeIsReflected) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - ASSERT_TRUE(extension); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "executableAvailableChangeIsReflected(false)")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - - GetPrefs()->SetFilePath(kIPFSBinaryPath, - base::FilePath(FILE_PATH_LITERAL("some_path"))); - ASSERT_TRUE(extension); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "executableAvailableChangeIsReflected(true)")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, ResolveMethodChangeIsReflected) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)); - ASSERT_TRUE(extension); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "resolveMethodChangeIsReflected('local')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - - GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_DISABLED)); - ASSERT_TRUE(extension); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "resolveMethodChangeIsReflected('disabled')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - - GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - ASSERT_TRUE(extension); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "resolveMethodChangeIsReflected('gateway')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, GetConfig) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - ASSERT_TRUE(extension); - - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "getConfig(false, '')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - - WriteConfigToFile(); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - std::string("getConfig(true, '") + ipfs_config + "')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -// No great way to test launch and shutdown succeeding easily, so at least -// just make sure the API call works. IpfsService::SetAllowIpfsLaunchForTest -// is used to short-circuit the launch and shutdown process. -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, LaunchShutdownSuccess) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - ASSERT_TRUE(extension); - ipfs::IpfsService* service = - ipfs::IpfsServiceFactory::GetInstance()->GetForContext( - browser()->profile()); - ASSERT_TRUE(service); - - GetPrefs()->SetFilePath(kIPFSBinaryPath, - base::FilePath(FILE_PATH_LITERAL("some_path"))); - service->SetAllowIpfsLaunchForTest(true); - - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, "launchSuccess()")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - - service->SetAllowIpfsLaunchForTest(false); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, "shutdownSuccess()")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, LaunchFailWhenNotInstalled) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - ASSERT_TRUE(extension); - ipfs::IpfsService* service = - ipfs::IpfsServiceFactory::GetInstance()->GetForContext( - browser()->profile()); - ASSERT_TRUE(service); - - service->SetAllowIpfsLaunchForTest(true); - GetPrefs()->SetFilePath(kIPFSBinaryPath, base::FilePath()); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, "launchFail()")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, IpfsAPINotAvailable) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("notIpfsCompanion")); - ASSERT_TRUE(extension); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, ResolveIPFSURIMatches) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - ASSERT_TRUE(extension); - ipfs::IpfsService* service = - ipfs::IpfsServiceFactory::GetInstance()->GetForContext( - browser()->profile()); - ASSERT_TRUE(service); - - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "resolveIPFSURIMatches(" - "'ipfs://bafybeifk6th5qhox7pffjqjerbjxkpmsmufdcswdgacnmyv3fn53z2wgwe'," - "'https://bafybeifk6th5qhox7pffjqjerbjxkpmsmufdcswdgacnmyv3fn53z2wgwe" - ".ipfs.dweb.link/')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, IpfsPermissionAPIAccess) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ExtensionWithIpfsPermission")); - ASSERT_TRUE(extension); - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_persmission_extension_id, "testBasics()")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, GetSettings) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - ASSERT_TRUE(extension); - ipfs::IpfsService* service = - ipfs::IpfsServiceFactory::GetInstance()->GetForContext( - browser()->profile()); - ASSERT_TRUE(service); - - service->SetAllowIpfsLaunchForTest(true); - GetPrefs()->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, true); - GetPrefs()->SetBoolean(kIPFSAutoFallbackToGateway, true); - GetPrefs()->SetInteger(kIpfsStorageMax, 2); - - GetPrefs()->SetString(kIPFSPublicGatewayAddress, "https://a.b"); - GetPrefs()->SetString(kIPFSPublicNFTGatewayAddress, "https://a.b.c"); - GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_ASK)); - - std::string expected_json = - "{\"gateway_auto_fallback_enabled\": true, " - "\"auto_redirect_to_configured_gateway\": true, \"storage_max\": 2, " - "\"gateway_url\": \"https://a.b\", \"nft_gateway_url\": " - "\"https://a.b.c\", \"resolve_method\": \"ask\"}"; - - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - base::StringPrintf("getSettings('%s')", expected_json.c_str()))); - ASSERT_TRUE(catcher.GetNextResult()) << message_; -} - -IN_PROC_BROWSER_TEST_F(IpfsExtensionApiTest, SetSettings) { - ResultCatcher catcher; - const Extension* extension = - LoadExtension(extension_dir_.AppendASCII("ipfsCompanion")); - ASSERT_TRUE(extension); - ipfs::IpfsService* service = - ipfs::IpfsServiceFactory::GetInstance()->GetForContext( - browser()->profile()); - ASSERT_TRUE(service); - - service->SetAllowIpfsLaunchForTest(true); - - { - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "setPublicGateway('https://ipfs.io/')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - EXPECT_EQ(GetPrefs()->GetString(kIPFSPublicGatewayAddress), - "https://ipfs.io/"); - } - - { - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "setPublicNFTGateway('https://ipfs.io/')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - EXPECT_EQ(GetPrefs()->GetString(kIPFSPublicNFTGatewayAddress), - "https://ipfs.io/"); - } - - { - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "setResolveMethod('ask')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - EXPECT_EQ(GetPrefs()->GetInteger(kIPFSResolveMethod), - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_ASK)); - - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "setResolveMethod('local')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - EXPECT_EQ(GetPrefs()->GetInteger(kIPFSResolveMethod), - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)); - - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "setResolveMethod('gateway')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - EXPECT_EQ(GetPrefs()->GetInteger(kIPFSResolveMethod), - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "setResolveMethod('disabled')")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - EXPECT_EQ(GetPrefs()->GetInteger(kIPFSResolveMethod), - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_DISABLED)); - } - - { - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "setAutoRedirectToConfiguredGateway(true)")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - EXPECT_EQ(GetPrefs()->GetBoolean(kIPFSAutoRedirectToConfiguredGateway), - true); - } - - { - ASSERT_TRUE(browsertest_util::ExecuteScriptInBackgroundPageNoWait( - browser()->profile(), ipfs_companion_extension_id, - "setGatewayFallbackEnabled(true)")); - ASSERT_TRUE(catcher.GetNextResult()) << message_; - EXPECT_EQ(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway), true); - } -} - -} // namespace -} // namespace extensions diff --git a/browser/extensions/api/settings_private/brave_prefs_util.cc b/browser/extensions/api/settings_private/brave_prefs_util.cc index cd53aa553475..d792716e2769 100644 --- a/browser/extensions/api/settings_private/brave_prefs_util.cc +++ b/browser/extensions/api/settings_private/brave_prefs_util.cc @@ -21,7 +21,6 @@ #include "brave/components/de_amp/common/pref_names.h" #include "brave/components/debounce/core/common/pref_names.h" #include "brave/components/decentralized_dns/core/pref_names.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/ntp_background_images/common/pref_names.h" #include "brave/components/omnibox/browser/brave_omnibox_prefs.h" #include "brave/components/playlist/common/buildflags/buildflags.h" @@ -51,10 +50,6 @@ #include "brave/browser/ethereum_remote_client/pref_names.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/pref_names.h" -#endif - #if BUILDFLAG(ENABLE_AI_CHAT) #include "brave/components/ai_chat/core/browser/model_service.h" #include "brave/components/ai_chat/core/common/pref_names.h" @@ -244,9 +239,6 @@ const PrefsUtil::TypedPrefMap& BravePrefsUtil::GetAllowlistedKeys() { settings_api::PrefType::kBoolean; // Hangouts pref (*s_brave_allowlist)[kHangoutsEnabled] = settings_api::PrefType::kBoolean; - // IPFS Companion pref - (*s_brave_allowlist)[kIPFSCompanionEnabled] = - settings_api::PrefType::kBoolean; // Brave Wallet pref (*s_brave_allowlist)[kBraveWalletSelectedNetworks] = @@ -268,21 +260,6 @@ const PrefsUtil::TypedPrefMap& BravePrefsUtil::GetAllowlistedKeys() { (*s_brave_allowlist)[kBraveWalletPrivateWindowsEnabled] = settings_api::PrefType::kBoolean; - // IPFS pref -#if BUILDFLAG(ENABLE_IPFS) - (*s_brave_allowlist)[kIPFSResolveMethod] = settings_api::PrefType::kNumber; - (*s_brave_allowlist)[kIPFSAutoFallbackToGateway] = - settings_api::PrefType::kBoolean; - (*s_brave_allowlist)[kIPFSPublicGatewayAddress] = - settings_api::PrefType::kString; - (*s_brave_allowlist)[kIPFSPublicNFTGatewayAddress] = - settings_api::PrefType::kString; - (*s_brave_allowlist)[kIPFSAutoRedirectToConfiguredGateway] = - settings_api::PrefType::kBoolean; - (*s_brave_allowlist)[kIPFSAlwaysStartMode] = settings_api::PrefType::kBoolean; - (*s_brave_allowlist)[kIpfsStorageMax] = settings_api::PrefType::kNumber; -#endif - // Leo Assistant pref #if BUILDFLAG(ENABLE_AI_CHAT) (*s_brave_allowlist)[ai_chat::prefs::kBraveChatAutocompleteProviderEnabled] = @@ -324,9 +301,6 @@ const PrefsUtil::TypedPrefMap& BravePrefsUtil::GetAllowlistedKeys() { (*s_brave_allowlist)[kEnableMediaRouterOnRestart] = settings_api::PrefType::kBoolean; - // NFT pinning pref - (*s_brave_allowlist)[kAutoPinEnabled] = settings_api::PrefType::kBoolean; - #if defined(TOOLKIT_VIEWS) // Vertical tab strip prefs (*s_brave_allowlist)[brave_tabs::kVerticalTabsEnabled] = diff --git a/browser/extensions/brave_extension_management.cc b/browser/extensions/brave_extension_management.cc index 586516544996..1d99041be9cb 100644 --- a/browser/extensions/brave_extension_management.cc +++ b/browser/extensions/brave_extension_management.cc @@ -12,7 +12,6 @@ #include "brave/browser/extensions/brave_extension_provider.h" #include "brave/browser/tor/tor_profile_service_factory.h" #include "brave/components/constants/pref_names.h" -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/tor/buildflags/buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_management_internal.h" @@ -31,12 +30,6 @@ #include "brave/components/tor/pref_names.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/ipfs/brave_ipfs_client_updater.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "components/user_prefs/user_prefs.h" -#endif - #if BUILDFLAG(ETHEREUM_REMOTE_CLIENT_ENABLED) #include "brave/browser/ethereum_remote_client/ethereum_remote_client_constants.h" #endif @@ -74,21 +67,6 @@ BraveExtensionManagement::~BraveExtensionManagement() { local_state_pref_change_registrar_.RemoveAll(); } -void BraveExtensionManagement::OnExtensionLoaded( - content::BrowserContext* browser_context, - const Extension* extension) { - if (extension->id() == ipfs_companion_extension_id) - pref_service_->SetBoolean(kIPFSCompanionEnabled, true); -} - -void BraveExtensionManagement::OnExtensionUnloaded( - content::BrowserContext* browser_context, - const Extension* extension, - UnloadedExtensionReason reason) { - if (extension->id() == ipfs_companion_extension_id) - pref_service_->SetBoolean(kIPFSCompanionEnabled, false); -} - void BraveExtensionManagement::OnTorDisabledChanged() { #if BUILDFLAG(ENABLE_TOR) if (TorProfileServiceFactory::IsTorDisabled(profile_)) { @@ -121,12 +99,6 @@ void BraveExtensionManagement::Cleanup(content::BrowserContext* context) { OnTorDisabledChanged(); OnTorPluggableTransportChanged(); } - -#if BUILDFLAG(ENABLE_IPFS) - // Remove ipfs executable if it is disabled by GPO. - if (ipfs::IsIpfsDisabledByPolicy(user_prefs::UserPrefs::Get(context))) - g_brave_browser_process->ipfs_client_updater()->Cleanup(); -#endif } } // namespace extensions diff --git a/browser/extensions/brave_extension_management.h b/browser/extensions/brave_extension_management.h index 6c78ed980249..0fbbaea50785 100644 --- a/browser/extensions/brave_extension_management.h +++ b/browser/extensions/brave_extension_management.h @@ -23,15 +23,6 @@ class BraveExtensionManagement : public ExtensionManagement, ~BraveExtensionManagement() override; private: - // ExtensionRegistryObserver implementation. - void OnExtensionLoaded( - content::BrowserContext* browser_context, - const Extension* extension) override; - void OnExtensionUnloaded( - content::BrowserContext* browser_context, - const Extension* extension, - UnloadedExtensionReason reason) override; - void OnTorDisabledChanged(); void OnTorPluggableTransportChanged(); void Cleanup(content::BrowserContext* browser_context); diff --git a/browser/infobars/brave_global_confirm_infobar_delegate.cc b/browser/infobars/brave_global_confirm_infobar_delegate.cc deleted file mode 100644 index d6d5a1c390f6..000000000000 --- a/browser/infobars/brave_global_confirm_infobar_delegate.cc +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/infobars/brave_global_confirm_infobar_delegate.h" - -BraveGlobalConfirmInfobarDelegate::BraveGlobalConfirmInfobarDelegate() = - default; -BraveGlobalConfirmInfobarDelegate::~BraveGlobalConfirmInfobarDelegate() = - default; - -void BraveGlobalConfirmInfobarDelegate::AddObserver(Observer* obs) { - observer_list_.AddObserver(obs); -} - -void BraveGlobalConfirmInfobarDelegate::RemoveObserver(Observer* obs) { - observer_list_.RemoveObserver(obs); -} - -bool BraveGlobalConfirmInfobarDelegate::Accept() { - for (Observer& observer : observer_list_) { - observer.OnInfoBarClosed(); - } - - return true; -} - -bool BraveGlobalConfirmInfobarDelegate::Cancel() { - for (Observer& observer : observer_list_) { - observer.OnInfoBarClosed(); - } - - return true; -} - -void BraveGlobalConfirmInfobarDelegate::InfoBarDismissed() { - for (Observer& observer : observer_list_) { - observer.OnInfoBarClosed(); - } -} diff --git a/browser/infobars/brave_global_confirm_infobar_delegate.h b/browser/infobars/brave_global_confirm_infobar_delegate.h deleted file mode 100644 index 1fcf27d35fd9..000000000000 --- a/browser/infobars/brave_global_confirm_infobar_delegate.h +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_CONFIRM_INFOBAR_DELEGATE_H_ -#define BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_CONFIRM_INFOBAR_DELEGATE_H_ - -#include - -#include "brave/components/infobars/core/brave_confirm_infobar_delegate.h" - -class BraveGlobalConfirmInfobarDelegate : public BraveConfirmInfoBarDelegate { - public: - class Observer : public base::CheckedObserver { - public: - virtual void OnInfoBarClosed() = 0; - }; - - BraveGlobalConfirmInfobarDelegate(const BraveGlobalConfirmInfobarDelegate&) = - delete; - BraveGlobalConfirmInfobarDelegate& operator=( - const BraveGlobalConfirmInfobarDelegate&) = delete; - ~BraveGlobalConfirmInfobarDelegate() override; - - bool Accept() override; - bool Cancel() override; - void InfoBarDismissed() override; - - void AddObserver(Observer* obs); - void RemoveObserver(Observer* obs); - - protected: - BraveGlobalConfirmInfobarDelegate(); - - private: - base::ObserverList observer_list_; -}; - -class BraveGlobalConfirmInfoBarDelegateFactory { - public: - BraveGlobalConfirmInfoBarDelegateFactory( - const BraveGlobalConfirmInfoBarDelegateFactory&) = delete; - BraveGlobalConfirmInfoBarDelegateFactory& operator=( - const BraveGlobalConfirmInfoBarDelegateFactory&) = delete; - virtual ~BraveGlobalConfirmInfoBarDelegateFactory() = default; - - virtual std::unique_ptr Create() = 0; - virtual infobars::InfoBarDelegate::InfoBarIdentifier GetInfoBarIdentifier() - const = 0; - - protected: - BraveGlobalConfirmInfoBarDelegateFactory() = default; -}; - -#endif // BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_CONFIRM_INFOBAR_DELEGATE_H_ diff --git a/browser/infobars/brave_global_infobar_service.cc b/browser/infobars/brave_global_infobar_service.cc deleted file mode 100644 index f105b047a23a..000000000000 --- a/browser/infobars/brave_global_infobar_service.cc +++ /dev/null @@ -1,35 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/infobars/brave_global_infobar_service.h" - -#include - -#include "base/containers/contains.h" -#include "brave/browser/infobars/brave_ipfs_always_start_infobar_delegate.h" -#include "brave/browser/ui/views/infobars/brave_global_infobar_manager.h" -#include "components/infobars/core/infobar_delegate.h" - -BraveGlobalInfobarService::BraveGlobalInfobarService(PrefService* prefs) - : prefs_(prefs) { - infobar_managers_[infobars::InfoBarDelegate::InfoBarIdentifier:: - BRAVE_IPFS_ALWAYS_START_INFOBAR_DELEGATE] = - std::make_unique( - std::make_unique(prefs)); -} - -BraveGlobalInfobarService::~BraveGlobalInfobarService() = default; - -void BraveGlobalInfobarService::ShowAlwaysStartInfobar() { - const auto ib_type = infobars::InfoBarDelegate::InfoBarIdentifier:: - BRAVE_IPFS_ALWAYS_START_INFOBAR_DELEGATE; - const bool is_exists = base::Contains(infobar_managers_, ib_type); - DCHECK(is_exists); - if (!is_exists) { - return; - } - - infobar_managers_[ib_type]->Show(); -} diff --git a/browser/infobars/brave_global_infobar_service.h b/browser/infobars/brave_global_infobar_service.h deleted file mode 100644 index f294128ba251..000000000000 --- a/browser/infobars/brave_global_infobar_service.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_INFOBAR_SERVICE_H_ -#define BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_INFOBAR_SERVICE_H_ - -#include -#include - -#include "components/infobars/core/infobar_delegate.h" -#include "components/keyed_service/core/keyed_service.h" - -class BraveGlobalInfoBarManager; -class PrefService; - -class BraveGlobalInfobarService : public KeyedService { - public: - explicit BraveGlobalInfobarService(PrefService* prefs); - ~BraveGlobalInfobarService() override; - - BraveGlobalInfobarService(const BraveGlobalInfobarService&) = delete; - BraveGlobalInfobarService& operator=(const BraveGlobalInfobarService&) = - delete; - - void ShowAlwaysStartInfobar(); - - private: - std::map> - infobar_managers_; - raw_ptr prefs_ = nullptr; -}; - -#endif // BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_INFOBAR_SERVICE_H_ diff --git a/browser/infobars/brave_global_infobar_service_factory.cc b/browser/infobars/brave_global_infobar_service_factory.cc deleted file mode 100644 index fe65520796f3..000000000000 --- a/browser/infobars/brave_global_infobar_service_factory.cc +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/infobars/brave_global_infobar_service_factory.h" - -#include "brave/browser/infobars/brave_global_infobar_service.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_context.h" - -// static -BraveGlobalInfobarServiceFactory* -BraveGlobalInfobarServiceFactory::GetInstance() { - static base::NoDestructor instance; - return instance.get(); -} - -// static -BraveGlobalInfobarService* -BraveGlobalInfobarServiceFactory::GetForBrowserContext( - content::BrowserContext* context) { - return static_cast( - GetInstance()->GetServiceForBrowserContext(context, true)); -} - -BraveGlobalInfobarServiceFactory::BraveGlobalInfobarServiceFactory() - : BrowserContextKeyedServiceFactory( - "BraveGlobalInfobarService", - BrowserContextDependencyManager::GetInstance()) {} - -BraveGlobalInfobarServiceFactory::~BraveGlobalInfobarServiceFactory() = default; - -KeyedService* BraveGlobalInfobarServiceFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - return new BraveGlobalInfobarService(user_prefs::UserPrefs::Get(context)); -} diff --git a/browser/infobars/brave_global_infobar_service_factory.h b/browser/infobars/brave_global_infobar_service_factory.h deleted file mode 100644 index 7e2f333d9876..000000000000 --- a/browser/infobars/brave_global_infobar_service_factory.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_INFOBAR_SERVICE_FACTORY_H_ -#define BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_INFOBAR_SERVICE_FACTORY_H_ - -#include "base/no_destructor.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -class BraveGlobalInfobarService; - -class BraveGlobalInfobarServiceFactory - : public BrowserContextKeyedServiceFactory { - public: - static BraveGlobalInfobarServiceFactory* GetInstance(); - static BraveGlobalInfobarService* GetForBrowserContext( - content::BrowserContext* context); - - BraveGlobalInfobarServiceFactory(const BraveGlobalInfobarServiceFactory&) = - delete; - BraveGlobalInfobarServiceFactory& operator=( - const BraveGlobalInfobarServiceFactory&) = delete; - - private: - friend base::NoDestructor; - BraveGlobalInfobarServiceFactory(); - ~BraveGlobalInfobarServiceFactory() override; - - // BrowserContextKeyedServiceFactory overrides: - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; -}; - -#endif // BRAVE_BROWSER_INFOBARS_BRAVE_GLOBAL_INFOBAR_SERVICE_FACTORY_H_ diff --git a/browser/infobars/brave_ipfs_always_start_infobar_delegate.cc b/browser/infobars/brave_ipfs_always_start_infobar_delegate.cc deleted file mode 100644 index b85e595c0cd3..000000000000 --- a/browser/infobars/brave_ipfs_always_start_infobar_delegate.cc +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/infobars/brave_ipfs_always_start_infobar_delegate.h" - -#include "base/memory/ptr_util.h" -#include "brave/components/ipfs/pref_names.h" -#include "brave/components/l10n/common/localization_util.h" -#include "brave/grit/brave_generated_resources.h" -#include "components/prefs/pref_service.h" - -BraveIPFSAlwaysStartInfoBarDelegateFactory:: - BraveIPFSAlwaysStartInfoBarDelegateFactory(PrefService* local_state) - : local_state_(local_state) {} - -std::unique_ptr -BraveIPFSAlwaysStartInfoBarDelegateFactory::Create() { - if (!local_state_ || local_state_->GetBoolean(kIPFSAlwaysStartMode)) { - return nullptr; - } - - if (local_state_->GetBoolean(kIPFSAlwaysStartInfobarShown)) { - return nullptr; - } - - return base::WrapUnique( - new BraveIPFSAlwaysStartInfoBarDelegate(local_state_)); -} - -infobars::InfoBarDelegate::InfoBarIdentifier -BraveIPFSAlwaysStartInfoBarDelegateFactory::GetInfoBarIdentifier() const { - return BraveConfirmInfoBarDelegate::BRAVE_IPFS_ALWAYS_START_INFOBAR_DELEGATE; -} - -BraveIPFSAlwaysStartInfoBarDelegate::BraveIPFSAlwaysStartInfoBarDelegate( - PrefService* local_state) - : local_state_(local_state) {} - -BraveIPFSAlwaysStartInfoBarDelegate::~BraveIPFSAlwaysStartInfoBarDelegate() = - default; - -// ConfirmInfoBarDelegate -infobars::InfoBarDelegate::InfoBarIdentifier -BraveIPFSAlwaysStartInfoBarDelegate::GetIdentifier() const { - return BRAVE_IPFS_ALWAYS_START_INFOBAR_DELEGATE; -} - -std::u16string BraveIPFSAlwaysStartInfoBarDelegate::GetMessageText() const { - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_ALWAYS_START_INFOBAR_TEXT); -} - -int BraveIPFSAlwaysStartInfoBarDelegate::GetButtons() const { - return BUTTON_OK | BUTTON_CANCEL; -} - -std::vector BraveIPFSAlwaysStartInfoBarDelegate::GetButtonsOrder() const { - return {BUTTON_OK, BUTTON_CANCEL}; -} - -std::u16string BraveIPFSAlwaysStartInfoBarDelegate::GetButtonLabel( - InfoBarButton button) const { - if (button == BUTTON_CANCEL) { - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_ALWAYS_START_INFOBAR_NO); - } - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_ALWAYS_START_INFOBAR_OK); -} - -bool BraveIPFSAlwaysStartInfoBarDelegate::Accept() { - if (local_state_) { - local_state_->SetBoolean(kIPFSAlwaysStartMode, true); - } - SetLastShownTime(); - return BraveGlobalConfirmInfobarDelegate::Accept(); -} - -bool BraveIPFSAlwaysStartInfoBarDelegate::Cancel() { - SetLastShownTime(); - return BraveGlobalConfirmInfobarDelegate::Cancel(); -} - -void BraveIPFSAlwaysStartInfoBarDelegate::InfoBarDismissed() { - SetLastShownTime(); - BraveGlobalConfirmInfobarDelegate::InfoBarDismissed(); -} - -void BraveIPFSAlwaysStartInfoBarDelegate::SetLastShownTime() { - if (!local_state_) { - return; - } - local_state_->SetBoolean(kIPFSAlwaysStartInfobarShown, true); -} diff --git a/browser/infobars/brave_ipfs_always_start_infobar_delegate.h b/browser/infobars/brave_ipfs_always_start_infobar_delegate.h deleted file mode 100644 index a721ed210040..000000000000 --- a/browser/infobars/brave_ipfs_always_start_infobar_delegate.h +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_ALWAYS_START_INFOBAR_DELEGATE_H_ -#define BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_ALWAYS_START_INFOBAR_DELEGATE_H_ - -#include -#include -#include - -#include "base/functional/callback.h" -#include "brave/browser/infobars/brave_global_confirm_infobar_delegate.h" - -class PrefService; - -class BraveIPFSAlwaysStartInfoBarDelegate - : public BraveGlobalConfirmInfobarDelegate { - public: - BraveIPFSAlwaysStartInfoBarDelegate( - const BraveIPFSAlwaysStartInfoBarDelegate&) = delete; - BraveIPFSAlwaysStartInfoBarDelegate& operator=( - const BraveIPFSAlwaysStartInfoBarDelegate&) = delete; - ~BraveIPFSAlwaysStartInfoBarDelegate() override; - - private: - friend class BraveIPFSAlwaysStartInfoBarDelegateFactory; - explicit BraveIPFSAlwaysStartInfoBarDelegate(PrefService* local_state); - - // BraveConfirmInfoBarDelegate - infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; - std::u16string GetMessageText() const override; - int GetButtons() const override; - std::u16string GetButtonLabel(InfoBarButton button) const override; - std::vector GetButtonsOrder() const override; - - bool Accept() override; - bool Cancel() override; - void InfoBarDismissed() override; - - void SetLastShownTime(); - - raw_ptr local_state_ = nullptr; -}; - -class BraveIPFSAlwaysStartInfoBarDelegateFactory - : public BraveGlobalConfirmInfoBarDelegateFactory { - public: - explicit BraveIPFSAlwaysStartInfoBarDelegateFactory(PrefService* local_state); - ~BraveIPFSAlwaysStartInfoBarDelegateFactory() override = default; - - std::unique_ptr Create() override; - infobars::InfoBarDelegate::InfoBarIdentifier GetInfoBarIdentifier() - const override; - - private: - raw_ptr local_state_ = nullptr; -}; - -#endif // BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_ALWAYS_START_INFOBAR_DELEGATE_H_ diff --git a/browser/infobars/brave_ipfs_fallback_infobar_delegate.cc b/browser/infobars/brave_ipfs_fallback_infobar_delegate.cc deleted file mode 100644 index 968eb91d60ef..000000000000 --- a/browser/infobars/brave_ipfs_fallback_infobar_delegate.cc +++ /dev/null @@ -1,108 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/infobars/brave_ipfs_fallback_infobar_delegate.h" - -#include - -#include "brave/browser/infobars/brave_confirm_infobar_creator.h" -#include "brave/components/l10n/common/localization_util.h" -#include "brave/components/vector_icons/vector_icons.h" -#include "brave/grit/brave_generated_resources.h" -#include "components/infobars/core/infobar.h" - -// BraveIPFSFallbackInfoBarDelegateObserver -BraveIPFSFallbackInfoBarDelegateObserver:: - BraveIPFSFallbackInfoBarDelegateObserver() = default; -BraveIPFSFallbackInfoBarDelegateObserver:: - ~BraveIPFSFallbackInfoBarDelegateObserver() = default; - -// BraveIPFSFallbackInfoBarDelegate -// static -void BraveIPFSFallbackInfoBarDelegate::Create( - infobars::ContentInfoBarManager* infobar_manager, - std::unique_ptr observer, - PrefService* local_state) { - infobar_manager->AddInfoBar( - CreateBraveConfirmInfoBar(std::unique_ptr( - new BraveIPFSFallbackInfoBarDelegate(std::move(observer), - local_state))), - true); -} - -BraveIPFSFallbackInfoBarDelegate::BraveIPFSFallbackInfoBarDelegate( - std::unique_ptr observer, - PrefService* local_state) - : observer_(std::move(observer)), local_state_(local_state) {} - -BraveIPFSFallbackInfoBarDelegate::~BraveIPFSFallbackInfoBarDelegate() = default; - -// BraveConfirmInfoBarDelegate -bool BraveIPFSFallbackInfoBarDelegate::HasCheckbox() const { - return false; -} - -std::u16string BraveIPFSFallbackInfoBarDelegate::GetCheckboxText() const { - NOTREACHED_NORETURN(); -} - -void BraveIPFSFallbackInfoBarDelegate::SetCheckboxChecked(bool checked) { - NOTREACHED_IN_MIGRATION(); -} - -bool BraveIPFSFallbackInfoBarDelegate::InterceptClosing() { - return false; -} - -// ConfirmInfoBarDelegate -infobars::InfoBarDelegate::InfoBarIdentifier -BraveIPFSFallbackInfoBarDelegate::GetIdentifier() const { - return BRAVE_IPFS_FALLBACK_INFOBAR_DELEGATE; -} - -const gfx::VectorIcon& BraveIPFSFallbackInfoBarDelegate::GetVectorIcon() const { - return kLeoInfoOutlineIcon; -} - -bool BraveIPFSFallbackInfoBarDelegate::ShouldExpire( - const NavigationDetails& details) const { - return details.is_navigation_to_different_page; -} - -void BraveIPFSFallbackInfoBarDelegate::InfoBarDismissed() {} - -std::u16string BraveIPFSFallbackInfoBarDelegate::GetMessageText() const { - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_FALLBACK_INFOBAR_TEXT); -} - -int BraveIPFSFallbackInfoBarDelegate::GetButtons() const { - return BUTTON_OK | BUTTON_CANCEL; -} - -std::vector BraveIPFSFallbackInfoBarDelegate::GetButtonsOrder() const { - return {InfoBarButton::BUTTON_OK, InfoBarButton::BUTTON_CANCEL}; -} - -std::u16string BraveIPFSFallbackInfoBarDelegate::GetButtonLabel( - InfoBarButton button) const { - if (button == BUTTON_CANCEL) { - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_FALLBACK_INFOBAR_NO); - } - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_FALLBACK_REDIRECT); -} - -bool BraveIPFSFallbackInfoBarDelegate::Accept() { - if (observer_) { - observer_->OnRedirectToOriginalAddress(); - } - return true; -} - -bool BraveIPFSFallbackInfoBarDelegate::Cancel() { - return true; -} diff --git a/browser/infobars/brave_ipfs_fallback_infobar_delegate.h b/browser/infobars/brave_ipfs_fallback_infobar_delegate.h deleted file mode 100644 index f04fe37c69c7..000000000000 --- a/browser/infobars/brave_ipfs_fallback_infobar_delegate.h +++ /dev/null @@ -1,69 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_FALLBACK_INFOBAR_DELEGATE_H_ -#define BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_FALLBACK_INFOBAR_DELEGATE_H_ - -#include -#include - -#include "brave/components/infobars/core/brave_confirm_infobar_delegate.h" -#include "components/infobars/content/content_infobar_manager.h" - -class PrefService; - -namespace infobars { -class ContentInfoBarManager; -} // namespace infobars - -class BraveIPFSFallbackInfoBarDelegateObserver { - public: - BraveIPFSFallbackInfoBarDelegateObserver(); - virtual void OnRedirectToOriginalAddress() = 0; - virtual ~BraveIPFSFallbackInfoBarDelegateObserver(); -}; - -class BraveIPFSFallbackInfoBarDelegate : public BraveConfirmInfoBarDelegate { - public: - BraveIPFSFallbackInfoBarDelegate(const BraveIPFSFallbackInfoBarDelegate&) = - delete; - BraveIPFSFallbackInfoBarDelegate& operator=( - const BraveIPFSFallbackInfoBarDelegate&) = delete; - - static void Create( - infobars::ContentInfoBarManager* infobar_manager, - std::unique_ptr observer, - PrefService* local_state); - - private: - explicit BraveIPFSFallbackInfoBarDelegate( - std::unique_ptr observer, - PrefService* local_state); - ~BraveIPFSFallbackInfoBarDelegate() override; - - // BraveConfirmInfoBarDelegate - bool HasCheckbox() const override; - std::u16string GetCheckboxText() const override; - void SetCheckboxChecked(bool checked) override; - bool InterceptClosing() override; - - // ConfirmInfoBarDelegate - infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; - const gfx::VectorIcon& GetVectorIcon() const override; - bool ShouldExpire(const NavigationDetails& details) const override; - void InfoBarDismissed() override; - std::u16string GetMessageText() const override; - int GetButtons() const override; - std::u16string GetButtonLabel(InfoBarButton button) const override; - std::vector GetButtonsOrder() const override; - - bool Accept() override; - bool Cancel() override; - - std::unique_ptr observer_; - raw_ptr local_state_ = nullptr; -}; - -#endif // BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_FALLBACK_INFOBAR_DELEGATE_H_ diff --git a/browser/infobars/brave_ipfs_infobar_delegate.cc b/browser/infobars/brave_ipfs_infobar_delegate.cc deleted file mode 100644 index c46d351c1fce..000000000000 --- a/browser/infobars/brave_ipfs_infobar_delegate.cc +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/infobars/brave_ipfs_infobar_delegate.h" - -#include -#include - -#include "brave/browser/ui/views/infobars/brave_confirm_infobar.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/pref_names.h" -#include "brave/components/l10n/common/localization_util.h" -#include "brave/grit/brave_generated_resources.h" -#include "components/infobars/core/infobar.h" -#include "components/prefs/pref_service.h" -#include "ui/views/vector_icons.h" - -// BraveIPFSInfoBarDelegateObserver -BraveIPFSInfoBarDelegateObserver::BraveIPFSInfoBarDelegateObserver() = default; - -BraveIPFSInfoBarDelegateObserver::~BraveIPFSInfoBarDelegateObserver() = default; - -// BraveIPFSInfoBarDelegate -// static -void BraveIPFSInfoBarDelegate::Create( - infobars::ContentInfoBarManager* infobar_manager, - std::unique_ptr observer, - PrefService* local_state) { - if (!local_state->GetBoolean(kShowIPFSPromoInfobar)) { - return; - } - infobar_manager->AddInfoBar(std::make_unique( - std::make_unique( - std::move(observer), local_state)), - true); -} - -BraveIPFSInfoBarDelegate::BraveIPFSInfoBarDelegate( - std::unique_ptr observer, - PrefService* local_state) - : observer_(std::move(observer)), local_state_(local_state) {} - -BraveIPFSInfoBarDelegate::~BraveIPFSInfoBarDelegate() {} - -// BraveConfirmInfoBarDelegate -bool BraveIPFSInfoBarDelegate::HasCheckbox() const { - return false; -} - -std::u16string BraveIPFSInfoBarDelegate::GetCheckboxText() const { - NOTREACHED_NORETURN(); -} - -void BraveIPFSInfoBarDelegate::SetCheckboxChecked(bool checked) { - NOTREACHED_IN_MIGRATION(); -} - -bool BraveIPFSInfoBarDelegate::InterceptClosing() { - return false; -} - -// ConfirmInfoBarDelegate -infobars::InfoBarDelegate::InfoBarIdentifier -BraveIPFSInfoBarDelegate::GetIdentifier() const { - return BRAVE_IPFS_INFOBAR_DELEGATE; -} - -const gfx::VectorIcon& BraveIPFSInfoBarDelegate::GetVectorIcon() const { - return views::kInfoIcon; -} - -bool BraveIPFSInfoBarDelegate::ShouldExpire( - const NavigationDetails& details) const { - return details.is_navigation_to_different_page; -} - -void BraveIPFSInfoBarDelegate::InfoBarDismissed() {} - -std::u16string BraveIPFSInfoBarDelegate::GetMessageText() const { - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_INFOBAR_TEXT); -} - -int BraveIPFSInfoBarDelegate::GetButtons() const { - return BUTTON_OK | BUTTON_CANCEL | BUTTON_EXTRA; -} - -bool BraveIPFSInfoBarDelegate::IsProminent(int id) const { - return id == BUTTON_OK || id == BUTTON_EXTRA; -} - -std::u16string BraveIPFSInfoBarDelegate::GetButtonLabel( - InfoBarButton button) const { - switch (button) { - case InfoBarButton::BUTTON_OK: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_INFOBAR_APPROVE); - case InfoBarButton::BUTTON_EXTRA: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_INFOBAR_APPROVE_ONCE); - case InfoBarButton::BUTTON_CANCEL: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_INFOBAR_NEVER); - default: - NOTREACHED_NORETURN(); - } -} - -std::vector BraveIPFSInfoBarDelegate::GetButtonsOrder() const { - return {InfoBarButton::BUTTON_OK, InfoBarButton::BUTTON_EXTRA, - InfoBarButton::BUTTON_CANCEL}; -} - -std::u16string BraveIPFSInfoBarDelegate::GetLinkText() const { - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_BRAVE_IPFS_INFOBAR_LINK); -} - -GURL BraveIPFSInfoBarDelegate::GetLinkURL() const { - return GURL(ipfs::kIPFSLearnMorePrivacyURL); -} - -bool BraveIPFSInfoBarDelegate::Accept() { - if (observer_) { - local_state_->SetBoolean(kShowIPFSPromoInfobar, false); - observer_->OnRedirectToIPFS(true); - } - return true; -} - -bool BraveIPFSInfoBarDelegate::ExtraButtonPressed() { - if (observer_) { - observer_->OnRedirectToIPFS(false); - } - return true; -} - -bool BraveIPFSInfoBarDelegate::Cancel() { - local_state_->SetBoolean(kShowIPFSPromoInfobar, false); - return true; -} diff --git a/browser/infobars/brave_ipfs_infobar_delegate.h b/browser/infobars/brave_ipfs_infobar_delegate.h deleted file mode 100644 index 71a25043af33..000000000000 --- a/browser/infobars/brave_ipfs_infobar_delegate.h +++ /dev/null @@ -1,73 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_INFOBAR_DELEGATE_H_ -#define BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_INFOBAR_DELEGATE_H_ - -#include -#include - -#include "base/compiler_specific.h" -#include "base/memory/raw_ptr.h" -#include "brave/components/infobars/core/brave_confirm_infobar_delegate.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "url/gurl.h" - -class PrefService; - -namespace infobars { -class ContentInfoBarManager; -} // namespace infobars - -class BraveIPFSInfoBarDelegateObserver { - public: - BraveIPFSInfoBarDelegateObserver(); - virtual void OnRedirectToIPFS(bool remember) = 0; - virtual ~BraveIPFSInfoBarDelegateObserver(); -}; - -class BraveIPFSInfoBarDelegate : public BraveConfirmInfoBarDelegate { - public: - BraveIPFSInfoBarDelegate(const BraveIPFSInfoBarDelegate&) = delete; - BraveIPFSInfoBarDelegate& operator=(const BraveIPFSInfoBarDelegate&) = delete; - - BraveIPFSInfoBarDelegate( - std::unique_ptr observer, - PrefService* local_state); - ~BraveIPFSInfoBarDelegate() override; - - static void Create(infobars::ContentInfoBarManager* infobar_manager, - std::unique_ptr observer, - PrefService* local_state); - - private: - // BraveConfirmInfoBarDelegate - bool HasCheckbox() const override; - std::u16string GetCheckboxText() const override; - void SetCheckboxChecked(bool checked) override; - bool InterceptClosing() override; - - // ConfirmInfoBarDelegate - infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; - const gfx::VectorIcon& GetVectorIcon() const override; - bool ShouldExpire(const NavigationDetails& details) const override; - void InfoBarDismissed() override; - std::u16string GetMessageText() const override; - int GetButtons() const override; - std::vector GetButtonsOrder() const override; - bool IsProminent(int id) const override; - std::u16string GetButtonLabel(InfoBarButton button) const override; - std::u16string GetLinkText() const override; - GURL GetLinkURL() const override; - - bool Accept() override; - bool Cancel() override; - bool ExtraButtonPressed() override; - - std::unique_ptr observer_; - raw_ptr local_state_ = nullptr; -}; - -#endif // BRAVE_BROWSER_INFOBARS_BRAVE_IPFS_INFOBAR_DELEGATE_H_ diff --git a/browser/infobars/sources.gni b/browser/infobars/sources.gni index 0e33c2f3dd8e..9aa9810fedb4 100644 --- a/browser/infobars/sources.gni +++ b/browser/infobars/sources.gni @@ -3,7 +3,6 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//build/config/features.gni") brave_browser_infobar_sources = [] @@ -14,12 +13,6 @@ if (!is_android) { "//brave/browser/infobars/brave_confirm_infobar_creator.h", "//brave/browser/infobars/brave_confirm_p3a_infobar_delegate.cc", "//brave/browser/infobars/brave_confirm_p3a_infobar_delegate.h", - "//brave/browser/infobars/brave_global_confirm_infobar_delegate.cc", - "//brave/browser/infobars/brave_global_confirm_infobar_delegate.h", - "//brave/browser/infobars/brave_global_infobar_service.cc", - "//brave/browser/infobars/brave_global_infobar_service.h", - "//brave/browser/infobars/brave_global_infobar_service_factory.cc", - "//brave/browser/infobars/brave_global_infobar_service_factory.h", "//brave/browser/infobars/brave_sync_account_deleted_infobar_delegate.cc", "//brave/browser/infobars/brave_sync_account_deleted_infobar_delegate.h", "//brave/browser/infobars/dev_channel_deprecation_infobar_delegate.cc", @@ -37,6 +30,7 @@ if (!is_android) { "//brave/components/brave_sync:features", "//brave/components/brave_sync:prefs", "//brave/components/constants", + "//brave/components/infobars/core:core", "//brave/components/p3a", "//chrome/app:branded_strings", "//chrome/browser/ui", @@ -48,21 +42,4 @@ if (!is_android) { "//ui/views", "//url", ] - - if (enable_ipfs) { - brave_browser_infobar_sources += [ - "//brave/browser/infobars/brave_ipfs_always_start_infobar_delegate.cc", - "//brave/browser/infobars/brave_ipfs_always_start_infobar_delegate.h", - "//brave/browser/infobars/brave_ipfs_fallback_infobar_delegate.cc", - "//brave/browser/infobars/brave_ipfs_fallback_infobar_delegate.h", - "//brave/browser/infobars/brave_ipfs_infobar_delegate.cc", - "//brave/browser/infobars/brave_ipfs_infobar_delegate.h", - ] - brave_browser_infobar_deps += [ - "//brave/components/infobars/core:core", - "//brave/components/ipfs", - "//brave/components/vector_icons", - "//components/user_prefs", - ] - } } diff --git a/browser/ipfs/content_browser_client_helper.cc b/browser/ipfs/content_browser_client_helper.cc deleted file mode 100644 index 38dde6fd9b09..000000000000 --- a/browser/ipfs/content_browser_client_helper.cc +++ /dev/null @@ -1,165 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/content_browser_client_helper.h" - -#include -#include - -#include "base/strings/string_util.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/browser/profiles/profile_util.h" -#include "brave/components/constants/url_constants.h" -#include "brave/components/constants/webui_url_constants.h" -#include "brave/components/decentralized_dns/core/utils.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/external_protocol/external_protocol_handler.h" -#include "chrome/common/channel_info.h" -#include "components/prefs/pref_service.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/browser/render_view_host.h" -#include "content/public/common/url_constants.h" -#include "url/gurl.h" - -namespace { - -constexpr char kIpfsLocalhost[] = ".ipfs.localhost"; -constexpr char kIpnsLocalhost[] = ".ipns.localhost"; - -bool IsIPFSLocalGateway(PrefService* prefs) { - auto resolve_method = static_cast( - prefs->GetInteger(kIPFSResolveMethod)); - return resolve_method == ipfs::IPFSResolveMethodTypes::IPFS_LOCAL; -} - -std::size_t GetIPFSCidOrHostEndPos(GURL const* url, - const std::size_t& ipfs_pos, - const std::size_t& ipns_pos) { - if (ipfs_pos != std::string::npos) { - return ipfs_pos; - } - - if (ipns_pos != std::string::npos) { - return ipns_pos; - } - - return url->host().length(); -} - -} // namespace - -namespace ipfs { - -bool HandleIPFSURLRewrite(GURL* url, content::BrowserContext* browser_context) { - if (!brave::IsRegularProfile(browser_context)) { - return false; - } - // This is needed for triggering ReverseRewrite later. - if (url->SchemeIs("http") && - (base::EndsWith(url->host_piece(), kIpfsLocalhost) || - base::EndsWith(url->host_piece(), kIpnsLocalhost))) { - return true; - } -#if BUILDFLAG(ENABLE_IPFS_INTERNALS_WEBUI) - if (url->SchemeIs(content::kChromeUIScheme) && url->DomainIs(kIPFSScheme)) { - GURL::Replacements host_replacements; - host_replacements.SetHostStr(kIPFSWebUIHost); - *url = url->ReplaceComponents(host_replacements); - return true; - } -#endif - PrefService* prefs = user_prefs::UserPrefs::Get(browser_context); - if (!IsIpfsResolveMethodDisabled(prefs) && - // When it's not the local gateway we don't want to show a ipfs:// URL. - // We instead will translate the URL later. - IsIPFSLocalGateway(prefs) && - (url->SchemeIs(kIPFSScheme) || url->SchemeIs(kIPNSScheme))) { - return TranslateIPFSURI( - *url, url, GetDefaultIPFSLocalGateway(chrome::GetChannel()), false); - } - - if (url->DomainIs(kLocalhostIP)) { - GURL::Replacements replacements; - replacements.SetHostStr(kLocalhostDomain); - if (IsDefaultGatewayURL(url->ReplaceComponents(replacements), prefs)) { - *url = url->ReplaceComponents(replacements); - return true; - } - } - - if (IsLocalGatewayConfigured(prefs)) { - if (decentralized_dns::IsENSTLD(url->host_piece()) && - decentralized_dns::IsENSResolveMethodEnabled( - g_browser_process->local_state())) { - return true; - } - - if (decentralized_dns::IsSnsTLD(url->host_piece()) && - decentralized_dns::IsSnsResolveMethodEnabled( - g_browser_process->local_state())) { - return true; - } - - if (decentralized_dns::IsUnstoppableDomainsTLD(url->host_piece()) && - decentralized_dns::IsUnstoppableDomainsResolveMethodEnabled( - g_browser_process->local_state())) { - return true; - } - } - - return false; -} - -bool HandleIPFSURLReverseRewrite(GURL* url, - content::BrowserContext* browser_context) { -#if BUILDFLAG(ENABLE_IPFS_INTERNALS_WEBUI) - if (url->SchemeIs(content::kChromeUIScheme) && - url->DomainIs(kIPFSWebUIHost)) { - return true; - } -#endif - - std::size_t ipfs_pos = url->host_piece().find(kIpfsLocalhost); - std::size_t ipns_pos = url->host_piece().find(kIpnsLocalhost); - - if (ipfs_pos == std::string::npos && ipns_pos == std::string::npos) - return false; - - const auto decoded_host = ipfs::DecodeSingleLabelForm( - url->host().substr(0, GetIPFSCidOrHostEndPos(url, ipfs_pos, ipns_pos))); - - if (!ipfs::IsValidCIDOrDomain(decoded_host)) { - return false; - } - - GURL configured_gateway = GetConfiguredBaseGateway( - user_prefs::UserPrefs::Get(browser_context), chrome::GetChannel()); - if (configured_gateway.port() != url->port()) - return false; - GURL::Replacements scheme_replacements; - GURL::Replacements host_replacements; - if (ipfs_pos != std::string::npos) { - scheme_replacements.SetSchemeStr(kIPFSScheme); - host_replacements.SetHostStr(url->host_piece().substr(0, ipfs_pos)); - host_replacements.ClearPort(); - } else { // ipns - scheme_replacements.SetSchemeStr(kIPNSScheme); - host_replacements.SetHostStr(decoded_host); - host_replacements.ClearPort(); - } - - *url = url->ReplaceComponents(host_replacements); - *url = url->ReplaceComponents(scheme_replacements); - return true; -} - -} // namespace ipfs diff --git a/browser/ipfs/content_browser_client_helper.h b/browser/ipfs/content_browser_client_helper.h deleted file mode 100644 index a2bd1521d2c7..000000000000 --- a/browser/ipfs/content_browser_client_helper.h +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_CONTENT_BROWSER_CLIENT_HELPER_H_ -#define BRAVE_BROWSER_IPFS_CONTENT_BROWSER_CLIENT_HELPER_H_ - -#include - -#include "content/public/browser/web_contents.h" - -class GURL; - -namespace content { -class BrowserContext; -} // namespace content - -namespace url { -class Origin; -} // namespace url - -namespace ipfs { - -bool HandleIPFSURLReverseRewrite( - GURL* url, - content::BrowserContext* browser_context); - -void LoadOrLaunchIPFSURL(const GURL& url, - content::WebContents::OnceGetter web_contents_getter, - ui::PageTransition page_transition, - bool has_user_gesture, - const std::optional& initiating_origin); - -bool HandleIPFSURLRewrite(GURL* url, - content::BrowserContext* browser_context); - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_CONTENT_BROWSER_CLIENT_HELPER_H_ diff --git a/browser/ipfs/content_browser_client_helper_unittest.cc b/browser/ipfs/content_browser_client_helper_unittest.cc deleted file mode 100644 index cb11f4ea49d8..000000000000 --- a/browser/ipfs/content_browser_client_helper_unittest.cc +++ /dev/null @@ -1,397 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/content_browser_client_helper.h" - -#include -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/test/bind.h" -#include "base/test/scoped_feature_list.h" -#include "brave/components/constants/webui_url_constants.h" -#include "brave/components/decentralized_dns/core/constants.h" -#include "brave/components/decentralized_dns/core/pref_names.h" -#include "brave/components/decentralized_dns/core/utils.h" -#include "brave/components/ipfs/features.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_ports.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/prefs/browser_prefs.h" -#include "chrome/common/channel_info.h" -#include "chrome/test/base/chrome_render_view_host_test_harness.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile.h" -#include "chrome/test/base/testing_profile_manager.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/test/browser_task_environment.h" -#include "content/public/test/mock_navigation_handle.h" -#include "content/public/test/test_utils.h" -#include "content/public/test/web_contents_tester.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace { - -constexpr char kTestProfileName[] = "TestProfile"; -const GURL& GetDecentralizedTLDURL() { - static const GURL url("https://brave.crypto/"); - return url; -} -const GURL& GetIPFSURI() { - static const GURL ipfs_url( - "ipfs://bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq/wiki/" - "Vincent_van_Gogh.html"); // NOLINT - return ipfs_url; -} - -const GURL& GetLocalhostIPGatewayURI() { - static const GURL ipfs_url("http://127.0.0.1:8080/ipfs/QmV4FVfWR"); - return ipfs_url; -} - -const GURL& GetIPNSURI() { - static const GURL ipns_url( - "ipns://tr.wikipedia-on-ipfs.org/wiki/Anasayfa.html"); // NOLINT - return ipns_url; -} - -} // namespace - -using content::NavigationThrottle; - -namespace ipfs { - -class ContentBrowserClientHelperUnitTest : public testing::Test { - public: - ContentBrowserClientHelperUnitTest() = default; - ContentBrowserClientHelperUnitTest( - const ContentBrowserClientHelperUnitTest&) = delete; - ContentBrowserClientHelperUnitTest& operator=( - const ContentBrowserClientHelperUnitTest&) = delete; - ~ContentBrowserClientHelperUnitTest() override = default; - - void SetUp() override { - feature_list_.InitAndEnableFeature(ipfs::features::kIpfsFeature); - - TestingBrowserProcess* browser_process = TestingBrowserProcess::GetGlobal(); - profile_manager_ = std::make_unique(browser_process); - ASSERT_TRUE(profile_manager_->SetUp()); - profile_ = profile_manager_->CreateTestingProfile(kTestProfileName); - - web_contents_ = - content::WebContentsTester::CreateTestWebContents(profile_, nullptr); - } - - void TearDown() override { - web_contents_.reset(); - profile_ = nullptr; - profile_manager_->DeleteTestingProfile(kTestProfileName); - } - bool ResolveUnstoppableURL(decentralized_dns::ResolveMethodTypes type) { - local_state()->SetInteger( - decentralized_dns::kUnstoppableDomainsResolveMethod, - static_cast(type)); - GURL ipfs_uri = GetDecentralizedTLDURL(); - bool result = HandleIPFSURLRewrite(&ipfs_uri, browser_context()); - EXPECT_EQ(ipfs_uri, GetDecentralizedTLDURL()); - return result; - } - content::WebContents* web_contents() { return web_contents_.get(); } - - // Helper that creates simple test guest profile. - std::unique_ptr CreateGuestProfile() { - TestingProfile::Builder profile_builder; - profile_builder.SetGuestSession(); - return profile_builder.Build(); - } - - Profile* profile() { return profile_; } - PrefService* local_state() { return profile_manager_->local_state()->Get(); } - content::BrowserContext* browser_context() { - return web_contents()->GetBrowserContext(); - } - -#if BUILDFLAG(ENABLE_IPFS_INTERNALS_WEBUI) - bool RedirectedToInternalPage(IPFSResolveMethodTypes method) { - profile()->GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(method)); - GURL ipfs_diagnostic("chrome://ipfs"); - return ipfs::HandleIPFSURLRewrite(&ipfs_diagnostic, browser_context()) && - ipfs_diagnostic.spec() == kIPFSWebUIURL && - HandleIPFSURLReverseRewrite(&ipfs_diagnostic, browser_context()) && - ipfs_diagnostic.spec() == kIPFSWebUIURL; - } -#endif - - private: - content::BrowserTaskEnvironment task_environment_; - content::RenderViewHostTestEnabler test_render_host_factories_; - std::unique_ptr web_contents_; - raw_ptr profile_ = nullptr; - std::unique_ptr profile_manager_; - base::test::ScopedFeatureList feature_list_; -}; - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteDisabled) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_DISABLED)); - GURL ipfs_uri(GetIPFSURI()); - ASSERT_FALSE(HandleIPFSURLRewrite(&ipfs_uri, browser_context())); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteAsk) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - GURL ipfs_uri(GetIPFSURI()); - ASSERT_FALSE(HandleIPFSURLRewrite(&ipfs_uri, browser_context())); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteGatewayIP) { - profile()->GetPrefs()->SetString(kIPFSPublicGatewayAddress, - "http://127.0.0.1:8080/gateway"); - - const GURL& localhostGateway = GetLocalhostIPGatewayURI(); - GURL ipfs_uri = localhostGateway; - ASSERT_TRUE(HandleIPFSURLRewrite(&ipfs_uri, browser_context())); - GURL::Replacements replacements; - replacements.SetHostStr(kLocalhostDomain); - EXPECT_EQ(ipfs_uri, localhostGateway.ReplaceComponents(replacements)); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteGatewayIPSkip) { - profile()->GetPrefs()->SetString(kIPFSPublicGatewayAddress, - "http://dweb.link/gateway"); - - const GURL& localhostGateway = GetLocalhostIPGatewayURI(); - GURL ipfs_uri = localhostGateway; - ASSERT_FALSE(HandleIPFSURLRewrite(&ipfs_uri, browser_context())); - GURL::Replacements replacements; - replacements.SetHostStr(kLocalhostDomain); - EXPECT_NE(ipfs_uri, localhostGateway.ReplaceComponents(replacements)); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteGateway) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_GATEWAY)); - GURL ipfs_uri(GetIPFSURI()); - ASSERT_FALSE(HandleIPFSURLRewrite(&ipfs_uri, browser_context())); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteLocal) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - GURL ipfs_uri(GetIPFSURI()); - ASSERT_TRUE(HandleIPFSURLRewrite(&ipfs_uri, browser_context())); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteDDns) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - EXPECT_FALSE(decentralized_dns::IsENSResolveMethodEnabled(local_state())); - GURL ens_uri("https://brave.eth"); - ASSERT_FALSE(HandleIPFSURLRewrite(&ens_uri, browser_context())); - local_state()->SetInteger( - decentralized_dns::kENSResolveMethod, - static_cast(decentralized_dns::ResolveMethodTypes::ENABLED)); - EXPECT_TRUE(decentralized_dns::IsENSResolveMethodEnabled(local_state())); - ASSERT_TRUE(HandleIPFSURLRewrite(&ens_uri, browser_context())); - - EXPECT_FALSE(decentralized_dns::IsSnsResolveMethodEnabled(local_state())); - GURL sns_uri("https://brave.sol"); - ASSERT_FALSE(HandleIPFSURLRewrite(&sns_uri, browser_context())); - local_state()->SetInteger( - decentralized_dns::kSnsResolveMethod, - static_cast(decentralized_dns::ResolveMethodTypes::ENABLED)); - EXPECT_TRUE(decentralized_dns::IsSnsResolveMethodEnabled(local_state())); - ASSERT_TRUE(HandleIPFSURLRewrite(&sns_uri, browser_context())); - - EXPECT_FALSE(decentralized_dns::IsUnstoppableDomainsResolveMethodEnabled( - local_state())); - GURL ud_uri("https://brave.crypto"); - ASSERT_FALSE(HandleIPFSURLRewrite(&ud_uri, browser_context())); - local_state()->SetInteger( - decentralized_dns::kUnstoppableDomainsResolveMethod, - static_cast(decentralized_dns::ResolveMethodTypes::ENABLED)); - EXPECT_TRUE(decentralized_dns::IsUnstoppableDomainsResolveMethodEnabled( - local_state())); - ASSERT_TRUE(HandleIPFSURLRewrite(&ud_uri, browser_context())); - - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - ASSERT_FALSE(HandleIPFSURLRewrite(&ens_uri, browser_context())); - ASSERT_FALSE(HandleIPFSURLRewrite(&sns_uri, browser_context())); - ASSERT_FALSE(HandleIPFSURLRewrite(&ud_uri, browser_context())); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPNSURLRewriteLocal) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - GURL ipns_uri(GetIPNSURI()); - ASSERT_TRUE(HandleIPFSURLRewrite(&ipns_uri, browser_context())); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLReverseRewriteLocal) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - GURL gateway_url("http://localhost/"); - GURL::Replacements replacements; - const std::string& port = ipfs::GetGatewayPort(chrome::GetChannel()); - replacements.SetPortStr(port); - gateway_url = gateway_url.ReplaceComponents(replacements); - - ASSERT_EQ(ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - chrome::GetChannel()), - gateway_url); - - std::string source = "http://test.com.ipns.localhost/#ref"; - GURL ipns_uri(GURL(source).ReplaceComponents(replacements)); - ASSERT_TRUE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), "ipns://test.com/#ref"); - - source = "http://en-wikipedia--on--ipfs-org.ipns.localhost/wiki/Architecture"; - ipns_uri = GURL(source).ReplaceComponents(replacements); - ASSERT_TRUE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), - "ipns://en.wikipedia-on-ipfs.org/wiki/Architecture"); - - source = - "http://" - "bafkreiedqfhqvarz2y4c2s3vrbrcq427sawhzbewzksegopavnmwbz4zyq.ipfs." - "localhost"; - ipns_uri = GURL(source).ReplaceComponents(replacements); - ASSERT_TRUE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ( - ipns_uri.spec(), - "ipfs://bafkreiedqfhqvarz2y4c2s3vrbrcq427sawhzbewzksegopavnmwbz4zyq/"); - - source = "http://test.com.ipns.localhost:8000/"; - ipns_uri = GURL(source); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); - - ipns_uri = GURL("http://wrongcidandbaddomain.ipns.localhost/#ref"); - ipns_uri = ipns_uri.ReplaceComponents(replacements); - source = ipns_uri.spec(); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); -} - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLReverseRewriteGateway) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_GATEWAY)); - ASSERT_EQ(ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - version_info::Channel::UNKNOWN), - GURL("https://dweb.link/")); - - std::string source = "http://test.com.ipns.localhost:8000/"; - GURL ipns_uri(source); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); - - source = "https://ku2jvrakgpiqgx4j6fe.ipfs.dweb.link/"; - ipns_uri = GURL(source); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); - - profile()->GetPrefs()->SetString(kIPFSPublicGatewayAddress, - "http://localhost:8080"); - ASSERT_EQ(ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - version_info::Channel::UNKNOWN), - GURL("http://localhost:8080")); - - source = "http://test.com.ipns.localhost:8000/"; - ipns_uri = GURL(source); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); - - source = "https://ku2jvrakgpiqgx4j6fe.ipfs.dweb.link/"; - ipns_uri = GURL(source); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); - - source = "https://ku2jvrakgpiqgx4j6fe.ipfs.dweb.link:8080/"; - ipns_uri = GURL(source); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); - - source = "http://test.com.ipns.localhost:8080/#some-ref"; - ipns_uri = GURL(source); - ASSERT_TRUE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), "ipns://test.com/#some-ref"); - - source = "https://wrongcidandbaddomain.ipns.localhost:8080/"; - ipns_uri = GURL(source); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); - - source = "http://en-wikipedia--on--ipfs-org.ipns.localhost:48080/wiki/"; - ipns_uri = GURL(source); - ASSERT_FALSE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), source); - - source = "http://en-wikipedia--on--ipfs-org.ipns.localhost:8080/wiki/"; - ipns_uri = GURL(source); - ASSERT_TRUE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ(ipns_uri.spec(), "ipns://en.wikipedia-on-ipfs.org/wiki/"); - - ipns_uri = GURL( - "https://bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq" - ".ipns.localhost:8080/"); - ASSERT_TRUE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ( - ipns_uri.spec(), - "ipns://bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq/"); - - ipns_uri = GURL( - "https://bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq" - ".ipfs.localhost:8080/"); - ASSERT_TRUE(HandleIPFSURLReverseRewrite(&ipns_uri, browser_context())); - ASSERT_EQ( - ipns_uri.spec(), - "ipfs://bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq/"); -} - -#if BUILDFLAG(ENABLE_IPFS_INTERNALS_WEBUI) -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteInternal) { - ASSERT_TRUE(RedirectedToInternalPage(IPFSResolveMethodTypes::IPFS_LOCAL)); - ASSERT_TRUE(RedirectedToInternalPage(IPFSResolveMethodTypes::IPFS_GATEWAY)); - ASSERT_TRUE(RedirectedToInternalPage(IPFSResolveMethodTypes::IPFS_ASK)); - ASSERT_TRUE(RedirectedToInternalPage(IPFSResolveMethodTypes::IPFS_DISABLED)); -} -#endif - -TEST_F(ContentBrowserClientHelperUnitTest, HandleIPFSURLRewriteCrypto) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - ASSERT_TRUE( - ResolveUnstoppableURL(decentralized_dns::ResolveMethodTypes::ENABLED)); - ASSERT_FALSE( - ResolveUnstoppableURL(decentralized_dns::ResolveMethodTypes::DISABLED)); - - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_GATEWAY)); - ASSERT_FALSE( - ResolveUnstoppableURL(decentralized_dns::ResolveMethodTypes::ENABLED)); - ASSERT_FALSE( - ResolveUnstoppableURL(decentralized_dns::ResolveMethodTypes::DISABLED)); - - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_DISABLED)); - ASSERT_FALSE( - ResolveUnstoppableURL(decentralized_dns::ResolveMethodTypes::ENABLED)); - ASSERT_FALSE( - ResolveUnstoppableURL(decentralized_dns::ResolveMethodTypes::DISABLED)); -} -} // namespace ipfs diff --git a/browser/ipfs/import/ipfs_import_controller.cc b/browser/ipfs/import/ipfs_import_controller.cc deleted file mode 100644 index c7eb5a73e341..000000000000 --- a/browser/ipfs/import/ipfs_import_controller.cc +++ /dev/null @@ -1,366 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/import/ipfs_import_controller.h" - -#include -#include -#include -#include - -#include "base/files/file_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task/thread_pool.h" -#include "base/uuid.h" -#include "brave/browser/ipfs/import/save_package_observer.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/constants/webui_url_constants.h" -#include "brave/components/ipfs/import/imported_data.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_navigation_throttle.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/keys/ipns_keys_manager.h" -#include "brave/components/l10n/common/localization_util.h" -#include "chrome/browser/notifications/notification_display_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/chrome_select_file_policy.h" -#include "chrome/common/channel_info.h" -#include "components/grit/brave_components_strings.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/web_contents.h" -#include "net/base/filename_util.h" -#include "net/base/url_util.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/models/image_model.h" -#include "ui/message_center/public/cpp/notification.h" -#include "ui/message_center/public/cpp/notification_types.h" -#include "ui/message_center/public/cpp/notifier_id.h" -#include "ui/shell_dialogs/selected_file_info.h" - -namespace { - -// Converts url to directory name: -// https://one.two/ -> one.two -// https://one.two/some/path -> one.two_some_path -std::string GetDirectoryNameForWebPageImport(const GURL& url) { - if (url.path().empty() || url.path() == "/") - return url.host(); - std::string content = url.host() + url.path(); - base::ReplaceSubstringsAfterOffset(&content, 0, "/", "_"); - return content; -} - -// The index.html page is the most common name used for default pages -// if no other page is specified. We use it to open imported pages -// by shareable link automatically in browsers. -const char kDefaultHtmlPageName[] = "index.html"; - -// Message center notifier id for user notifications -const char kNotifierId[] = "service.ipfs"; - -// Imported shareable link should have filename parameter. -const char kImportFileNameParam[] = "filename"; - -std::u16string GetImportNotificationTitle(ipfs::ImportState state) { - switch (state) { - case ipfs::IPFS_IMPORT_SUCCESS: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_IMPORT_NOTIFICATION_TITLE); - case ipfs::IPFS_IMPORT_ERROR_REQUEST_EMPTY: - case ipfs::IPFS_IMPORT_ERROR_ADD_FAILED: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_IMPORT_ERROR_NOTIFICATION_TITLE); - case ipfs::IPFS_IMPORT_ERROR_MKDIR_FAILED: - case ipfs::IPFS_IMPORT_ERROR_MOVE_FAILED: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_IMPORT_PARTLY_COMPLETED_NOTIFICATION_TITLE); - default: - NOTREACHED_IN_MIGRATION(); - break; - } - return std::u16string(); -} - -std::u16string GetImportNotificationBody(ipfs::ImportState state, - const GURL& shareable_link) { - switch (state) { - case ipfs::IPFS_IMPORT_SUCCESS: - return l10n_util::GetStringFUTF16( - IDS_IPFS_IMPORT_NOTIFICATION_BODY, - base::UTF8ToUTF16(shareable_link.spec())); - case ipfs::IPFS_IMPORT_ERROR_REQUEST_EMPTY: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_IMPORT_ERROR_NO_REQUEST_BODY); - case ipfs::IPFS_IMPORT_ERROR_ADD_FAILED: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_IMPORT_ERROR_ADD_FAILED_BODY); - case ipfs::IPFS_IMPORT_ERROR_MKDIR_FAILED: - case ipfs::IPFS_IMPORT_ERROR_MOVE_FAILED: - return brave_l10n::GetLocalizedResourceUTF16String( - IDS_IPFS_IMPORT_PARTLY_COMPLETED_NOTIFICATION_BODY); - default: - NOTREACHED_IN_MIGRATION(); - break; - } - return std::u16string(); -} - -std::unique_ptr CreateMessageCenterNotification( - const std::u16string& title, - const std::u16string& body, - const std::string& uuid, - const GURL& link) { - message_center::RichNotificationData notification_data; - // hack to prevent origin from showing in the notification - // since we're using that to get the notification_id to OpenSettings - notification_data.context_message = u" "; - auto notification = std::make_unique( - message_center::NOTIFICATION_TYPE_SIMPLE, uuid, title, body, - ui::ImageModel(), std::u16string(), link, - message_center::NotifierId(message_center::NotifierType::SYSTEM_COMPONENT, - kNotifierId), - notification_data, nullptr); - - return notification; -} - -base::FilePath CreateTempDownloadDirectory(const std::string& subdir) { - base::FilePath temp_dir_path; - base::CreateNewTempDirectory(base::FilePath::StringType(), &temp_dir_path); - base::FilePath web_package_dir = temp_dir_path.AppendASCII(subdir); - if (base::CreateDirectory(web_package_dir)) - return web_package_dir; - return base::FilePath(); -} - -} // namespace - -namespace ipfs { - -IpfsImportController::~IpfsImportController() = default; - -IpfsImportController::IpfsImportController(content::WebContents& web_contents) - : web_contents_(web_contents), - ipfs_service_(*ipfs::IpfsServiceFactory::GetForContext( - web_contents.GetBrowserContext())), - file_task_runner_(base::ThreadPool::CreateSequencedTaskRunner( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::BLOCK_SHUTDOWN})) {} - -void IpfsImportController::ImportLinkToIpfs(const GURL& url) { - ipfs_service_->ImportLinkToIpfs( - url, base::BindOnce(&IpfsImportController::OnImportCompleted, - weak_ptr_factory_.GetWeakPtr())); -} - -void IpfsImportController::ImportCurrentPageToIpfs() { - if (!web_contents_->IsSavable()) { - VLOG(1) << "Unable to save pages with mime type:" - << web_contents_->GetContentsMimeType(); - return; - } - web_contents_->Stop(); - - file_task_runner_->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce(&CreateTempDownloadDirectory, - GetDirectoryNameForWebPageImport(web_contents_->GetURL())), - base::BindOnce(&IpfsImportController::SaveWebPage, - weak_ptr_factory_.GetWeakPtr())); -} - -void IpfsImportController::SaveWebPage(const base::FilePath& directory) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (directory.empty()) { - VLOG(1) << "Unable to create temporary directory for import"; - return; - } - base::FilePath saved_main_file_path = - directory.AppendASCII(kDefaultHtmlPageName); - net::GenerateSafeFileName(web_contents_->GetContentsMimeType(), false, - &saved_main_file_path); - base::FilePath saved_main_directory_path = saved_main_file_path.DirName(); - saved_main_directory_path = saved_main_directory_path.Append( - saved_main_file_path.RemoveExtension().BaseName().value() + - FILE_PATH_LITERAL("_files")); - auto* download_manager = - web_contents_->GetBrowserContext()->GetDownloadManager(); - save_package_observer_ = std::make_unique( - download_manager, saved_main_file_path, - base::BindOnce(&IpfsImportController::OnDownloadFinished, - weak_ptr_factory_.GetWeakPtr(), directory)); - web_contents_->SavePage(saved_main_file_path, saved_main_directory_path, - content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML); -} - -bool IpfsImportController::HasInProgressDownload(download::DownloadItem* item) { - if (!save_package_observer_ || !item) - return false; - return save_package_observer_->HasInProgressDownload(item); -} - -void IpfsImportController::OnDownloadFinished( - const base::FilePath& path, - download::DownloadItem* download) { - DCHECK(download); - switch (download->GetState()) { - case download::DownloadItem::COMPLETE: - ipfs_service_->ImportDirectoryToIpfs( - path, std::string(), - base::BindOnce(&IpfsImportController::OnWebPageImportCompleted, - weak_ptr_factory_.GetWeakPtr(), path)); - break; - case download::DownloadItem::CANCELLED: - base::ThreadPool::PostTask( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, - base::GetDeletePathRecursivelyCallback(path.DirName())); - break; - default: - NOTREACHED_IN_MIGRATION(); - } - - save_package_observer_.reset(); -} - -void IpfsImportController::ImportDirectoryToIpfs(const base::FilePath& path, - const std::string& key) { - ipfs_service_->ImportDirectoryToIpfs( - path, key, - base::BindOnce(&IpfsImportController::OnImportCompleted, - weak_ptr_factory_.GetWeakPtr())); -} - -void IpfsImportController::ImportTextToIpfs(const std::string& text) { - ipfs_service_->ImportTextToIpfs( - text, web_contents_->GetURL().host(), - base::BindOnce(&IpfsImportController::OnImportCompleted, - weak_ptr_factory_.GetWeakPtr())); -} - -void IpfsImportController::ImportFileToIpfs(const base::FilePath& path, - const std::string& key) { - ipfs_service_->ImportFileToIpfs( - path, key, - base::BindOnce(&IpfsImportController::OnImportCompleted, - weak_ptr_factory_.GetWeakPtr())); -} - -GURL IpfsImportController::CreateAndCopyShareableLink( - const ipfs::ImportedData& data) { - if (data.hash.empty()) - return GURL(); - std::string ipfs = ipfs::kIPFSScheme + std::string("://") + data.hash; - if (!data.published_key.empty()) { - auto key = ipfs_service_->GetIpnsKeysManager()->FindKey(data.published_key); - if (!key.empty()) { - ipfs = ipfs::kIPNSScheme + std::string("://") + key; - } - } - auto shareable_link = ipfs::ToPublicGatewayURL( - GURL(ipfs), - user_prefs::UserPrefs::Get(web_contents_->GetBrowserContext())); - if (!shareable_link.is_valid()) - return GURL(); - if (!data.filename.empty()) - shareable_link = net::AppendQueryParameter( - shareable_link, kImportFileNameParam, data.filename); - ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) - .WriteText(base::UTF8ToUTF16(shareable_link.spec())); - ipfs_service_->PreWarmShareableLink(shareable_link); - return shareable_link; -} - -void IpfsImportController::OnWebPageImportCompleted( - const base::FilePath& imported_direcory, - const ipfs::ImportedData& data) { - base::ThreadPool::PostTask( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, - GetDeletePathRecursivelyCallback(imported_direcory.DirName())); - OnImportCompleted(data); -} - -void IpfsImportController::OnImportCompleted(const ipfs::ImportedData& data) { - auto link = CreateAndCopyShareableLink(data); -#if BUILDFLAG(ENABLE_IPFS_INTERNALS_WEBUI) - if (!link.is_valid()) { - // Open node diagnostic page if import failed - link = GURL(kIPFSWebUIURL); - } -#endif - PushNotification(GetImportNotificationTitle(data.state), - GetImportNotificationBody(data.state, link), link); - if (data.state == ipfs::IPFS_IMPORT_SUCCESS) { - GURL url = ResolveWebUIFilesLocation(data.directory, chrome::GetChannel()); - content::OpenURLParams params(url, content::Referrer(), - WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui::PAGE_TRANSITION_LINK, false); - web_contents_->OpenURL(params, /*navigation_handle_callback=*/{}); - } -} - -void IpfsImportController::PushNotification(const std::u16string& title, - const std::u16string& body, - const GURL& link) { - auto notification = CreateMessageCenterNotification( - title, body, base::Uuid::GenerateRandomV4().AsLowercaseString(), link); - Profile* profile = - Profile::FromBrowserContext(web_contents_->GetBrowserContext()); - auto* display_service = NotificationDisplayService::GetForProfile(profile); - display_service->Display(NotificationHandler::Type::SEND_TAB_TO_SELF, - *notification, /*metadata=*/nullptr); -} - -void IpfsImportController::FileSelected(const ui::SelectedFileInfo& file, - int index, - void* params) { - switch (dialog_type_) { - case ui::SelectFileDialog::SELECT_OPEN_FILE: - ImportFileToIpfs(file.path(), dialog_key_); - break; - case ui::SelectFileDialog::SELECT_EXISTING_FOLDER: - ImportDirectoryToIpfs(file.path(), dialog_key_); - break; - default: - NOTREACHED_IN_MIGRATION() - << "Only existing file or directory import supported"; - break; - } - dialog_type_ = ui::SelectFileDialog::SELECT_NONE; - select_file_dialog_.reset(); - dialog_key_.clear(); -} - -void IpfsImportController::FileSelectionCanceled(void* params) { - select_file_dialog_.reset(); - dialog_key_.clear(); -} - -void IpfsImportController::ShowImportDialog(ui::SelectFileDialog::Type type, - const std::string& key) { - select_file_dialog_ = ui::SelectFileDialog::Create( - this, std::make_unique(&*web_contents_)); - if (!select_file_dialog_) { - VLOG(1) << "Import already in progress"; - return; - } - Profile* profile = - Profile::FromBrowserContext(web_contents_->GetBrowserContext()); - const base::FilePath directory = profile->last_selected_directory(); - gfx::NativeWindow parent_window = web_contents_->GetTopLevelNativeWindow(); - ui::SelectFileDialog::FileTypeInfo file_types; - file_types.allowed_paths = - ui::SelectFileDialog::FileTypeInfo::ANY_PATH_OR_URL; - dialog_type_ = type; - dialog_key_ = key; - select_file_dialog_->SelectFile(type, std::u16string(), directory, - &file_types, 0, base::FilePath::StringType(), - parent_window, nullptr); -} - -} // namespace ipfs diff --git a/browser/ipfs/import/ipfs_import_controller.h b/browser/ipfs/import/ipfs_import_controller.h deleted file mode 100644 index 9ee7e3b41ce1..000000000000 --- a/browser/ipfs/import/ipfs_import_controller.h +++ /dev/null @@ -1,99 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IMPORT_IPFS_IMPORT_CONTROLLER_H_ -#define BRAVE_BROWSER_IPFS_IMPORT_IPFS_IMPORT_CONTROLLER_H_ - -#include -#include -#include -#include - -#include "brave/components/ipfs/ipfs_service.h" -#include "ui/shell_dialogs/select_file_dialog.h" - -namespace content { -class WebContents; -} // namespace content - -class SavePackageFinishedObserver; - -namespace download { -class DownloadItem; -} - -namespace ui { -class SelectFileDialog; -} - -namespace ipfs { - -struct ImportedData; -class IpfsService; - -// Prepares data for IPFS import and does some interactions with user. -// Shows dialog to select file or folder for import and pushes notifications -// when import completed. -class IpfsImportController : public ui::SelectFileDialog::Listener { - public: - explicit IpfsImportController(content::WebContents& web_contents); - ~IpfsImportController() override; - - IpfsImportController(const IpfsImportController&) = delete; - IpfsImportController& operator=(const IpfsImportController&) = delete; - - void ImportLinkToIpfs(const GURL& url); - void ImportTextToIpfs(const std::string& text); - void ImportFileToIpfs(const base::FilePath& path, const std::string& key); - void ImportDirectoryToIpfs(const base::FilePath& path, - const std::string& key); - void ImportCurrentPageToIpfs(); - - void ShowImportDialog(ui::SelectFileDialog::Type type, - const std::string& key); - bool HasInProgressDownload(download::DownloadItem* item); - - void SetIpfsServiceForTesting(ipfs::IpfsService* service) { - ipfs_service_ = *service; - } - void SkipSavePageForTesting(bool value) { - skip_save_page_for_testing_ = value; - } - - private: - // ui::SelectFileDialog::Listener - void FileSelected(const ui::SelectedFileInfo& file, - int index, - void* params) override; - void FileSelectionCanceled(void* params) override; - - void OnDownloadFinished(const base::FilePath& path, - download::DownloadItem* download); - - void SaveWebPage(const base::FilePath& directory); - void PushNotification(const std::u16string& title, - const std::u16string& body, - const GURL& link); - GURL CreateAndCopyShareableLink(const ipfs::ImportedData& data); - void OnImportCompleted(const ipfs::ImportedData& data); - void OnWebPageImportCompleted(const base::FilePath& imported_direcory, - const ipfs::ImportedData& data); - - std::unique_ptr save_package_observer_; - scoped_refptr select_file_dialog_; - ui::SelectFileDialog::Type dialog_type_ = ui::SelectFileDialog::SELECT_NONE; - std::string dialog_key_; - - const raw_ref web_contents_; - raw_ref ipfs_service_; - bool skip_save_page_for_testing_ = false; - - scoped_refptr file_task_runner_; - base::WeakPtrFactory weak_ptr_factory_{this}; -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IMPORT_IPFS_IMPORT_CONTROLLER_H_ diff --git a/browser/ipfs/import/ipfs_import_controller_browsertest.cc b/browser/ipfs/import/ipfs_import_controller_browsertest.cc deleted file mode 100644 index 3a48d132015f..000000000000 --- a/browser/ipfs/import/ipfs_import_controller_browsertest.cc +++ /dev/null @@ -1,299 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/import/ipfs_import_controller.h" - -#include "base/path_service.h" -#include "brave/browser/ipfs/ipfs_blob_context_getter_factory.h" -#include "brave/browser/ipfs/ipfs_dns_resolver_impl.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/browser/ipfs/ipfs_service_impl_delegate.h" -#include "brave/browser/ipfs/ipfs_tab_helper.h" -#include "brave/components/ipfs/blob_context_getter_factory.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "chrome/browser/notifications/notification_display_service_tester.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/channel_info.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" - -using content::WebContents; - -namespace { - -class FakeIpfsService : public ipfs::IpfsService { - public: - FakeIpfsService( - PrefService* prefs, - scoped_refptr url_loader_factory, - ipfs::BlobContextGetterFactoryPtr blob_context_getter_factory, - ipfs::BraveIpfsClientUpdater* updater, - const base::FilePath& user_dir, - version_info::Channel channel) - : ipfs::IpfsService( - prefs, - url_loader_factory, - std::move(blob_context_getter_factory), - updater, - user_dir, - channel, - std::make_unique(), - std::make_unique(prefs, nullptr)) {} - ~FakeIpfsService() override = default; - void ImportTextToIpfs(const std::string& text, - const std::string& host, - ipfs::ImportCompletedCallback callback) override { - function_calls_["ImportTextToIpfs"]++; - if (callback) - std::move(callback).Run(data_); - } - void ImportLinkToIpfs(const GURL& url, - ipfs::ImportCompletedCallback callback) override { - function_calls_["ImportLinkToIpfs"]++; - if (callback) - std::move(callback).Run(data_); - } - void ImportFileToIpfs(const base::FilePath& path, - const std::string& key, - ipfs::ImportCompletedCallback callback) override { - function_calls_["ImportFileToIpfs"]++; - if (callback) - std::move(callback).Run(data_); - } - void ImportDirectoryToIpfs(const base::FilePath& path, - const std::string& key, - ipfs::ImportCompletedCallback callback) override { - function_calls_["ImportDirectoryToIpfs"]++; - if (callback) - std::move(callback).Run(data_); - if (directory_callback_) - std::move(directory_callback_).Run(); - } - void PreWarmShareableLink(const GURL& url) override { - function_calls_["PreWarmShareableLink"]++; - } - int GetCallsNumber(const std::string& function) { - if (!function_calls_.count(function)) - return 0; - return function_calls_[function]; - } - void SetImportData(const ipfs::ImportedData& data) { data_ = data; } - void SetDirectoryCallback(base::OnceClosure callback) { - directory_callback_ = std::move(callback); - } - - private: - ipfs::ImportedData data_; - base::OnceClosure directory_callback_; - std::unordered_map function_calls_; -}; - -} // namespace - -namespace ipfs { - -class IpfsImportControllerBrowserTest : public InProcessBrowserTest { - public: - IpfsImportControllerBrowserTest() = default; - void SetUpOnMainThread() override { - InProcessBrowserTest::SetUpOnMainThread(); - ASSERT_TRUE(embedded_test_server()->Start()); - display_service_ = std::make_unique( - Profile::FromBrowserContext(active_contents()->GetBrowserContext())); - base::FilePath user_dir = base::FilePath(FILE_PATH_LITERAL("test")); - auto context_getter = std::make_unique( - active_contents()->GetBrowserContext()); - fake_service_ = std::make_unique( - nullptr, nullptr, std::move(context_getter), nullptr, user_dir, - chrome::GetChannel()); - } - - content::WebContents* active_contents() { - return browser()->tab_strip_model()->GetActiveWebContents(); - } - - bool NotificationShown() { - std::vector notifications = - display_service_->GetDisplayedNotificationsForType( - NotificationHandler::Type::SEND_TAB_TO_SELF); - return notifications.size() == 1u; - } - - FakeIpfsService* fake_ipfs_service() { return fake_service_.get(); } - - private: - std::unique_ptr display_service_; - std::unique_ptr fake_service_; -}; - -IN_PROC_BROWSER_TEST_F(IpfsImportControllerBrowserTest, ImportFileToIpfs) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - if (!helper) - return; - base::FilePath user_dir = base::FilePath(FILE_PATH_LITERAL("test")); - auto* ipfs_service = fake_ipfs_service(); - ipfs::ImportedData data; - data.hash = "QmYbK4SLaSvTKKAKvNZMwyzYPy4P3GqBPN6CZzbS73FxxU"; - data.filename = "google.com"; - data.size = 111; - data.directory = "/brave/imports/"; - data.state = ipfs::IPFS_IMPORT_SUCCESS; - ipfs_service->SetImportData(data); - auto* controller = helper->GetImportController(); - controller->SetIpfsServiceForTesting(ipfs_service); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 1); - controller->ImportFileToIpfs(base::FilePath(FILE_PATH_LITERAL("fake.file")), - std::string()); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 2); - auto* web_content = browser()->tab_strip_model()->GetWebContentsAt(1); - ASSERT_TRUE(web_content); - GURL url = - ipfs::ResolveWebUIFilesLocation(data.directory, chrome::GetChannel()); - EXPECT_EQ(web_content->GetURL().spec(), url.spec()); - EXPECT_EQ(ipfs_service->GetCallsNumber("ImportFileToIpfs"), 1); - EXPECT_EQ(ipfs_service->GetCallsNumber("PreWarmShareableLink"), 1); - ASSERT_TRUE(NotificationShown()); -} - -IN_PROC_BROWSER_TEST_F(IpfsImportControllerBrowserTest, ImportTextToIpfs) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - if (!helper) - return; - base::FilePath user_dir = base::FilePath(FILE_PATH_LITERAL("test")); - auto* ipfs_service = fake_ipfs_service(); - ipfs::ImportedData data; - data.hash = "QmYbK4SLaSvTKKAKvNZMwyzYPy4P3GqBPN6CZzbS73FxxU"; - data.filename = "google.com"; - data.size = 111; - data.directory = "/brave/imports/"; - data.state = ipfs::IPFS_IMPORT_SUCCESS; - ipfs_service->SetImportData(data); - auto* controller = helper->GetImportController(); - controller->SetIpfsServiceForTesting(ipfs_service); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 1); - controller->ImportTextToIpfs("test"); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 2); - auto* web_content = browser()->tab_strip_model()->GetWebContentsAt(1); - ASSERT_TRUE(web_content); - GURL url = - ipfs::ResolveWebUIFilesLocation(data.directory, chrome::GetChannel()); - EXPECT_EQ(web_content->GetURL().spec(), url.spec()); - EXPECT_EQ(ipfs_service->GetCallsNumber("ImportTextToIpfs"), 1); - EXPECT_EQ(ipfs_service->GetCallsNumber("PreWarmShareableLink"), 1); - ASSERT_TRUE(NotificationShown()); -} - -IN_PROC_BROWSER_TEST_F(IpfsImportControllerBrowserTest, ImportLinkToIpfs) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - if (!helper) - return; - base::FilePath user_dir = base::FilePath(FILE_PATH_LITERAL("test")); - auto* ipfs_service = fake_ipfs_service(); - ipfs::ImportedData data; - data.hash = "QmYbK4SLaSvTKKAKvNZMwyzYPy4P3GqBPN6CZzbS73FxxU"; - data.filename = "google.com"; - data.size = 111; - data.directory = "/brave/imports/"; - data.state = ipfs::IPFS_IMPORT_SUCCESS; - ipfs_service->SetImportData(data); - auto* controller = helper->GetImportController(); - controller->SetIpfsServiceForTesting(ipfs_service); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 1); - controller->ImportLinkToIpfs(GURL("test.com")); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 2); - auto* web_content = browser()->tab_strip_model()->GetWebContentsAt(1); - ASSERT_TRUE(web_content); - GURL url = - ipfs::ResolveWebUIFilesLocation(data.directory, chrome::GetChannel()); - EXPECT_EQ(web_content->GetURL().spec(), url.spec()); - EXPECT_EQ(ipfs_service->GetCallsNumber("ImportLinkToIpfs"), 1); - EXPECT_EQ(ipfs_service->GetCallsNumber("PreWarmShareableLink"), 1); - ASSERT_TRUE(NotificationShown()); -} - -IN_PROC_BROWSER_TEST_F(IpfsImportControllerBrowserTest, ImportDirectoryToIpfs) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - if (!helper) - return; - base::FilePath user_dir = base::FilePath(FILE_PATH_LITERAL("test")); - - auto* ipfs_service = fake_ipfs_service(); - ipfs::ImportedData data; - data.hash = "QmYbK4SLaSvTKKAKvNZMwyzYPy4P3GqBPN6CZzbS73FxxU"; - data.filename = "google.com"; - data.size = 111; - data.directory = "/brave/imports/"; - data.state = ipfs::IPFS_IMPORT_SUCCESS; - ipfs_service->SetImportData(data); - auto* controller = helper->GetImportController(); - controller->SetIpfsServiceForTesting(ipfs_service); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 1); - controller->ImportDirectoryToIpfs( - base::FilePath(FILE_PATH_LITERAL("test.file")), std::string()); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 2); - auto* web_content = browser()->tab_strip_model()->GetWebContentsAt(1); - ASSERT_TRUE(web_content); - GURL url = - ipfs::ResolveWebUIFilesLocation(data.directory, chrome::GetChannel()); - EXPECT_EQ(web_content->GetURL().spec(), url.spec()); - EXPECT_EQ(ipfs_service->GetCallsNumber("ImportDirectoryToIpfs"), 1); - EXPECT_EQ(ipfs_service->GetCallsNumber("PreWarmShareableLink"), 1); - ASSERT_TRUE(NotificationShown()); -} - -IN_PROC_BROWSER_TEST_F(IpfsImportControllerBrowserTest, - ImportCurrentPageToIpfs) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - if (!helper) - return; - base::FilePath user_dir = base::FilePath(FILE_PATH_LITERAL("test")); - auto* ipfs_service = fake_ipfs_service(); - ipfs::ImportedData data; - data.hash = "QmYbK4SLaSvTKKAKvNZMwyzYPy4P3GqBPN6CZzbS73FxxU"; - data.filename = "google.com"; - data.size = 111; - data.directory = "/brave/imports/"; - data.state = ipfs::IPFS_IMPORT_SUCCESS; - ipfs_service->SetImportData(data); - base::RunLoop run_loop; - ipfs_service->SetDirectoryCallback(run_loop.QuitClosure()); - auto* controller = helper->GetImportController(); - controller->SetIpfsServiceForTesting(ipfs_service); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 1); - controller->ImportCurrentPageToIpfs(); - run_loop.Run(); - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 2); - auto* web_content = browser()->tab_strip_model()->GetWebContentsAt(1); - ASSERT_TRUE(web_content); - GURL url = - ipfs::ResolveWebUIFilesLocation(data.directory, chrome::GetChannel()); - EXPECT_EQ(web_content->GetURL().spec(), url.spec()); - EXPECT_EQ(ipfs_service->GetCallsNumber("ImportDirectoryToIpfs"), 1); - EXPECT_EQ(ipfs_service->GetCallsNumber("PreWarmShareableLink"), 1); - ASSERT_TRUE(NotificationShown()); -} - -} // namespace ipfs diff --git a/browser/ipfs/import/save_package_observer.cc b/browser/ipfs/import/save_package_observer.cc deleted file mode 100644 index 915ee2e431de..000000000000 --- a/browser/ipfs/import/save_package_observer.cc +++ /dev/null @@ -1,82 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/import/save_package_observer.h" - -#include - -#include "chrome/browser/download/download_item_model.h" -#include "components/download/public/common/download_item.h" -#include "content/public/browser/download_manager.h" - -SavePackageFinishedObserver::SavePackageFinishedObserver( - content::DownloadManager* manager, - const base::FilePath& main_file_path, - SavePackageCompleted callback) - : download_manager_(manager), - download_(nullptr), - main_file_path_(main_file_path), - callback_(std::move(callback)) { - DCHECK(callback_); - download_manager_->AddObserver(this); -} - -SavePackageFinishedObserver::~SavePackageFinishedObserver() { - if (download_manager_) - download_manager_->RemoveObserver(this); - - if (download_) - download_->RemoveObserver(this); -} - -void SavePackageFinishedObserver::OnDownloadUpdated( - download::DownloadItem* download) { - if (download != download_) - return; - if (download->GetState() == download::DownloadItem::COMPLETE || - download->GetState() == download::DownloadItem::CANCELLED) { - if (callback_) - std::move(callback_).Run(download); - } -} - -void SavePackageFinishedObserver::OnDownloadDestroyed( - download::DownloadItem* download) { - download_->RemoveObserver(this); - download_ = nullptr; -} - -bool SavePackageFinishedObserver::HasInProgressDownload( - download::DownloadItem* item) const { - if (!item) - return false; - if (item->GetDownloadCreationType() != - download::DownloadItem::TYPE_SAVE_PAGE_AS) - return false; - return main_file_path_ == item->GetTargetFilePath(); -} - -void SavePackageFinishedObserver::OnDownloadCreated( - content::DownloadManager* manager, - download::DownloadItem* download) { - if (!download) - return; - if (download->GetDownloadCreationType() != - download::DownloadItem::TYPE_SAVE_PAGE_AS) - return; - DownloadItemModel(download).SetShouldShowInShelf(false); - if (download_) - return; - download_ = download; - download->AddObserver(this); -} - -void SavePackageFinishedObserver::ManagerGoingDown( - content::DownloadManager* manager) { - download_->RemoveObserver(this); - download_ = nullptr; - download_manager_->RemoveObserver(this); - download_manager_ = nullptr; -} diff --git a/browser/ipfs/import/save_package_observer.h b/browser/ipfs/import/save_package_observer.h deleted file mode 100644 index 3a01799df57e..000000000000 --- a/browser/ipfs/import/save_package_observer.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IMPORT_SAVE_PACKAGE_OBSERVER_H_ -#define BRAVE_BROWSER_IPFS_IMPORT_SAVE_PACKAGE_OBSERVER_H_ - -#include "base/memory/raw_ptr.h" -#include "components/download/public/common/download_item.h" -#include "content/public/browser/download_manager.h" - -// Tracks downloading process for a pacakge and notifies when it is completed. -class SavePackageFinishedObserver : public download::DownloadItem::Observer, - public content::DownloadManager::Observer { - public: - using SavePackageCompleted = - base::OnceCallback; - - SavePackageFinishedObserver(content::DownloadManager* manager, - const base::FilePath& main_file_path, - SavePackageCompleted callback); - ~SavePackageFinishedObserver() override; - - SavePackageFinishedObserver(const SavePackageFinishedObserver&) = delete; - SavePackageFinishedObserver& operator=(const SavePackageFinishedObserver&) = - delete; - - bool HasInProgressDownload(download::DownloadItem* item) const; - - // download::DownloadItem::Observer: - void OnDownloadUpdated(download::DownloadItem* download) override; - void OnDownloadDestroyed(download::DownloadItem* download) override; - - // DownloadManager::Observer: - void OnDownloadCreated(content::DownloadManager* manager, - download::DownloadItem* download) override; - void ManagerGoingDown(content::DownloadManager* manager) override; - - private: - raw_ptr download_manager_ = nullptr; - raw_ptr download_ = nullptr; - base::FilePath main_file_path_; - SavePackageCompleted callback_; -}; - -#endif // BRAVE_BROWSER_IPFS_IMPORT_SAVE_PACKAGE_OBSERVER_H_ diff --git a/browser/ipfs/import/save_package_observer_browsertest.cc b/browser/ipfs/import/save_package_observer_browsertest.cc deleted file mode 100644 index 1f0322d1cf7e..000000000000 --- a/browser/ipfs/import/save_package_observer_browsertest.cc +++ /dev/null @@ -1,98 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/import/save_package_observer.h" - -#include "base/files/file_util.h" -#include "chrome/browser/download/download_item_model.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/download/public/common/download_item.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/download_manager.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/fake_download_item.h" -#include "net/base/filename_util.h" -#include "net/test/embedded_test_server/embedded_test_server.h" - -class SavePackageFinishedObserverBrowserTest : public InProcessBrowserTest { - public: - SavePackageFinishedObserverBrowserTest() = default; - void SetUpOnMainThread() override { - InProcessBrowserTest::SetUpOnMainThread(); - ASSERT_TRUE(embedded_test_server()->Start()); - ASSERT_TRUE(save_dir_.CreateUniqueTempDir()); - } - - content::WebContents* web_contents() { - return browser()->tab_strip_model()->GetActiveWebContents(); - } - - void GetDestinationPaths(const std::string& prefix, - base::FilePath* full_file_name, - base::FilePath* dir) { - *full_file_name = save_dir_.GetPath().AppendASCII(prefix + ".html"); - *dir = save_dir_.GetPath().AppendASCII(prefix + "_files"); - } - - private: - base::ScopedTempDir save_dir_; -}; - -class FakePackageDownloadItem : public content::FakeDownloadItem { - public: - FakePackageDownloadItem() = default; - ~FakePackageDownloadItem() override = default; - - download::DownloadItem::DownloadCreationType GetDownloadCreationType() - const override { - return type_; - } - - void SetDownloadCreationType(DownloadCreationType type) { type_ = type; } - - private: - download::DownloadItem::DownloadCreationType type_ = - download::DownloadItem::DownloadCreationType::TYPE_ACTIVE_DOWNLOAD; -}; - -IN_PROC_BROWSER_TEST_F(SavePackageFinishedObserverBrowserTest, Success) { - GURL url = - embedded_test_server()->GetURL("/save_page/brave-text-content.html"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); - auto* download_manager = - web_contents()->GetBrowserContext()->GetDownloadManager(); - { - base::RunLoop run_loop; - auto completed_callback = base::BindOnce( - [](base::OnceClosure callback, download::DownloadItem* item) { - EXPECT_EQ(item->GetState(), download::DownloadItem::COMPLETE); - EXPECT_EQ(item->GetDownloadCreationType(), - download::DownloadItem::TYPE_SAVE_PAGE_AS); - if (callback) - std::move(callback).Run(); - }, - run_loop.QuitClosure()); - base::FilePath saved_main_file_path; - base::FilePath saved_main_directory_path; - GetDestinationPaths("index", &saved_main_file_path, - &saved_main_directory_path); - SavePackageFinishedObserver finished_observer( - download_manager, saved_main_file_path, std::move(completed_callback)); - FakePackageDownloadItem item; - ASSERT_FALSE(finished_observer.HasInProgressDownload(&item)); - item.SetDownloadCreationType(download::DownloadItem::TYPE_SAVE_PAGE_AS); - ASSERT_FALSE(finished_observer.HasInProgressDownload(&item)); - item.SetTargetFilePath(saved_main_file_path); - ASSERT_TRUE(finished_observer.HasInProgressDownload(&item)); - ASSERT_FALSE(finished_observer.HasInProgressDownload(nullptr)); - web_contents()->SavePage(saved_main_file_path, saved_main_directory_path, - content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML); - - run_loop.Run(); - } -} diff --git a/browser/ipfs/ipfs_blob_context_getter_factory.cc b/browser/ipfs/ipfs_blob_context_getter_factory.cc deleted file mode 100644 index cc89794df371..000000000000 --- a/browser/ipfs/ipfs_blob_context_getter_factory.cc +++ /dev/null @@ -1,31 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_blob_context_getter_factory.h" - -#include - -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/storage_partition.h" - -namespace ipfs { - -IpfsBlobContextGetterFactory::IpfsBlobContextGetterFactory( - content::BrowserContext* browser_context) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - getter_callback_ = browser_context->GetBlobStorageContext(); - DCHECK(getter_callback_); -} - -IpfsBlobContextGetterFactory::~IpfsBlobContextGetterFactory() = default; - -base::WeakPtr -IpfsBlobContextGetterFactory::RetrieveStorageContext() { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - return getter_callback_.Run(); -} - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_blob_context_getter_factory.h b/browser/ipfs/ipfs_blob_context_getter_factory.h deleted file mode 100644 index a47679f81e12..000000000000 --- a/browser/ipfs/ipfs_blob_context_getter_factory.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IPFS_BLOB_CONTEXT_GETTER_FACTORY_H_ -#define BRAVE_BROWSER_IPFS_IPFS_BLOB_CONTEXT_GETTER_FACTORY_H_ - -#include "brave/components/ipfs/blob_context_getter_factory.h" - -namespace content { -class BrowserContext; -} // namespace content - -namespace ipfs { - -class IpfsBlobContextGetterFactory : public ipfs::BlobContextGetterFactory { - public: - explicit IpfsBlobContextGetterFactory(content::BrowserContext* context); - IpfsBlobContextGetterFactory(const IpfsBlobContextGetterFactory&) = delete; - IpfsBlobContextGetterFactory& operator=(const IpfsBlobContextGetterFactory&) = - delete; - ~IpfsBlobContextGetterFactory() override; - - private: - base::WeakPtr RetrieveStorageContext() override; - - ipfs::BlobContextGetter getter_callback_; -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IPFS_BLOB_CONTEXT_GETTER_FACTORY_H_ diff --git a/browser/ipfs/ipfs_blob_context_getter_factory_unittest.cc b/browser/ipfs/ipfs_blob_context_getter_factory_unittest.cc deleted file mode 100644 index 5d9cb04b229c..000000000000 --- a/browser/ipfs/ipfs_blob_context_getter_factory_unittest.cc +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_blob_context_getter_factory.h" - -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/run_loop.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile.h" -#include "chrome/test/base/testing_profile_manager.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/test/browser_task_environment.h" -#include "content/public/test/test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace { -constexpr char kTestProfileName[] = "TestProfile"; -} // namespace - -namespace ipfs { -class IpfsBlobContextGetterFactoryUnitTest : public testing::Test { - public: - IpfsBlobContextGetterFactoryUnitTest() = default; - IpfsBlobContextGetterFactoryUnitTest( - const IpfsBlobContextGetterFactoryUnitTest&) = delete; - IpfsBlobContextGetterFactoryUnitTest& operator=( - const IpfsBlobContextGetterFactoryUnitTest&) = delete; - ~IpfsBlobContextGetterFactoryUnitTest() override = default; - - void SetUp() override { - TestingBrowserProcess* browser_process = TestingBrowserProcess::GetGlobal(); - profile_manager_ = std::make_unique(browser_process); - ASSERT_TRUE(profile_manager_->SetUp()); - profile_ = profile_manager_->CreateTestingProfile(kTestProfileName); - } - void TearDown() override { - profile_ = nullptr; - profile_manager_->DeleteTestingProfile(kTestProfileName); - } - - content::BrowserContext* browser_context() { return profile_; } - - void RetrieveStorageIO(BlobContextGetterFactory* getter_factory, - base::OnceClosure closure) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - ASSERT_TRUE(getter_factory); - auto storage_context = getter_factory->RetrieveStorageContext(); - ASSERT_TRUE(storage_context); - std::move(closure).Run(); - } - - private: - content::BrowserTaskEnvironment task_environment_; - raw_ptr profile_ = nullptr; - std::unique_ptr profile_manager_; -}; - -TEST_F(IpfsBlobContextGetterFactoryUnitTest, GetStorageContext) { - IpfsBlobContextGetterFactory factory(browser_context()); - std::unique_ptr run_loop(new base::RunLoop()); - content::GetIOThreadTaskRunner({})->PostTask( - FROM_HERE, - base::BindOnce(&IpfsBlobContextGetterFactoryUnitTest::RetrieveStorageIO, - base::Unretained(this), &factory, - run_loop->QuitClosure())); - run_loop->Run(); - run_loop = std::make_unique(); - content::GetIOThreadTaskRunner({})->PostTask( - FROM_HERE, - base::BindOnce(&IpfsBlobContextGetterFactoryUnitTest::RetrieveStorageIO, - base::Unretained(this), &factory, - run_loop->QuitClosure())); - run_loop->Run(); -} - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_dns_resolver_impl.cc b/browser/ipfs/ipfs_dns_resolver_impl.cc deleted file mode 100644 index 10db31d5efd6..000000000000 --- a/browser/ipfs/ipfs_dns_resolver_impl.cc +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright (c) 2022 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_dns_resolver_impl.h" - -#include - -#include "base/time/time.h" -#include "chrome/browser/net/secure_dns_config.h" -#include "chrome/browser/net/system_network_context_manager.h" -#include "content/public/browser/network_service_instance.h" -#include "services/network/public/mojom/network_service.mojom.h" - -namespace ipfs { - -constexpr base::TimeDelta kRetryDelay = base::Seconds(1); - -mojo::Remote -GetDnsConfigChangeManager() { - mojo::Remote - dns_config_change_manager_remote; - content::GetNetworkService()->GetDnsConfigChangeManager( - dns_config_change_manager_remote.BindNewPipeAndPassReceiver()); - return dns_config_change_manager_remote; -} - -IpfsDnsResolverImpl::IpfsDnsResolverImpl() : weak_ptr_factory_(this) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - dns_config_change_manager_ = GetDnsConfigChangeManager(); - SetupDnsConfigChangeNotifications(); -} - -void IpfsDnsResolverImpl::SetupDnsConfigChangeNotifications() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - dns_config_change_manager_->RequestNotifications( - receiver_.BindNewPipeAndPassRemote()); - receiver_.set_disconnect_handler(base::BindOnce( - &IpfsDnsResolverImpl::OnDnsConfigChangeManagerConnectionError, - base::Unretained(this))); -} - -IpfsDnsResolverImpl::~IpfsDnsResolverImpl() = default; - -void IpfsDnsResolverImpl::OnDnsConfigChangeManagerConnectionError() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - receiver_.reset(); - // Throttle network service reconnect to prevent possible battery drain. - base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&IpfsDnsResolverImpl::SetupDnsConfigChangeNotifications, - weak_ptr_factory_.GetWeakPtr()), - kRetryDelay); -} - -void IpfsDnsResolverImpl::OnDnsConfigChanged() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - Notify(GetFirstDnsOverHttpsServer()); -} - -std::optional IpfsDnsResolverImpl::GetFirstDnsOverHttpsServer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - SecureDnsConfig secure_dns_config = - SystemNetworkContextManager::GetStubResolverConfigReader() - ->GetSecureDnsConfiguration( - false /* force_check_parental_controls_for_automatic_mode */); - const auto servers = secure_dns_config.doh_servers().servers(); - - if (secure_dns_config.mode() == net::SecureDnsMode::kOff || servers.empty()) { - return std::nullopt; - } - std::string server_template = servers[0].server_template(); - if (server_template.empty()) { - return std::nullopt; - } - return server_template; -} - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_dns_resolver_impl.h b/browser/ipfs/ipfs_dns_resolver_impl.h deleted file mode 100644 index bb723c1d0281..000000000000 --- a/browser/ipfs/ipfs_dns_resolver_impl.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright (c) 2022 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IPFS_DNS_RESOLVER_IMPL_H_ -#define BRAVE_BROWSER_IPFS_IPFS_DNS_RESOLVER_IMPL_H_ - -#include -#include - -#include "base/gtest_prod_util.h" -#include "base/sequence_checker.h" -#include "brave/components/ipfs/ipfs_dns_resolver.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "services/network/public/mojom/host_resolver.mojom.h" -#include "services/network/public/mojom/network_service.mojom.h" - -namespace ipfs { - -using base::SequenceChecker; - -class IpfsDnsResolverImpl - : public IpfsDnsResolver, - public network::mojom::DnsConfigChangeManagerClient { - public: - IpfsDnsResolverImpl(); - ~IpfsDnsResolverImpl() override; - IpfsDnsResolverImpl(const IpfsDnsResolverImpl&) = delete; - IpfsDnsResolverImpl& operator=(const IpfsDnsResolverImpl&) = delete; - - void OnDnsConfigChanged() override; - void OnDnsConfigChangeManagerConnectionError(); - - std::optional GetFirstDnsOverHttpsServer() override; - - private: - FRIEND_TEST_ALL_PREFIXES(IpfsDnsResolverImplUnitTest, ReconnectOnMojoError); - void SetupDnsConfigChangeNotifications(); - - mojo::Remote - dns_config_change_manager_; - mojo::Receiver receiver_{this}; - - SEQUENCE_CHECKER(sequence_checker_); - - base::WeakPtrFactory weak_ptr_factory_; -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IPFS_DNS_RESOLVER_IMPL_H_ diff --git a/browser/ipfs/ipfs_host_resolver.cc b/browser/ipfs/ipfs_host_resolver.cc deleted file mode 100644 index b16feecf25ee..000000000000 --- a/browser/ipfs/ipfs_host_resolver.cc +++ /dev/null @@ -1,121 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_host_resolver.h" - -#include -#include -#include - -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "chrome/browser/net/secure_dns_config.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/storage_partition.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "net/base/host_port_pair.h" -#include "net/dns/public/dns_protocol.h" - -namespace { - -// DNSLink values are of the form: dnslink= -// https://dnslink.io/#dnslink-format -const char kDnsLinkHeader[] = "dnslink"; - -// Expects dns TXT record in format: name=value -std::optional GetDNSRecordValue( - const std::vector& text_results, - const std::string& name) { - for (const auto& txt : text_results) { - std::vector tokens = base::SplitString( - txt, "=", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); - if (!tokens.size()) - continue; - if (tokens.front() != name) - continue; - return tokens.back(); - } - return std::nullopt; -} - -} // namespace - -namespace ipfs { - -IPFSHostResolver::IPFSHostResolver(content::BrowserContext* browser_context, - const std::string& prefix) - : prefix_(prefix), browser_context_(browser_context) {} -IPFSHostResolver::~IPFSHostResolver() = default; - -void IPFSHostResolver::Resolve( - const net::HostPortPair& host, - const net::NetworkAnonymizationKey& anonymization_key, - net::DnsQueryType dns_query_type, - HostTextResultsCallback callback) { - if (!callback) - return; - - if (host.host() == resolving_host_) { - if (callback) { - std::move(callback).Run(host.host(), dnslink_); - } - return; - } - - network::mojom::ResolveHostParametersPtr parameters = - network::mojom::ResolveHostParameters::New(); - parameters->dns_query_type = dns_query_type; - - receiver_.reset(); - resolved_callback_ = std::move(callback); - dnslink_ = std::nullopt; - resolving_host_ = host.host(); - net::HostPortPair local_host_port(prefix_ + resolving_host_, host.port()); - auto* network_context = GetNetworkContext(); - if (!network_context) { - return; - } - network_context->ResolveHost( - network::mojom::HostResolverHost::NewHostPortPair(local_host_port), - anonymization_key, std::move(parameters), - receiver_.BindNewPipeAndPassRemote()); -} - -network::mojom::NetworkContext* IPFSHostResolver::GetNetworkContext() { - if (network_context_for_testing_.has_value()) { - return network_context_for_testing_.value(); - } - auto* storage_partition = browser_context_->GetDefaultStoragePartition(); - if (!storage_partition) { - return nullptr; - } - return storage_partition->GetNetworkContext(); -} - -void IPFSHostResolver::OnComplete( - int result, - const net::ResolveErrorInfo& error_info, - const std::optional& list, - const std::optional& - endpoint_results_with_metadata) { - if (result != net::OK) { - VLOG(1) << "DNS resolving error:" << net::ErrorToString(result) - << " for host: " << prefix_ + resolving_host_; - if (resolved_callback_) { - std::move(resolved_callback_).Run(resolving_host_, std::nullopt); - } - } -} - -void IPFSHostResolver::OnTextResults(const std::vector& results) { - VLOG(2) << results.size() - << " TXT records resolved for host: " << prefix_ + resolving_host_; - dnslink_ = GetDNSRecordValue(results, kDnsLinkHeader); - - if (resolved_callback_) - std::move(resolved_callback_).Run(resolving_host_, dnslink_); -} - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_host_resolver.h b/browser/ipfs/ipfs_host_resolver.h deleted file mode 100644 index 8b63010796cd..000000000000 --- a/browser/ipfs/ipfs_host_resolver.h +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IPFS_HOST_RESOLVER_H_ -#define BRAVE_BROWSER_IPFS_IPFS_HOST_RESOLVER_H_ - -#include -#include -#include -#include - -#include "base/functional/callback_forward.h" -#include "base/memory/raw_ptr.h" -#include "chrome/browser/net/system_network_context_manager.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "net/base/host_port_pair.h" -#include "net/base/network_anonymization_key.h" -#include "net/dns/public/dns_query_type.h" -#include "services/network/public/cpp/resolve_host_client_base.h" -#include "services/network/public/mojom/host_resolver.mojom.h" - -namespace content { -class BrowserContext; -} // namespace content - -namespace ipfs { - -// Resolves DNS TXT record for hosts. If prefix passed then -// automatically adds it to the host. -class IPFSHostResolver : public network::ResolveHostClientBase { - public: - explicit IPFSHostResolver(content::BrowserContext* browser_context, - const std::string& prefix = std::string()); - ~IPFSHostResolver() override; - - using HostTextResultsCallback = - base::OnceCallback& dnslink)>; - - virtual void Resolve(const net::HostPortPair& host, - const net::NetworkAnonymizationKey& anonymization_key, - net::DnsQueryType dns_query_type, - HostTextResultsCallback callback); - - std::string host() const { return resolving_host_; } - std::optional dnslink() const { return dnslink_; } - void SetNetworkContextForTesting( - network::mojom::NetworkContext* network_context) { - network_context_for_testing_ = network_context; - } - - private: - // network::mojom::ResolveHostClient implementation: - void OnComplete(int result, - const net::ResolveErrorInfo& resolve_error_info, - const std::optional& resolved_addresses, - const std::optional& - endpoint_results_with_metadata) override; - void OnTextResults(const std::vector& text_results) override; - network::mojom::NetworkContext* GetNetworkContext(); - - std::string resolving_host_; - std::string prefix_; - std::optional dnslink_; - std::optional network_context_for_testing_; - - raw_ptr browser_context_; - HostTextResultsCallback resolved_callback_; - - mojo::Receiver receiver_{this}; -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IPFS_HOST_RESOLVER_H_ diff --git a/browser/ipfs/ipfs_host_resolver_unittest.cc b/browser/ipfs/ipfs_host_resolver_unittest.cc deleted file mode 100644 index ae7d9f7160bf..000000000000 --- a/browser/ipfs/ipfs_host_resolver_unittest.cc +++ /dev/null @@ -1,268 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_host_resolver.h" - -#include -#include -#include - -#include "base/run_loop.h" -#include "base/test/bind.h" -#include "base/test/task_environment.h" -#include "chrome/browser/net/secure_dns_config.h" -#include "chrome/browser/net/stub_resolver_config_reader.h" -#include "chrome/browser/net/system_network_context_manager.h" -#include "chrome/test/base/scoped_testing_local_state.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile.h" -#include "content/public/browser/network_service_instance.h" -#include "content/public/browser/storage_partition.h" -#include "content/public/test/browser_task_environment.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "services/network/host_resolver.h" -#include "services/network/network_context.h" -#include "services/network/network_service.h" -#include "services/network/public/cpp/resolve_host_client_base.h" -#include "services/network/public/mojom/host_resolver.mojom.h" -#include "services/network/public/mojom/network_context.mojom.h" -#include "services/network/test/test_network_context.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -class FakeHostResolver : public network::mojom::HostResolver { - public: - explicit FakeHostResolver(const std::string& expected_host) - : expected_host_(expected_host) {} - ~FakeHostResolver() override = default; - - // network::mojom::HostResolver - void ResolveHost( - network::mojom::HostResolverHostPtr host, - const net::NetworkAnonymizationKey& network_anonymization_key, - network::mojom::ResolveHostParametersPtr parameters, - mojo::PendingRemote - pending_response_client) override { - EXPECT_EQ(expected_host_, host->is_host_port_pair() - ? host->get_host_port_pair().host() - : host->get_scheme_host_port().host()); - EXPECT_EQ(parameters->dns_query_type, net::DnsQueryType::TXT); - mojo::Remote response_client; - response_client.Bind(std::move(pending_response_client)); - response_client->OnTextResults(text_results_); - resolve_host_called_++; - } - - void MdnsListen( - const ::net::HostPortPair& host, - ::net::DnsQueryType query_type, - ::mojo::PendingRemote response_client, - MdnsListenCallback callback) override {} - - int resolve_host_called() { return resolve_host_called_; } - - void RespondTextResults(const std::vector& text_results) { - text_results_ = text_results; - } - - void SetExpectedHost(const std::string& expected_host) { - expected_host_ = expected_host; - } - - protected: - int resolve_host_called_ = 0; - - private: - std::vector text_results_; - std::string expected_host_; -}; - -class FakeHostResolverFail : public FakeHostResolver { - public: - explicit FakeHostResolverFail(const std::string& expected_host) - : FakeHostResolver(expected_host) {} - ~FakeHostResolverFail() override = default; - - // network::mojom::HostResolver - void ResolveHost( - network::mojom::HostResolverHostPtr host, - const net::NetworkAnonymizationKey& network_anonymization_key, - network::mojom::ResolveHostParametersPtr parameters, - mojo::PendingRemote - pending_response_client) override { - mojo::Remote response_client; - response_client.Bind(std::move(pending_response_client)); - response_client->OnComplete(-2, net::ResolveErrorInfo(), std::nullopt, - std::nullopt); - resolve_host_called_++; - } -}; - -class FakeNetworkContext : public network::TestNetworkContext { - public: - FakeNetworkContext() = default; - ~FakeNetworkContext() override = default; - - // network::mojom::HostResolver - void ResolveHost( - network::mojom::HostResolverHostPtr host, - const net::NetworkAnonymizationKey& network_anonymization_key, - network::mojom::ResolveHostParametersPtr parameters, - mojo::PendingRemote - pending_response_client) override { - DCHECK(host_resolver_); - host_resolver_->ResolveHost(std::move(host), network_anonymization_key, - std::move(parameters), - std::move(pending_response_client)); - } - - void SetHostResolver( - std::unique_ptr host_resolver) { - host_resolver_ = std::move(host_resolver); - } - - private: - std::unique_ptr host_resolver_; -}; - -class IPFSHostResolverTest : public testing::Test { - public: - IPFSHostResolverTest() { - local_state_ = std::make_unique( - TestingBrowserProcess::GetGlobal()); - network_context_ = std::make_unique(); - } - - void HostResolvedCallback(base::OnceClosure callback, - const std::string& expected_host, - const std::string& host, - const std::optional& dnslink) { - EXPECT_EQ(expected_host, host); - resolved_callback_called_ = true; - if (callback) - std::move(callback).Run(); - } - - FakeNetworkContext* GetNetworkContext() { return network_context_.get(); } - - void SetResolvedCallbackCalled(bool value) { - resolved_callback_called_ = value; - } - bool resolved_callback_called() const { return resolved_callback_called_; } - - content::BrowserTaskEnvironment task_environment_; - bool resolved_callback_called_ = false; - std::unique_ptr network_context_; - std::unique_ptr local_state_; - std::unique_ptr stub_resolver_config_reader_; - base::WeakPtrFactory weak_ptr_factory_{this}; -}; - -TEST_F(IPFSHostResolverTest, PrefixRunSuccess) { - std::string prefix = "__dnslink."; - std::vector success = {"dnslink=abc", "a", "a=b", ""}; - std::string host = "example.com"; - - std::unique_ptr fake_host_resolver( - new FakeHostResolver(prefix + host)); - fake_host_resolver->RespondTextResults(success); - auto* network_context = GetNetworkContext(); - auto* fake_host_resolver_raw = fake_host_resolver.get(); - network_context->SetHostResolver(std::move(fake_host_resolver)); - base::RunLoop run_loop; - ipfs::IPFSHostResolver ipfs_resolver(nullptr, prefix); - ipfs_resolver.SetNetworkContextForTesting(network_context); - - SetResolvedCallbackCalled(false); - ipfs_resolver.Resolve( - net::HostPortPair(host, 11), net::NetworkAnonymizationKey(), - net::DnsQueryType::TXT, - base::BindOnce(&IPFSHostResolverTest::HostResolvedCallback, - weak_ptr_factory_.GetWeakPtr(), run_loop.QuitClosure(), - host)); - - run_loop.Run(); - EXPECT_EQ(ipfs_resolver.host(), host); - EXPECT_EQ(ipfs_resolver.dnslink(), "abc"); - EXPECT_EQ(fake_host_resolver_raw->resolve_host_called(), 1); - EXPECT_TRUE(resolved_callback_called()); -} - -TEST_F(IPFSHostResolverTest, SuccessOnReuse) { - std::string prefix = "__dnslink."; - std::vector success = {"dnslink=abc", "a", "a=b", ""}; - std::string host = "example.com"; - - std::unique_ptr fake_host_resolver( - new FakeHostResolver(prefix + host)); - fake_host_resolver->RespondTextResults(success); - auto* network_context = GetNetworkContext(); - auto* fake_host_resolver_raw = fake_host_resolver.get(); - network_context->SetHostResolver(std::move(fake_host_resolver)); - ipfs::IPFSHostResolver ipfs_resolver(nullptr, prefix); - ipfs_resolver.SetNetworkContextForTesting(network_context); - - SetResolvedCallbackCalled(false); - { - base::RunLoop run_loop; - ipfs_resolver.Resolve( - net::HostPortPair(host, 11), net::NetworkAnonymizationKey(), - net::DnsQueryType::TXT, - base::BindOnce(&IPFSHostResolverTest::HostResolvedCallback, - weak_ptr_factory_.GetWeakPtr(), run_loop.QuitClosure(), - host)); - run_loop.Run(); - } - - EXPECT_EQ(ipfs_resolver.host(), host); - EXPECT_EQ(ipfs_resolver.dnslink(), "abc"); - EXPECT_EQ(fake_host_resolver_raw->resolve_host_called(), 1); - EXPECT_TRUE(resolved_callback_called()); - { - base::RunLoop run_loop; - std::string expected_host = host; - ipfs_resolver.Resolve(net::HostPortPair(host, 11), - net::NetworkAnonymizationKey(), - net::DnsQueryType::TXT, - base::BindLambdaForTesting( - [&run_loop, &expected_host]( - const std::string& host, - const std::optional& dnslink) { - EXPECT_EQ(expected_host, host); - EXPECT_EQ(dnslink.value(), "abc"); - run_loop.Quit(); - })); - run_loop.Run(); - } - EXPECT_EQ(fake_host_resolver_raw->resolve_host_called(), 1); - EXPECT_EQ(ipfs_resolver.dnslink(), "abc"); -} - -TEST_F(IPFSHostResolverTest, ResolutionFailed) { - std::string host = "example.com"; - std::unique_ptr fake_host_resolver( - new FakeHostResolverFail(host)); - auto* network_context = GetNetworkContext(); - auto* fake_host_resolver_raw = fake_host_resolver.get(); - network_context->SetHostResolver(std::move(fake_host_resolver)); - ipfs::IPFSHostResolver ipfs_resolver(nullptr); - ipfs_resolver.SetNetworkContextForTesting(network_context); - base::RunLoop run_loop; - ipfs_resolver.Resolve( - net::HostPortPair(host, 11), net::NetworkAnonymizationKey(), - net::DnsQueryType::TXT, - base::BindLambdaForTesting( - [&run_loop](const std::string& host, - const std::optional& dnslink) { - EXPECT_FALSE(dnslink); - run_loop.Quit(); - })); - run_loop.Run(); - EXPECT_EQ(ipfs_resolver.host(), host); - EXPECT_FALSE(ipfs_resolver.dnslink()); - EXPECT_EQ(fake_host_resolver_raw->resolve_host_called(), 1); -} diff --git a/browser/ipfs/ipfs_local_pin_service_factory.cc b/browser/ipfs/ipfs_local_pin_service_factory.cc deleted file mode 100644 index 5f412b163492..000000000000 --- a/browser/ipfs/ipfs_local_pin_service_factory.cc +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2023 The Brave Authors. All rights reserved. -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at https://mozilla.org/MPL/2.0/. - -#include "brave/browser/ipfs/ipfs_local_pin_service_factory.h" - -#include -#include - -#include "base/no_destructor.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/ipfs/pin/ipfs_local_pin_service.h" -#include "chrome/browser/profiles/incognito_helpers.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/prefs/pref_service.h" -#include "components/user_prefs/user_prefs.h" - -namespace ipfs { - -// static -IpfsLocalPinServiceFactory* IpfsLocalPinServiceFactory::GetInstance() { - static base::NoDestructor instance; - return instance.get(); -} - -// static -IpfsLocalPinService* IpfsLocalPinServiceFactory::GetServiceForContext( - content::BrowserContext* context) { - if (!ipfs::IpfsServiceFactory::IsIpfsEnabled(context)) { - return nullptr; - } - return static_cast( - GetInstance()->GetServiceForBrowserContext(context, true)); -} - -IpfsLocalPinServiceFactory::IpfsLocalPinServiceFactory() - : BrowserContextKeyedServiceFactory( - "IpfsLocalPinService", - BrowserContextDependencyManager::GetInstance()) { - DependsOn(ipfs::IpfsServiceFactory::GetInstance()); -} - -IpfsLocalPinServiceFactory::~IpfsLocalPinServiceFactory() = default; - -KeyedService* IpfsLocalPinServiceFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - return new IpfsLocalPinService(user_prefs::UserPrefs::Get(context), - IpfsServiceFactory::GetForContext(context)); -} - -content::BrowserContext* IpfsLocalPinServiceFactory::GetBrowserContextToUse( - content::BrowserContext* context) const { - return chrome::GetBrowserContextRedirectedInIncognito(context); -} - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_local_pin_service_factory.h b/browser/ipfs/ipfs_local_pin_service_factory.h deleted file mode 100644 index 724cdc391136..000000000000 --- a/browser/ipfs/ipfs_local_pin_service_factory.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2023 The Brave Authors. All rights reserved. -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at https://mozilla.org/MPL/2.0/. - -#ifndef BRAVE_BROWSER_IPFS_IPFS_LOCAL_PIN_SERVICE_FACTORY_H_ -#define BRAVE_BROWSER_IPFS_IPFS_LOCAL_PIN_SERVICE_FACTORY_H_ - -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" -#include "components/keyed_service/core/keyed_service.h" -#include "content/public/browser/browser_context.h" - -namespace base { -template -class NoDestructor; -} // namespace base - -namespace ipfs { - -class IpfsLocalPinService; - -class IpfsLocalPinServiceFactory : public BrowserContextKeyedServiceFactory { - public: - static IpfsLocalPinService* GetServiceForContext( - content::BrowserContext* context); - static IpfsLocalPinServiceFactory* GetInstance(); - - private: - friend base::NoDestructor; - - IpfsLocalPinServiceFactory(); - ~IpfsLocalPinServiceFactory() override; - - IpfsLocalPinServiceFactory(const IpfsLocalPinServiceFactory&) = delete; - IpfsLocalPinServiceFactory& operator=(const IpfsLocalPinServiceFactory&) = - delete; - - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; - content::BrowserContext* GetBrowserContextToUse( - content::BrowserContext* context) const override; -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IPFS_LOCAL_PIN_SERVICE_FACTORY_H_ diff --git a/browser/ipfs/ipfs_policy_browsertest.cc b/browser/ipfs/ipfs_policy_browsertest.cc deleted file mode 100644 index ecd752c83ad8..000000000000 --- a/browser/ipfs/ipfs_policy_browsertest.cc +++ /dev/null @@ -1,173 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "base/test/scoped_feature_list.h" -#include "base/values.h" -#include "brave/browser/ipfs/content_browser_client_helper.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/browser/ipfs/ipfs_tab_helper.h" -#include "brave/components/ipfs/features.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_navigation_throttle.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "components/policy/core/browser/browser_policy_connector.h" -#include "components/policy/core/common/mock_configuration_policy_provider.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/policy_constants.h" -#include "components/prefs/pref_service.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "content/public/test/mock_navigation_handle.h" -#include "content/public/test/navigation_handle_observer.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "url/gurl.h" - -#include "components/infobars/core/infobar.h" - -namespace policy { - -template -class IpfsPolicyTest : public InProcessBrowserTest { - public: - IpfsPolicyTest() { - feature_list_.InitAndEnableFeature(ipfs::features::kIpfsFeature); - } - - void SetUpOnMainThread() override { - InProcessBrowserTest::SetUpOnMainThread(); - ASSERT_TRUE(embedded_test_server()->Start()); - ipfs_url_ = GURL( - "ipfs://bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq/" - "wiki/Vincent_van_Gogh.html"); - - auto* prefs = user_prefs::UserPrefs::Get(browser_context()); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)); - } - - void SetUpInProcessBrowserTestFixture() override { - EXPECT_CALL(provider_, IsInitializationComplete(testing::_)) - .WillRepeatedly(testing::Return(true)); - BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); - PolicyMap policies; - policies.Set(key::kIPFSEnabled, POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, POLICY_SOURCE_PLATFORM, - base::Value(enable), nullptr); - provider_.UpdateChromePolicy(policies); - } - PrefService* prefs() { return user_prefs::UserPrefs::Get(browser_context()); } - content::WebContents* web_contents() const { - return browser()->tab_strip_model()->GetActiveWebContents(); - } - - content::BrowserContext* browser_context() { - return web_contents()->GetBrowserContext(); - } - - const GURL& ipfs_url() { return ipfs_url_; } - - private: - MockConfigurationPolicyProvider provider_; - base::test::ScopedFeatureList feature_list_; - GURL ipfs_url_; -}; - -using IpfsEnabledPolicyTest = IpfsPolicyTest; -using IpfsDisabledPolicyTest = IpfsPolicyTest; - -IN_PROC_BROWSER_TEST_F(IpfsEnabledPolicyTest, IsIpfsDisabledByPolicy) { - auto* prefs = user_prefs::UserPrefs::Get(browser_context()); - EXPECT_FALSE(ipfs::IsIpfsDisabledByPolicy(prefs)); - EXPECT_TRUE(prefs->FindPreference(kIPFSEnabled)); - EXPECT_TRUE(prefs->GetBoolean(kIPFSEnabled)); -} - -IN_PROC_BROWSER_TEST_F(IpfsDisabledPolicyTest, IsIpfsDisabledByPolicy) { - auto* prefs = user_prefs::UserPrefs::Get(browser_context()); - EXPECT_TRUE(ipfs::IsIpfsDisabledByPolicy(prefs)); - EXPECT_TRUE(prefs->FindPreference(kIPFSEnabled)); - EXPECT_FALSE(prefs->GetBoolean(kIPFSEnabled)); -} - -IN_PROC_BROWSER_TEST_F(IpfsEnabledPolicyTest, GetService) { - EXPECT_NE(ipfs::IpfsServiceFactory::GetForContext(browser_context()), - nullptr); -} - -IN_PROC_BROWSER_TEST_F(IpfsDisabledPolicyTest, GetService) { - EXPECT_EQ(ipfs::IpfsServiceFactory::GetForContext(browser_context()), - nullptr); -} - -IN_PROC_BROWSER_TEST_F(IpfsEnabledPolicyTest, IPFSPageAccess) { - content::NavigationHandleObserver observer(web_contents(), - GURL("chrome://ipfs-internals")); - EXPECT_TRUE( - ui_test_utils::NavigateToURL(browser(), GURL("chrome://ipfs-internals"))); - EXPECT_TRUE(observer.has_committed()); - EXPECT_FALSE(observer.is_error()); -} - -IN_PROC_BROWSER_TEST_F(IpfsDisabledPolicyTest, IPFSPageAccess) { - content::NavigationHandleObserver observer(web_contents(), - GURL("chrome://ipfs-internals")); - EXPECT_TRUE( - ui_test_utils::NavigateToURL(browser(), GURL("chrome://ipfs-internals"))); - EXPECT_TRUE(observer.has_committed()); - EXPECT_TRUE(observer.is_error()); -} - -IN_PROC_BROWSER_TEST_F(IpfsDisabledPolicyTest, IPFSPageAccessWithRedirect) { - content::NavigationHandleObserver observer(web_contents(), - GURL("chrome://ipfs-internals")); - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("chrome://ipfs"))); - EXPECT_TRUE(observer.has_committed()); - EXPECT_TRUE(observer.is_error()); -} - -IN_PROC_BROWSER_TEST_F(IpfsEnabledPolicyTest, NavigationThrottle) { - content::MockNavigationHandle test_handle(web_contents()); - auto throttle = ipfs::IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, ipfs::IpfsServiceFactory::GetForContext(browser_context()), - prefs(), "en-US"); - EXPECT_TRUE(throttle != nullptr); -} - -IN_PROC_BROWSER_TEST_F(IpfsDisabledPolicyTest, NavigationThrottle) { - content::MockNavigationHandle test_handle(web_contents()); - auto throttle = ipfs::IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, ipfs::IpfsServiceFactory::GetForContext(browser_context()), - prefs(), "en-US"); - EXPECT_TRUE(throttle == nullptr); -} - -IN_PROC_BROWSER_TEST_F(IpfsEnabledPolicyTest, TabHelper) { - EXPECT_TRUE(ipfs::IPFSTabHelper::MaybeCreateForWebContents(web_contents())); -} - -IN_PROC_BROWSER_TEST_F(IpfsDisabledPolicyTest, TabHelper) { - EXPECT_FALSE(ipfs::IPFSTabHelper::MaybeCreateForWebContents(web_contents())); -} - -IN_PROC_BROWSER_TEST_F(IpfsEnabledPolicyTest, HandleIPFSURLRewrite) { - GURL url(ipfs_url()); - EXPECT_TRUE(ipfs::HandleIPFSURLRewrite(&url, browser_context())); -} - -IN_PROC_BROWSER_TEST_F(IpfsDisabledPolicyTest, HandleIPFSURLRewrite) { - GURL url(ipfs_url()); - EXPECT_FALSE(ipfs::HandleIPFSURLRewrite(&url, browser_context())); -} - -} // namespace policy diff --git a/browser/ipfs/ipfs_service_factory.cc b/browser/ipfs/ipfs_service_factory.cc deleted file mode 100644 index 1e812a450267..000000000000 --- a/browser/ipfs/ipfs_service_factory.cc +++ /dev/null @@ -1,118 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_service_factory.h" - -#include -#include - -#include "base/no_destructor.h" -#include "base/path_service.h" -#include "brave/browser/brave_browser_process.h" -#include "brave/browser/ipfs/ipfs_blob_context_getter_factory.h" -#include "brave/browser/ipfs/ipfs_dns_resolver_impl.h" -#include "brave/browser/ipfs/ipfs_service_impl_delegate.h" -#include "brave/browser/profiles/profile_util.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "chrome/common/channel_info.h" -#include "chrome/common/chrome_paths.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/storage_partition.h" -#include "extensions/buildflags/buildflags.h" - -#if BUILDFLAG(ENABLE_EXTENSIONS) -#include "base/metrics/histogram_macros.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_registry_factory.h" -#include "extensions/browser/extension_system.h" -#include "extensions/browser/extension_system_provider.h" -#include "extensions/browser/extensions_browser_client.h" -#endif - -#if !BUILDFLAG(IS_ANDROID) -#include "brave/browser/infobars/brave_global_infobar_service_factory.h" -#endif - -namespace { -#if BUILDFLAG(ENABLE_EXTENSIONS) -// IPFS companion installed? -// i) No, ii) Yes -void RecordIPFSCompanionInstalled(extensions::ExtensionRegistry* registry) { - const char ipfs_companion_extension_id[] = "nibjojkomfdiaoajekhjakgkdhaomnch"; - DCHECK(registry); - bool installed = - registry->enabled_extensions().Contains(ipfs_companion_extension_id); - UMA_HISTOGRAM_BOOLEAN("Brave.IPFS.IPFSCompanionInstalled", installed); -} -#endif -} // namespace - -namespace ipfs { - -// static -IpfsServiceFactory* IpfsServiceFactory::GetInstance() { - static base::NoDestructor instance; - return instance.get(); -} - -// static -IpfsService* IpfsServiceFactory::GetForContext( - content::BrowserContext* context) { - if (!IpfsServiceFactory::IsIpfsEnabled(context)) - return nullptr; - - return static_cast( - GetInstance()->GetServiceForBrowserContext(context, true)); -} - -IpfsServiceFactory::IpfsServiceFactory() - : BrowserContextKeyedServiceFactory( - "IpfsService", - BrowserContextDependencyManager::GetInstance()) { -#if BUILDFLAG(ENABLE_EXTENSIONS) - DependsOn(extensions::ExtensionRegistryFactory::GetInstance()); - DependsOn( - extensions::ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); -#endif -} - -IpfsServiceFactory::~IpfsServiceFactory() = default; - -KeyedService* IpfsServiceFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - base::FilePath user_data_dir; - base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); - auto url_loader = context->GetDefaultStoragePartition() - ->GetURLLoaderFactoryForBrowserProcess(); - auto context_getter = std::make_unique(context); - auto* ipfs_updater = g_brave_browser_process - ? g_brave_browser_process->ipfs_client_updater() - : nullptr; -#if BUILDFLAG(ENABLE_EXTENSIONS) - RecordIPFSCompanionInstalled(extensions::ExtensionRegistry::Get(context)); -#endif - return new IpfsService( - user_prefs::UserPrefs::Get(context), std::move(url_loader), - std::move(context_getter), ipfs_updater, user_data_dir, - chrome::GetChannel(), std::make_unique(), - std::make_unique( - user_prefs::UserPrefs::Get(context) -#if !BUILDFLAG(IS_ANDROID) - , - BraveGlobalInfobarServiceFactory::GetForBrowserContext(context) -#endif - )); -} - -// static -bool IpfsServiceFactory::IsIpfsEnabled(content::BrowserContext* context) { - auto* prefs = user_prefs::UserPrefs::Get(context); - return (brave::IsRegularProfile(context) && - !IsIpfsDisabledByFeatureOrPolicy(prefs)); -} - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_service_factory.h b/browser/ipfs/ipfs_service_factory.h deleted file mode 100644 index daad4efaba16..000000000000 --- a/browser/ipfs/ipfs_service_factory.h +++ /dev/null @@ -1,42 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IPFS_SERVICE_FACTORY_H_ -#define BRAVE_BROWSER_IPFS_IPFS_SERVICE_FACTORY_H_ - -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -namespace base { -template -class NoDestructor; -} // namespace base - -class Profile; -namespace ipfs { -class IpfsService; - -class IpfsServiceFactory : public BrowserContextKeyedServiceFactory { - public: - IpfsServiceFactory(const IpfsServiceFactory&) = delete; - IpfsServiceFactory& operator=(const IpfsServiceFactory&) = delete; - - static IpfsService* GetForContext(content::BrowserContext* context); - static IpfsServiceFactory* GetInstance(); - static bool IsIpfsEnabled(content::BrowserContext* context); - - private: - friend base::NoDestructor; - - IpfsServiceFactory(); - ~IpfsServiceFactory() override; - - // BrowserContextKeyedServiceFactory overrides: - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IPFS_SERVICE_FACTORY_H_ diff --git a/browser/ipfs/ipfs_service_impl_delegate.cc b/browser/ipfs/ipfs_service_impl_delegate.cc deleted file mode 100644 index 24afbe8ff521..000000000000 --- a/browser/ipfs/ipfs_service_impl_delegate.cc +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_service_impl_delegate.h" - -#include - -#include "brave/browser/infobars/brave_ipfs_always_start_infobar_delegate.h" -#if !BUILDFLAG(IS_ANDROID) -#include "brave/browser/infobars/brave_global_infobar_service.h" -#endif // !BUILDFLAG(IS_ANDROID) - -namespace ipfs { - -IpfsServiceImplDelegate::IpfsServiceImplDelegate( - PrefService* local_state -#if !BUILDFLAG(IS_ANDROID) - , - BraveGlobalInfobarService* global_infobar_service -#endif // !BUILDFLAG(IS_ANDROID) - ) - : local_state_(local_state) -#if !BUILDFLAG(IS_ANDROID) - , - global_infobar_service_(global_infobar_service) -#endif // !BUILDFLAG(IS_ANDROID) -{ -} - -IpfsServiceImplDelegate::~IpfsServiceImplDelegate() = default; - -void IpfsServiceImplDelegate::OnImportToIpfsFinished( - IpfsService* ipfs_service) { -#if !BUILDFLAG(IS_ANDROID) - if (global_infobar_service_) { - global_infobar_service_->ShowAlwaysStartInfobar(); - } -#endif // !BUILDFLAG(IS_ANDROID) -} - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_service_impl_delegate.h b/browser/ipfs/ipfs_service_impl_delegate.h deleted file mode 100644 index 898339872f3c..000000000000 --- a/browser/ipfs/ipfs_service_impl_delegate.h +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (c) 2023 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IPFS_SERVICE_IMPL_DELEGATE_H_ -#define BRAVE_BROWSER_IPFS_IPFS_SERVICE_IMPL_DELEGATE_H_ - -#include "base/memory/raw_ptr.h" -#include "brave/components/ipfs/ipfs_service_delegate.h" -#include "build/build_config.h" - -class PrefService; -#if !BUILDFLAG(IS_ANDROID) -class BraveGlobalInfobarService; -#endif // !BUILDFLAG(IS_ANDROID) - -namespace ipfs { - -class IpfsServiceImplDelegate : public IpfsServiceDelegate { - public: - explicit IpfsServiceImplDelegate( - PrefService* local_state -#if !BUILDFLAG(IS_ANDROID) - , - BraveGlobalInfobarService* global_infobar_service -#endif // !BUILDFLAG(IS_ANDROID) - ); - ~IpfsServiceImplDelegate() override; - void OnImportToIpfsFinished(IpfsService* ipfs_service) override; - - private: - raw_ptr local_state_ = nullptr; -#if !BUILDFLAG(IS_ANDROID) - raw_ptr global_infobar_service_; -#endif // !BUILDFLAG(IS_ANDROID) -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IPFS_SERVICE_IMPL_DELEGATE_H_ diff --git a/browser/ipfs/ipfs_subframe_navigation_throttle.cc b/browser/ipfs/ipfs_subframe_navigation_throttle.cc deleted file mode 100644 index 5769c0f361bb..000000000000 --- a/browser/ipfs/ipfs_subframe_navigation_throttle.cc +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (c) 2022 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_subframe_navigation_throttle.h" - -#include "brave/components/ipfs/ipfs_constants.h" - -namespace ipfs { - -// static -std::unique_ptr -IpfsSubframeNavigationThrottle::CreateThrottleFor( - content::NavigationHandle* navigation_handle) { - return std::make_unique(navigation_handle); -} - -IpfsSubframeNavigationThrottle::IpfsSubframeNavigationThrottle( - content::NavigationHandle* navigation_handle) - : content::NavigationThrottle(navigation_handle) {} - -IpfsSubframeNavigationThrottle::~IpfsSubframeNavigationThrottle() = default; - -// content::NavigationThrottle implementation: -content::NavigationThrottle::ThrottleCheckResult -IpfsSubframeNavigationThrottle::WillFailRequest() { - // Ignores subframe ipfs:// navigation. It is ok to commit toplevel - // navigation. - if (!navigation_handle()->IsInMainFrame() && - (navigation_handle()->GetURL().SchemeIs(ipfs::kIPFSScheme) || - navigation_handle()->GetURL().SchemeIs(ipfs::kIPNSScheme))) { - return {content::NavigationThrottle::CANCEL_AND_IGNORE, - navigation_handle()->GetNetErrorCode()}; - } - return content::NavigationThrottle::PROCEED; -} - -const char* IpfsSubframeNavigationThrottle::GetNameForLogging() { - return "IpfsSubframeNavigationThrottle"; -} - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_subframe_navigation_throttle.h b/browser/ipfs/ipfs_subframe_navigation_throttle.h deleted file mode 100644 index a37ead16c79d..000000000000 --- a/browser/ipfs/ipfs_subframe_navigation_throttle.h +++ /dev/null @@ -1,42 +0,0 @@ -/* Copyright (c) 2022 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IPFS_SUBFRAME_NAVIGATION_THROTTLE_H_ -#define BRAVE_BROWSER_IPFS_IPFS_SUBFRAME_NAVIGATION_THROTTLE_H_ - -#include - -#include "content/public/browser/navigation_handle.h" -#include "content/public/browser/navigation_throttle.h" - -namespace ipfs { - -// Prevents commiting of subframe IPFS navigations. -// IPFS urls must be changed to proper gateway urls. -// See ipfs_redirect_network_delegate_helper.h for example. -class IpfsSubframeNavigationThrottle : public content::NavigationThrottle { - public: - static std::unique_ptr CreateThrottleFor( - content::NavigationHandle* navigation_handle); - - explicit IpfsSubframeNavigationThrottle( - content::NavigationHandle* navigation_handle); - ~IpfsSubframeNavigationThrottle() override; - - IpfsSubframeNavigationThrottle(const IpfsSubframeNavigationThrottle&) = - delete; - IpfsSubframeNavigationThrottle& operator=( - const IpfsSubframeNavigationThrottle&) = delete; - - // content::NavigationThrottle implementation: - // This is called before navigation commits with error. - // Here we can cancel subframe navigation for ipfs:// urls. - content::NavigationThrottle::ThrottleCheckResult WillFailRequest() override; - const char* GetNameForLogging() override; -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IPFS_SUBFRAME_NAVIGATION_THROTTLE_H_ diff --git a/browser/ipfs/ipfs_tab_helper.cc b/browser/ipfs/ipfs_tab_helper.cc deleted file mode 100644 index fd7afbae1925..000000000000 --- a/browser/ipfs/ipfs_tab_helper.cc +++ /dev/null @@ -1,553 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_tab_helper.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/supports_user_data.h" -#include "brave/browser/infobars/brave_global_infobar_service.h" -#include "brave/browser/infobars/brave_ipfs_fallback_infobar_delegate.h" -#include "brave/browser/ipfs/ipfs_host_resolver.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/constants/pref_names.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/pref_names.h" -#include "build/buildflag.h" -#include "chrome/browser/shell_integration.h" -#include "chrome/common/channel_info.h" -#include "components/prefs/pref_service.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/navigation_controller.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/browser/web_contents_delegate.h" -#include "content/public/common/url_constants.h" -#include "net/base/url_util.h" -#include "net/http/http_status_code.h" -#include "url/gurl.h" -#include "url/origin.h" - -#if !BUILDFLAG(IS_ANDROID) -#include "brave/browser/infobars/brave_global_infobar_service_factory.h" -#include "brave/browser/infobars/brave_ipfs_always_start_infobar_delegate.h" -#include "brave/browser/infobars/brave_ipfs_infobar_delegate.h" -#include "brave/browser/ui/views/infobars/brave_global_infobar_manager.h" -#endif - -namespace { - -// We have to check both domain and _dnslink.domain -// https://dnslink.io/#can-i-use-dnslink-in-non-dns-systems -const char kDnsDomainPrefix[] = "_dnslink."; - -// IPFS HTTP gateways can return an x-ipfs-path header with each response. -// The value of the header is the IPFS path of the returned payload. -const char kIfpsPathHeader[] = "x-ipfs-path"; - -#if !BUILDFLAG(IS_ANDROID) -const char kIpfsFallbackOriginalUrlKey[] = "ipfs-fallback-original-url"; -const char kIpfsFallbackBlockRedirectForNavEntryIdKey[] = - "ipfs-fallback-block-redirect-for-nav-entry-id"; - -struct IpfsFallbackOriginalUrlData : public base::SupportsUserData::Data { - explicit IpfsFallbackOriginalUrlData(const GURL& url) : original_url(url) {} - ~IpfsFallbackOriginalUrlData() override = default; - - GURL original_url; -}; -struct IpfsFallbackBlockRedirectData : public base::SupportsUserData::Data { - explicit IpfsFallbackBlockRedirectData(const bool& enable_block) - : enable_redirect_block(enable_block) {} - ~IpfsFallbackBlockRedirectData() override = default; - - bool enable_redirect_block; -}; - -bool IsClientOrServerHttpError(content::NavigationHandle* handle) { - auto const* headers = handle->GetResponseHeaders(); - return headers && headers->response_code() >= net::HTTP_BAD_REQUEST; -} -#endif // !BUILDFLAG(IS_ANDROID) - -// Sets current executable as default protocol handler in a system. -void SetupIPFSProtocolHandler(const std::string& protocol) { - auto isDefaultCallback = [](const std::string& protocol, - shell_integration::DefaultWebClientState state) { - if (state == shell_integration::IS_DEFAULT) { - VLOG(1) << protocol << " already has a handler"; - return; - } - VLOG(1) << "Set as default handler for " << protocol; - // The worker pointer is reference counted. While it is running, the - // sequence it runs on will hold references it will be automatically - // freed once all its tasks have finished. - base::MakeRefCounted(protocol) - ->StartSetAsDefault(base::NullCallback()); - }; - - base::MakeRefCounted(protocol) - ->StartCheckIsDefault(base::BindOnce(isDefaultCallback, protocol)); -} - -} // namespace - -namespace ipfs { - -#if !BUILDFLAG(IS_ANDROID) -class BraveIPFSInfoBarDelegateObserverImpl - : public BraveIPFSInfoBarDelegateObserver { - public: - explicit BraveIPFSInfoBarDelegateObserverImpl( - base::WeakPtr ipfs_tab_helper) - : ipfs_tab_helper_(ipfs_tab_helper) {} - - void OnRedirectToIPFS(bool enable_gateway_autoredirect) override { - if (ipfs_tab_helper_ && ipfs_tab_helper_->ipfs_resolved_url_.is_valid()) { - if (enable_gateway_autoredirect) { - ipfs_tab_helper_->pref_service_->SetBoolean( - kIPFSAutoRedirectToConfiguredGateway, true); - } - ipfs_tab_helper_->LoadUrl(ipfs_tab_helper_->ipfs_resolved_url_); - } - } - - ~BraveIPFSInfoBarDelegateObserverImpl() override = default; - - private: - base::WeakPtr ipfs_tab_helper_; -}; - -class BraveIPFSFallbackInfoBarDelegateObserverImpl - : public BraveIPFSFallbackInfoBarDelegateObserver { - public: - explicit BraveIPFSFallbackInfoBarDelegateObserverImpl( - base::WeakPtr ipfs_tab_helper, - const GURL& original_url) - : original_url_(original_url), ipfs_tab_helper_(ipfs_tab_helper) {} - - void OnRedirectToOriginalAddress() override { - if (ipfs_tab_helper_) { - ipfs_tab_helper_->LoadUrlForFallback(original_url_); - } - } - - ~BraveIPFSFallbackInfoBarDelegateObserverImpl() override = default; - - private: - GURL original_url_; - base::WeakPtr ipfs_tab_helper_; -}; - -#endif // !BUILDFLAG(IS_ANDROID) - -IPFSTabHelper::~IPFSTabHelper() = default; - -IPFSTabHelper::IPFSTabHelper(content::WebContents* web_contents) - : content::WebContentsObserver(web_contents), - IpfsImportController(*web_contents), - content::WebContentsUserData(*web_contents), - pref_service_( - user_prefs::UserPrefs::Get(web_contents->GetBrowserContext())) -#if !BUILDFLAG(IS_ANDROID) - , - global_infobar_service_( - BraveGlobalInfobarServiceFactory::GetForBrowserContext( - web_contents->GetBrowserContext())) -#endif // !BUILDFLAG(IS_ANDROID) -{ - resolver_ = std::make_unique( - web_contents->GetBrowserContext(), kDnsDomainPrefix); - pref_change_registrar_.Init(pref_service_); - pref_change_registrar_.Add( - kIPFSResolveMethod, - base::BindRepeating(&IPFSTabHelper::UpdateDnsLinkButtonState, - base::Unretained(this))); -} - -// static -bool IPFSTabHelper::MaybeCreateForWebContents( - content::WebContents* web_contents) { - if (!ipfs::IpfsServiceFactory::GetForContext( - web_contents->GetBrowserContext())) { - return false; - } - - CreateForWebContents(web_contents); - return true; -} - -void IPFSTabHelper::IPFSResourceLinkResolved(const GURL& ipfs) { - ipfs_resolved_url_ = ipfs.is_valid() ? ipfs : GURL(); - UpdateLocationBar(); -} - -#if !BUILDFLAG(IS_ANDROID) -bool IPFSTabHelper::IsResolveMethod( - const ipfs::IPFSResolveMethodTypes& resolution_method) { - return pref_service_->GetInteger(kIPFSResolveMethod) == - static_cast(resolution_method); -} -#endif // !BUILDFLAG(IS_ANDROID) - -void IPFSTabHelper::DNSLinkResolved(const GURL& ipfs, - bool is_gateway_url, - const bool& auto_redirect_blocked) { - DCHECK(!ipfs.is_valid() || ipfs.SchemeIs(kIPNSScheme)); - ipfs_resolved_url_ = ipfs.is_valid() ? ipfs : GURL(); - bool should_redirect = - pref_service_->GetBoolean(kIPFSAutoRedirectToConfiguredGateway); - - if (ipfs.is_valid() && should_redirect -#if !BUILDFLAG(IS_ANDROID) - && !auto_redirect_blocked) { - LoadUrlForAutoRedirect(GetIPFSResolvedURL()); - if (IsResolveMethod(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)) { - global_infobar_service_->ShowAlwaysStartInfobar(); - } -#else - ) { - LoadUrl(GetIPFSResolvedURL()); -#endif // !BUILDFLAG(IS_ANDROID) - return; - } - UpdateLocationBar(); -} - -void IPFSTabHelper::HostResolvedCallback( - const GURL& current, - const GURL& target_url, - bool is_gateway_url, - std::optional x_ipfs_path_header, - const bool auto_redirect_blocked, - const std::string& host, - const std::optional& dnslink) { - // Check if user hasn't redirected to another host while dnslink was resolving - if (current.host() != web_contents()->GetVisibleURL().host() || - !current.SchemeIsHTTPOrHTTPS()) - return; - if (!dnslink || dnslink.value().empty()) { - if (x_ipfs_path_header) { - IPFSResourceLinkResolved(ResolveXIPFSPathUrl(x_ipfs_path_header.value())); - } - return; - } - - DNSLinkResolved(ResolveDNSLinkUrl(target_url), is_gateway_url, - auto_redirect_blocked); -} - -void IPFSTabHelper::LoadUrl(const GURL& gurl) { - if (redirect_callback_for_testing_) { - redirect_callback_for_testing_.Run(gurl); - return; - } - - content::OpenURLParams params(gurl, content::Referrer(), - WindowOpenDisposition::CURRENT_TAB, - ui::PAGE_TRANSITION_LINK, false); - params.should_replace_current_entry = true; - web_contents()->OpenURL(params, /*navigation_handle_callback=*/{}); -} - -#if !BUILDFLAG(IS_ANDROID) -void IPFSTabHelper::LoadUrlForAutoRedirect(const GURL& gurl) { - if (redirect_callback_for_testing_) { - redirect_callback_for_testing_.Run(gurl); - return; - } - - content::NavigationController::LoadURLParams params(content::OpenURLParams( - gurl, content::Referrer(), WindowOpenDisposition::CURRENT_TAB, - ui::PAGE_TRANSITION_LINK, false)); - params.should_replace_current_entry = true; - if (auto new_handle = - web_contents()->GetController().LoadURLWithParams(params)) { - new_handle->SetUserData( - kIpfsFallbackOriginalUrlKey, - std::make_unique(GetCurrentPageURL())); - } -} - -void IPFSTabHelper::LoadUrlForFallback(const GURL& gurl) { - content::NavigationController::LoadURLParams params(content::OpenURLParams( - gurl, content::Referrer(), WindowOpenDisposition::CURRENT_TAB, - ui::PAGE_TRANSITION_TYPED, false)); - params.should_replace_current_entry = true; - if (auto new_handle = - web_contents()->GetController().LoadURLWithParams(params); - new_handle) { - new_handle->SetUserData( - kIpfsFallbackBlockRedirectForNavEntryIdKey, - std::make_unique(true)); - } -} -#endif // !BUILDFLAG(IS_ANDROID) - -void IPFSTabHelper::UpdateLocationBar() { -#if !BUILDFLAG(IS_ANDROID) - auto* content_infobar_manager = - infobars::ContentInfoBarManager::FromWebContents(web_contents()); - // Check whether content_infobar_manager is present for unit tests - if (content_infobar_manager && ipfs_resolved_url_.is_valid() && - !pref_service_->GetBoolean(kIPFSAutoRedirectToConfiguredGateway)) { - BraveIPFSInfoBarDelegate::Create( - content_infobar_manager, - std::make_unique( - weak_ptr_factory_.GetWeakPtr()), - pref_service_); - } -#endif - - if (web_contents()->GetDelegate()) - web_contents()->GetDelegate()->NavigationStateChanged( - web_contents(), content::INVALIDATE_TYPE_URL); -} - -GURL IPFSTabHelper::GetCurrentPageURL() const { - if (current_page_url_for_testing_.is_valid()) - return current_page_url_for_testing_; - // We use GetLastCommittedURL as the current url for IPFS related checks - // because this checks are initiated after navigation commit. - return web_contents()->GetLastCommittedURL(); -} - -GURL IPFSTabHelper::GetIPFSResolvedURL() const { - if (!ipfs_resolved_url_.is_valid()) - return GURL(); - GURL current = GetCurrentPageURL(); - GURL::Replacements replacements; - replacements.SetQueryStr(current.query_piece()); - replacements.SetRefStr(current.ref_piece()); - return ipfs_resolved_url_.ReplaceComponents(replacements); -} - -void IPFSTabHelper::CheckDNSLinkRecord( - const GURL& target, - bool is_gateway_url, - std::optional x_ipfs_path_header, - const bool& auto_redirect_blocked) { - if (!target.SchemeIsHTTPOrHTTPS()) - return; - - auto host_port_pair = net::HostPortPair::FromURL(target); - - auto resolved_callback = base::BindOnce( - &IPFSTabHelper::HostResolvedCallback, weak_ptr_factory_.GetWeakPtr(), - GetCurrentPageURL(), target, is_gateway_url, - std::move(x_ipfs_path_header), auto_redirect_blocked); - - const auto& network_anonymization_key = - web_contents()->GetPrimaryMainFrame() - ? web_contents() - ->GetPrimaryMainFrame() - ->GetIsolationInfoForSubresources() - .network_anonymization_key() - : net::NetworkAnonymizationKey(); - resolver_->Resolve(host_port_pair, network_anonymization_key, - net::DnsQueryType::TXT, std::move(resolved_callback)); -} - -bool IPFSTabHelper::IsDNSLinkCheckEnabled() const { - auto resolve_method = static_cast( - pref_service_->GetInteger(kIPFSResolveMethod)); - - return (resolve_method != ipfs::IPFSResolveMethodTypes::IPFS_DISABLED); -} - -bool IPFSTabHelper::IsAutoRedirectIPFSResourcesEnabled() const { - auto resolve_method = static_cast( - pref_service_->GetInteger(kIPFSResolveMethod)); - auto autoredirect_ipfs_resources_enabled = - pref_service_->GetBoolean(kIPFSAutoRedirectToConfiguredGateway); - - return (resolve_method != ipfs::IPFSResolveMethodTypes::IPFS_DISABLED) && - autoredirect_ipfs_resources_enabled; -} - -void IPFSTabHelper::UpdateDnsLinkButtonState() { - if (!IsDNSLinkCheckEnabled()) { - if (ipfs_resolved_url_.is_valid()) { - ipfs_resolved_url_ = GURL(); - UpdateLocationBar(); - } - return; - } - GURL current = GetCurrentPageURL(); - if (!ipfs_resolved_url_.is_valid() || (resolver_->host() != current.host()) || - !CanResolveURL(current)) { - ipfs_resolved_url_ = GURL(); - UpdateLocationBar(); - } -} - -bool IPFSTabHelper::CanResolveURL(const GURL& url) const { - url::Origin url_origin = url::Origin::Create(url); - bool resolve = url.SchemeIsHTTPOrHTTPS() && - !IsAPIGateway(url_origin.GetURL(), chrome::GetChannel()); - if (!IsLocalGatewayConfigured(pref_service_)) { - resolve = resolve && !IsDefaultGatewayURL(url, pref_service_); - } else { - resolve = resolve && !IsLocalGatewayURL(url); - } - return resolve; -} - -// For x-ipfs-path header we are making urls like -// ipfs:// -GURL IPFSTabHelper::ResolveXIPFSPathUrl( - const std::string& x_ipfs_path_header_value) { - return TranslateXIPFSPath(x_ipfs_path_header_value).value_or(GURL()); -} - -std::optional IPFSTabHelper::ResolveIPFSUrlFromGatewayLikeUrl( - const GURL& gurl) { - bool api_gateway = IsAPIGateway(gurl, chrome::GetChannel()); - auto base_gateway = - GetConfiguredBaseGateway(pref_service_, chrome::GetChannel()); - if (!api_gateway && - // Make sure we don't infinite redirect - !gurl.DomainIs(base_gateway.host()) && !net::IsLocalhost(gurl)) { - return ipfs::ExtractSourceFromGateway(gurl); - } - - return std::nullopt; -} - -// For _dnslink we just translate url to ipns:// scheme -GURL IPFSTabHelper::ResolveDNSLinkUrl(const GURL& url) { - GURL::Replacements replacements; - replacements.SetSchemeStr(kIPNSScheme); - return url.ReplaceComponents(replacements); -} - -void IPFSTabHelper::MaybeCheckDNSLinkRecord( - const net::HttpResponseHeaders* headers, - const bool& auto_redirect_blocked) { - UpdateDnsLinkButtonState(); - auto current_url = GetCurrentPageURL(); - auto dnslink_target = current_url; - auto possible_redirect = ResolveIPFSUrlFromGatewayLikeUrl(current_url); - if (possible_redirect && IsIPFSScheme(possible_redirect.value())) { - if (IsAutoRedirectIPFSResourcesEnabled() && !auto_redirect_blocked) { -#if !BUILDFLAG(IS_ANDROID) - LoadUrlForAutoRedirect(possible_redirect.value()); - if (IsResolveMethod(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)) { - global_infobar_service_->ShowAlwaysStartInfobar(); - } -#else - LoadUrl(possible_redirect.value()); -#endif // !BUILDFLAG(IS_ANDROID) - } else { - IPFSResourceLinkResolved(possible_redirect.value()); - } - return; - } else if (possible_redirect) { - dnslink_target = possible_redirect.value(); - } - - if (!IsDNSLinkCheckEnabled() || !headers || ipfs_resolved_url_.is_valid() || - !CanResolveURL(dnslink_target)) { - UpdateLocationBar(); - return; - } - int response_code = headers->response_code(); - std::string normalized_header; - if ((response_code >= net::HttpStatusCode::HTTP_INTERNAL_SERVER_ERROR && - response_code <= net::HttpStatusCode::HTTP_VERSION_NOT_SUPPORTED)) { - CheckDNSLinkRecord(dnslink_target, possible_redirect.has_value(), - std::nullopt, auto_redirect_blocked); - } else if (headers->GetNormalizedHeader(kIfpsPathHeader, - &normalized_header)) { - CheckDNSLinkRecord(dnslink_target, possible_redirect.has_value(), - normalized_header, auto_redirect_blocked); - } else if (possible_redirect) { - CheckDNSLinkRecord(dnslink_target, possible_redirect.has_value(), - std::nullopt, auto_redirect_blocked); - } -} - -void IPFSTabHelper::MaybeSetupIpfsProtocolHandlers(const GURL& url) { - auto resolve_method = static_cast( - pref_service_->GetInteger(kIPFSResolveMethod)); - if (resolve_method == ipfs::IPFSResolveMethodTypes::IPFS_ASK && - IsDefaultGatewayURL(url, pref_service_)) { - auto infobar_count = pref_service_->GetInteger(kIPFSInfobarCount); - if (!infobar_count) { - pref_service_->SetInteger(kIPFSInfobarCount, infobar_count + 1); - SetupIPFSProtocolHandler(ipfs::kIPFSScheme); - SetupIPFSProtocolHandler(ipfs::kIPNSScheme); - } - } -} - -void IPFSTabHelper::DidFinishNavigation(content::NavigationHandle* handle) { - DCHECK(handle); - if (!handle->IsInMainFrame() || !handle->HasCommitted() || - handle->IsSameDocument()) { - return; - } - -#if !BUILDFLAG(IS_ANDROID) - auto is_ipfs_companion_enabled( - pref_service_->GetBoolean(kIPFSCompanionEnabled)); - if (!is_ipfs_companion_enabled && - (handle->IsErrorPage() || IsClientOrServerHttpError(handle))) { - auto* orig_url_nav_data = static_cast( - handle->GetUserData(kIpfsFallbackOriginalUrlKey)); - if (orig_url_nav_data && !orig_url_nav_data->original_url.is_empty()) { - ShowBraveIPFSFallbackInfoBar(orig_url_nav_data->original_url); - return; - } - } -#endif // !BUILDFLAG(IS_ANDROID) - - if (handle->GetResponseHeaders() && - handle->GetResponseHeaders()->HasHeader(kIfpsPathHeader)) { - MaybeSetupIpfsProtocolHandlers(handle->GetURL()); - } - -#if !BUILDFLAG(IS_ANDROID) - auto* block_redirect_nav_data = static_cast( - handle->GetUserData(kIpfsFallbackBlockRedirectForNavEntryIdKey)); - const bool auto_redirect_blocked = - block_redirect_nav_data && block_redirect_nav_data->enable_redirect_block; - - MaybeCheckDNSLinkRecord(handle->GetResponseHeaders(), auto_redirect_blocked); -#else - MaybeCheckDNSLinkRecord(handle->GetResponseHeaders(), false); -#endif // !BUILDFLAG(IS_ANDROID) -} - -#if !BUILDFLAG(IS_ANDROID) -void IPFSTabHelper::ShowBraveIPFSFallbackInfoBar( - const GURL& initial_navigation_url) { - if (show_fallback_infobar_callback_for_testing_) { - show_fallback_infobar_callback_for_testing_.Run(initial_navigation_url); - return; - } - auto* content_infobar_manager = - infobars::ContentInfoBarManager::FromWebContents(web_contents()); - if (content_infobar_manager) { - BraveIPFSFallbackInfoBarDelegate::Create( - content_infobar_manager, - std::make_unique( - weak_ptr_factory_.GetWeakPtr(), initial_navigation_url), - pref_service_); - } -} -#endif // !BUILDFLAG(IS_ANDROID) - -WEB_CONTENTS_USER_DATA_KEY_IMPL(IPFSTabHelper); - -} // namespace ipfs diff --git a/browser/ipfs/ipfs_tab_helper.h b/browser/ipfs/ipfs_tab_helper.h deleted file mode 100644 index 2f27cfff1c9f..000000000000 --- a/browser/ipfs/ipfs_tab_helper.h +++ /dev/null @@ -1,189 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_IPFS_IPFS_TAB_HELPER_H_ -#define BRAVE_BROWSER_IPFS_IPFS_TAB_HELPER_H_ - -#include -#include -#include -#include -#include - -#include "base/gtest_prod_util.h" -#include "base/memory/raw_ptr.h" -#include "brave/browser/ipfs/import/ipfs_import_controller.h" -#include "brave/browser/ipfs/ipfs_host_resolver.h" -#include "components/prefs/pref_change_registrar.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/browser/web_contents_user_data.h" - -namespace content { -class NavigationHandle; -class WebContents; -} // namespace content - -class BraveGlobalInfobarService; -class PrefService; - -namespace ipfs { -class IPFSHostResolver; -class IpfsImportController; - -// Determines if IPFS should be active for a given top-level navigation. -class IPFSTabHelper : public content::WebContentsObserver, - public IpfsImportController, - public content::WebContentsUserData { - public: - IPFSTabHelper(const IPFSTabHelper&) = delete; - IPFSTabHelper& operator=(IPFSTabHelper&) = delete; - ~IPFSTabHelper() override; - - static bool MaybeCreateForWebContents(content::WebContents* web_contents); - GURL GetIPFSResolvedURL() const; - - void SetResolverForTesting(std::unique_ptr resolver) { - resolver_ = std::move(resolver); - } - - IpfsImportController* GetImportController() { - return static_cast(this); - } - - void SetPageURLForTesting(const GURL& url) { - current_page_url_for_testing_ = url; - } - - void SetRediretCallbackForTesting( - base::RepeatingCallback callback) { - redirect_callback_for_testing_ = callback; - } - -#if !BUILDFLAG(IS_ANDROID) - virtual bool IsResolveMethod( - const ipfs::IPFSResolveMethodTypes& resolution_method); -#endif // !BUILDFLAG(IS_ANDROID) - private: - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, CanResolveURLTest); - FRIEND_TEST_ALL_PREFIXES( - IpfsTabHelperUnitTest, - TranslateUrlToIpns_When_HasDNSLinkRecord_AndXIPFSPathHeader); - FRIEND_TEST_ALL_PREFIXES( - IpfsTabHelperUnitTest, - TranslateUrlToIpns_When_HasDNSLinkRecord_AndOriginalPageFails_500); - FRIEND_TEST_ALL_PREFIXES( - IpfsTabHelperUnitTest, - DoNotTranslateUrlToIpns_When_HasDNSLinkRecord_AndOriginalPageFails_400); - FRIEND_TEST_ALL_PREFIXES( - IpfsTabHelperUnitTest, - TranslateUrlToIpns_When_HasDNSLinkRecord_AndOriginalPageFails_505); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - DoNotTranslateUrlToIpns_When_NoDNSLinkRecord); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - DoNotTranslateUrlToIpns_When_NoHeader_And_NoError); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - DNSLinkRecordResolved_AutoRedirectDNSLink); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - XIpfsPathHeaderUsed_IfNoDnsLinkRecord_IPFS); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - XIpfsPathHeaderUsed_IfNoDnsLinkRecord_IPNS); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, ResolveXIPFSPathUrl); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, GatewayResolving); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - GatewayLikeUrlParsed_AutoRedirectEnabled); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - GatewayLikeUrlParsed_AutoRedirectDisabled); - FRIEND_TEST_ALL_PREFIXES( - IpfsTabHelperUnitTest, - GatewayLikeUrlParsed_AutoRedirectDisabled_WithXIPFSPathHeader); - FRIEND_TEST_ALL_PREFIXES( - IpfsTabHelperUnitTest, - GatewayLikeUrlParsed_AutoRedirectDisabled_WithDnsLink); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, GatewayIPNS_Redirect); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - GatewayIPNS_NoRedirect_WhenNoDnsLinkRecord); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, GatewayIPNS_ResolveUrl); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - GatewayIPNS_Redirect_LibP2PKey); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - GatewayIPNS_Redirect_LibP2PKey_NoAutoRedirect); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, - GatewayIPNS_No_Redirect_WhenNoDnsLink); - FRIEND_TEST_ALL_PREFIXES(IpfsTabHelperUnitTest, IPFSAlwaysStartInfobar); - friend class content::WebContentsUserData; - friend class BraveIPFSInfoBarDelegateObserverImpl; -#if !BUILDFLAG(IS_ANDROID) - friend class IPFSTabHelperTest; - friend class BraveIPFSFallbackInfoBarDelegateObserverImpl; - - void SetSetShowFallbackInfobarCallbackForTesting( - base::RepeatingCallback callback) { - show_fallback_infobar_callback_for_testing_ = callback; - } -#endif // !BUILDFLAG(IS_ANDROID) - explicit IPFSTabHelper(content::WebContents* web_contents); - - GURL GetCurrentPageURL() const; - bool CanResolveURL(const GURL& url) const; - bool IsDNSLinkCheckEnabled() const; - bool IsAutoRedirectIPFSResourcesEnabled() const; - void IPFSResourceLinkResolved(const GURL& ipfs); - void DNSLinkResolved(const GURL& ipfs, - bool is_gateway_url, - const bool& auto_redirect_blocked); - void MaybeCheckDNSLinkRecord(const net::HttpResponseHeaders* headers, - const bool& auto_redirect_blocked); - void UpdateDnsLinkButtonState(); - std::optional ResolveIPFSUrlFromGatewayLikeUrl(const GURL& gurl); - - GURL ResolveDNSLinkUrl(const GURL& url); - GURL ResolveXIPFSPathUrl(const std::string& x_ipfs_path_header_value); - - void MaybeSetupIpfsProtocolHandlers(const GURL& url); - - // content::WebContentsObserver - void DidFinishNavigation( - content::NavigationHandle* navigation_handle) override; - void UpdateLocationBar(); - - void CheckDNSLinkRecord(const GURL& gurl, - bool is_gateway_url, - std::optional x_ipfs_path_header, - const bool& auto_redirect_blocked); - void HostResolvedCallback(const GURL& current, - const GURL& url, - bool is_gateway_url, - std::optional x_ipfs_path_header, - const bool auto_redirect_blocked, - const std::string& host, - const std::optional& dnslink); - - void LoadUrl(const GURL& gurl); - -#if !BUILDFLAG(IS_ANDROID) - void LoadUrlForAutoRedirect(const GURL& gurl); - void LoadUrlForFallback(const GURL& gurl); - void ShowBraveIPFSFallbackInfoBar(const GURL& initial_navigation_url); - base::RepeatingCallback - show_fallback_infobar_callback_for_testing_; -#endif // !BUILDFLAG(IS_ANDROID) - - const raw_ptr pref_service_ = nullptr; - PrefChangeRegistrar pref_change_registrar_; -#if !BUILDFLAG(IS_ANDROID) - raw_ptr global_infobar_service_; -#endif // !BUILDFLAG(IS_ANDROID) - GURL ipfs_resolved_url_; - GURL current_page_url_for_testing_; - base::RepeatingCallback redirect_callback_for_testing_; - std::unique_ptr resolver_; - base::WeakPtrFactory weak_ptr_factory_{this}; - - WEB_CONTENTS_USER_DATA_KEY_DECL(); -}; - -} // namespace ipfs - -#endif // BRAVE_BROWSER_IPFS_IPFS_TAB_HELPER_H_ diff --git a/browser/ipfs/ipfs_tab_helper_browsertest.cc b/browser/ipfs/ipfs_tab_helper_browsertest.cc deleted file mode 100644 index 9b49149cf5b8..000000000000 --- a/browser/ipfs/ipfs_tab_helper_browsertest.cc +++ /dev/null @@ -1,1154 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include -#include "brave/browser/ipfs/ipfs_tab_helper.h" - -#include "base/files/file_util.h" -#include "base/path_service.h" -#include "base/ranges/algorithm.h" -#include "brave/browser/ipfs/ipfs_host_resolver.h" -#include "brave/browser/ui/views/infobars/brave_confirm_infobar.h" -#include "brave/components/constants/brave_paths.h" -#include "brave/components/constants/pref_names.h" -#include "brave/components/infobars/core/brave_confirm_infobar_delegate.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/pref_names.h" -#include "build/build_config.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/channel_info.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "components/infobars/core/infobar.h" -#include "components/prefs/pref_service.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/navigation_entry.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/notification_types.h" -#include "content/public/browser/storage_partition.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "net/dns/mock_host_resolver.h" -#include "net/test/embedded_test_server/controllable_http_response.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" - -using content::NavigationHandle; -using content::WebContents; - -namespace { -constexpr char kCid1[] = - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi"; -constexpr char kClientSideRedirectResponsePath[] = "/client_side_redirect.html"; -constexpr char kClientSideRedirectHostName[] = "en.wikipedia-on-ipfs.org"; -} // namespace - -namespace ipfs { -class IPFSTabHelperTest : public IPFSTabHelper { - public: - explicit IPFSTabHelperTest(content::WebContents* web_contents) - : IPFSTabHelper(web_contents) {} - - bool IsResolveMethod( - const ipfs::IPFSResolveMethodTypes& resolution_method) override { - return resolution_method == ipfs::IPFSResolveMethodTypes::IPFS_LOCAL; - } -}; -} // namespace ipfs - -class IpfsTabHelperBrowserTest : public InProcessBrowserTest { - public: - IpfsTabHelperBrowserTest() - : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} - - void SetUpOnMainThread() override { - InProcessBrowserTest::SetUpOnMainThread(); - - test_data_dir_ = base::PathService::CheckedGet(brave::DIR_TEST_DATA); - embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); - https_server_.ServeFilesFromSourceDirectory("content/test/data"); - embedded_test_server()->RegisterRequestHandler(base::BindRepeating( - &IpfsTabHelperBrowserTest::ResponseHandler, base::Unretained(this))); - - https_server_.RegisterRequestHandler(base::BindRepeating( - &IpfsTabHelperBrowserTest::ResponseHandler, base::Unretained(this))); - ASSERT_TRUE(https_server_.Start()); - ASSERT_TRUE(embedded_test_server()->Start()); - host_resolver()->AddRule("*", "127.0.0.1"); - } - - content::WebContents* active_contents() { - return browser()->tab_strip_model()->GetActiveWebContents(); - } - - GURL ReplaceScheme(const GURL& current, const std::string& new_scheme) { - GURL::Replacements replacements; - replacements.SetSchemeStr(new_scheme); - return current.ReplaceComponents(replacements); - } - - std::unique_ptr ResponseHandler( - const net::test_server::HttpRequest& request) { - std::unique_ptr http_response( - new net::test_server::BasicHttpResponse); - - http_response->set_code(code_); - if (base::StartsWith(request.relative_url, - kClientSideRedirectResponsePath)) { - http_response->set_content(GetFileContent("client_side_redirect.html")); - } - if (code_ == net::HTTP_OK && !x_ipfs_path_.empty()) { - http_response->AddCustomHeader("x-ipfs-path", x_ipfs_path_); - } - return std::move(http_response); - } - - void SetXIpfsPathHeader(const std::string& value) { x_ipfs_path_ = value; } - - void SetHttpStatusCode(net::HttpStatusCode code) { code_ = code; } - - ipfs::IPFSTabHelper* SetIPFSTabHelperTest() { - active_contents()->SetUserData( - content::WebContentsUserData::UserDataKey(), - std::make_unique(active_contents())); - auto* helper = ipfs::IPFSTabHelper::FromWebContents(active_contents()); - EXPECT_TRUE( - helper->IsResolveMethod(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)); - return helper; - } - - const base::FilePath& test_data_dir() const { return test_data_dir_; } - std::string GetFileContent(const std::string& filename) const { - std::string result; - - const auto full_path = test_data_dir_.AppendASCII(filename); - [&]() { ASSERT_TRUE(base::ReadFileToString(full_path, &result)); }(); - return result; - } - - net::HttpStatusCode code_ = net::HTTP_OK; - std::string x_ipfs_path_; - net::EmbeddedTestServer https_server_; - - private: - base::FilePath test_data_dir_; -}; - -class FakeIPFSHostResolver : public ipfs::IPFSHostResolver { - public: - FakeIPFSHostResolver() : ipfs::IPFSHostResolver(nullptr) {} - ~FakeIPFSHostResolver() override = default; - void Resolve(const net::HostPortPair& host, - const net::NetworkAnonymizationKey& anonymization_key, - net::DnsQueryType dns_query_type, - HostTextResultsCallback callback) override { - resolve_called_ = true; - if (callback) - std::move(callback).Run(host.host(), dnslink_); - } - - void ResetResolveCalled() { resolve_called_ = false; } - bool resolve_called() const { return resolve_called_; } - - void SetDNSLinkToRespond(const std::string& dnslink) { dnslink_ = dnslink; } - - private: - bool resolve_called_ = false; - std::string dnslink_; -}; - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, ResolvedIPFSLinkLocal) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger(kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)); - GURL gateway = ipfs::GetConfiguredBaseGateway(prefs, chrome::GetChannel()); - - // X-IPFS-Path header and no DNSLink - SetXIpfsPathHeader("/ipfs/bafybeiemx/empty.html"); - GURL test_url = https_server_.GetURL("/empty.html?query#ref"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - auto resolved_url = helper->GetIPFSResolvedURL(); - EXPECT_EQ(resolved_url, GURL("ipfs://bafybeiemx/empty.html?query#ref")); - - resolver_raw->ResetResolveCalled(); - test_url = https_server_.GetURL("/another.html?query#ref"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - resolved_url = helper->GetIPFSResolvedURL(); - EXPECT_EQ(resolved_url, GURL("ipfs://bafybeiemx/empty.html?query#ref")); - - resolver_raw->ResetResolveCalled(); - SetXIpfsPathHeader("/ipns/brave.eth/empty.html"); - test_url = https_server_.GetURL("/?query#ref"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - resolved_url = helper->GetIPFSResolvedURL(); - EXPECT_EQ(resolved_url, GURL("ipns://brave.eth/empty.html?query#ref")); - - resolver_raw->ResetResolveCalled(); - SetXIpfsPathHeader("/ipfs/bafy"); - test_url = - embedded_test_server()->GetURL("a.com", "/wiki/empty.html?query#ref"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - resolved_url = helper->GetIPFSResolvedURL(); - EXPECT_EQ(resolved_url, GURL("ipfs://bafy?query#ref")); - - resolver_raw->ResetResolveCalled(); - SetXIpfsPathHeader("/ipns/bafyb"); - test_url = embedded_test_server()->GetURL( - "a.com", "/ipns/bafyb/wiki/empty.html?query#ref"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - resolved_url = helper->GetIPFSResolvedURL(); - EXPECT_EQ(resolved_url, GURL("ipns://bafyb?query#ref")); - - resolver_raw->ResetResolveCalled(); - SetXIpfsPathHeader("/ipfs/bafy"); - test_url = embedded_test_server()->GetURL( - "a.com", base::StringPrintf("/ipfs/%s/wiki/" - "empty.html?query#ref", - kCid1)); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - resolved_url = helper->GetIPFSResolvedURL(); - EXPECT_EQ(resolved_url, GURL(base::StringPrintf( - "ipfs://%s/wiki/empty.html?query#ref", kCid1))); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, ResolvedIPFSLinkGateway) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - SetXIpfsPathHeader("/ipfs/bafybeiemx/empty.html"); - const GURL test_url = https_server_.GetURL("/empty.html"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), - "ipfs://bafybeiemx/empty.html"); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, NoResolveIPFSLinkCalledMode) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_DISABLED)); - SetXIpfsPathHeader("/ipfs/bafybeiemx/empty.html"); - GURL test_url = https_server_.GetURL("/empty.html"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); - - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_DISABLED)); - - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, - NoResolveIPFSLinkCalledHeader) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger(kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)); - - GURL test_url = embedded_test_server()->GetURL("/empty.html"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, - GatewayRedirectToIPFS_DontRedirectConfiguredGateway) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, true); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - GURL gateway_url = embedded_test_server()->GetURL("a.com", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); - - const GURL test_url = embedded_test_server()->GetURL( - "a.com", base::StringPrintf("/ipfs/%s/wiki/" - "empty.html?query#ref", - kCid1)); - - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - - EXPECT_EQ(active_contents()->GetURL(), test_url); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, GatewayRedirectToIPFS) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - resolver_raw->SetDNSLinkToRespond("/ipfs/QmXoypiz"); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, true); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); - ASSERT_FALSE(resolver_raw->resolve_called()); - SetXIpfsPathHeader("/ipns/other"); - - const GURL test_url = embedded_test_server()->GetURL( - "navigate_to.com", base::StringPrintf("/ipfs/%s/wiki/" - "empty.html?query#ref", - kCid1)); - - GURL gateway_url = embedded_test_server()->GetURL("a.com", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - - // gateway url. - GURL expected_final_url; - ipfs::TranslateIPFSURI(GURL(base::StringPrintf("ipfs://%s/" - "wiki/empty.html?query#ref", - kCid1)), - &expected_final_url, gateway_url, false); - - EXPECT_EQ(active_contents()->GetVisibleURL(), expected_final_url); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, - GatewayRedirectToIPND_LibP2PKey) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - resolver_raw->SetDNSLinkToRespond("/ipfs/QmXoypiz"); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, true); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); - ASSERT_FALSE(resolver_raw->resolve_called()); - SetXIpfsPathHeader("/ipns/other"); - - const GURL test_url = embedded_test_server()->GetURL( - "navigate_to.com", - "/ipns/k51qzi5uqu5dlvj2baxnqndepeb86cbk3ng7n3i46uzyxzyqj2xjonzllnv0v8/" - "wiki/empty.html?query#ref"); - - GURL gateway_url = embedded_test_server()->GetURL("a.com", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - - // gateway url. - GURL expected_final_url; - ipfs::TranslateIPFSURI(GURL("ipns://" - "k51qzi5uqu5dlvj2baxnqndepeb86cbk3ng7n3i46uzyxzyq" - "j2xjonzllnv0v8/wiki/empty.html?query#ref"), - &expected_final_url, gateway_url, false); - - EXPECT_EQ(active_contents()->GetVisibleURL(), expected_final_url); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, GatewayRedirectToIPNS) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - resolver_raw->SetDNSLinkToRespond("/ipns/QmXoypiz"); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, true); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); - ASSERT_FALSE(resolver_raw->resolve_called()); - SetXIpfsPathHeader("/ipns/other"); - - const GURL test_url = embedded_test_server()->GetURL( - "navigate_to.com", - "/ipns/en-wikiepdia--on--ipfs-org/wiki/empty.html?query#ref"); - - GURL gateway_url = embedded_test_server()->GetURL("a.com", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - - // gateway url. - GURL expected_final_url; - ipfs::TranslateIPFSURI( - GURL("ipns://en.wikiepdia-on-ipfs.org/wiki/empty.html?query#ref"), - &expected_final_url, gateway_url, false); - - EXPECT_EQ(active_contents()->GetVisibleURL(), expected_final_url); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, ResolveIPFSLinkCalled5xx) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - resolver_raw->SetDNSLinkToRespond("/ipfs/QmXoypiz"); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); - ASSERT_FALSE(resolver_raw->resolve_called()); - SetHttpStatusCode(net::HTTP_INTERNAL_SERVER_ERROR); - const GURL test_url = https_server_.GetURL("/5xx.html?query#fragment"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_FALSE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - GURL ipns = ReplaceScheme(test_url, ipfs::kIPNSScheme); - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), ipns); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, ResolveNotCalled5xx) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - SetHttpStatusCode(net::HTTP_INTERNAL_SERVER_ERROR); - helper->SetResolverForTesting(std::move(resolver)); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_DISABLED)); - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); - ASSERT_FALSE(resolver_raw->resolve_called()); - const GURL test_url = https_server_.GetURL("/5xx.html"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_FALSE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), std::string()); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, ResolvedIPFSLinkBad) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - helper->SetResolverForTesting(std::move(resolver)); - - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger(kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)); - - SetXIpfsPathHeader(""); - resolver_raw->SetDNSLinkToRespond(""); - - const GURL test_url = https_server_.GetURL("/empty.html"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_FALSE(resolver_raw->resolve_called()); - std::string result = ""; - EXPECT_EQ(helper->GetIPFSResolvedURL().spec(), result); -} - -// Some tests are failing for Windows x86 CI, -// See https://github.com/brave/brave-browser/issues/22767 -#if BUILDFLAG(IS_WIN) && defined(ARCH_CPU_X86) -#define MAYBE_ResolvedIPFSLinkBackward DISABLED_ResolvedIPFSLinkBackward -#else -#define MAYBE_ResolvedIPFSLinkBackward ResolvedIPFSLinkBackward -#endif -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, - MAYBE_ResolvedIPFSLinkBackward) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* network_context = active_contents() - ->GetBrowserContext() - ->GetDefaultStoragePartition() - ->GetNetworkContext(); - ASSERT_TRUE(network_context); - std::unique_ptr resolver(new FakeIPFSHostResolver()); - FakeIPFSHostResolver* resolver_raw = resolver.get(); - resolver_raw->SetNetworkContextForTesting(network_context); - helper->SetResolverForTesting(std::move(resolver)); - std::string ipfs_path = "/ipfs/bafybeiemx/"; - SetXIpfsPathHeader(ipfs_path); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, true); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - - // Navigation with x-ipfs-path header and valid _dnslink record redirects to - // ipns:// url - GURL test_url = embedded_test_server()->GetURL("navigate_to.com", - "/empty.html?query#ref"); - GURL gateway_url = embedded_test_server()->GetURL("a.com", "/"); - resolver_raw->SetDNSLinkToRespond("/ipns/a.com/"); - - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - - GURL::Replacements scheme_replacements; - scheme_replacements.SetSchemeStr(ipfs::kIPNSScheme); - - // Url will be translated to ipns:// scheme which will be translated to - // gateway url. - GURL expected_final_url; - ipfs::TranslateIPFSURI(test_url.ReplaceComponents(scheme_replacements), - &expected_final_url, gateway_url, false); - - EXPECT_EQ(active_contents()->GetVisibleURL(), expected_final_url); - - // Second one navigation also succeed - GURL another_test_url = - embedded_test_server()->GetURL("/another.html?query#ref"); - - resolver_raw->ResetResolveCalled(); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), another_test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - ASSERT_TRUE(resolver_raw->resolve_called()); - - // Url will be translated to ipns:// scheme which will be translated to - // gateway url. - GURL expected_second_final_url; - ipfs::TranslateIPFSURI( - another_test_url.ReplaceComponents(scheme_replacements), - &expected_second_final_url, gateway_url, false); - - EXPECT_EQ(active_contents()->GetVisibleURL().spec(), - expected_second_final_url); - - // Backward navigation also succeed - active_contents()->GetController().GoBack(); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetVisibleURL(), expected_final_url); -} - -#if !BUILDFLAG(IS_ANDROID) -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, - IPFSPromoInfobarShowIfRedirect) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, false); - prefs->SetInteger(kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_ASK)); - GURL gateway_url = embedded_test_server()->GetURL("a.com", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - const GURL test_url = embedded_test_server()->GetURL( - kClientSideRedirectHostName, kClientSideRedirectResponsePath); - SetXIpfsPathHeader( - base::StringPrintf("/ipns/%s/", kClientSideRedirectHostName)); - - auto find_infobar = - [](infobars::ContentInfoBarManager* content_infobar_manager) - -> infobars::InfoBar* { - const auto it = base::ranges::find( - content_infobar_manager->infobars(), - BraveConfirmInfoBarDelegate::BRAVE_IPFS_INFOBAR_DELEGATE, - &infobars::InfoBar::GetIdentifier); - return it != content_infobar_manager->infobars().cend() ? *it : nullptr; - }; - - ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), test_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_TRUE(infobar); -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, IPFSPromoInfobar) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, false); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - GURL gateway_url = embedded_test_server()->GetURL("a.com", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - const GURL test_url = embedded_test_server()->GetURL( - "navigate_to.com", base::StringPrintf("/ipfs/%s/wiki/" - "empty.html?query#ref", - kCid1)); - // gateway url. - GURL expected_final_url; - ipfs::TranslateIPFSURI(GURL(base::StringPrintf("ipfs://%s/" - "wiki/empty.html?query#ref", - kCid1)), - &expected_final_url, gateway_url, false); - - auto find_infobar = - [](infobars::ContentInfoBarManager* content_infobar_manager) - -> infobars::InfoBar* { - const auto it = base::ranges::find( - content_infobar_manager->infobars(), - BraveConfirmInfoBarDelegate::BRAVE_IPFS_INFOBAR_DELEGATE, - &infobars::InfoBar::GetIdentifier); - return it != content_infobar_manager->infobars().cend() ? *it : nullptr; - }; - - // Press cancel - { - ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), test_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_TRUE(infobar); - static_cast(infobar)->GetDelegate()->Cancel(); - ASSERT_FALSE(prefs->GetBoolean(kIPFSAutoRedirectToConfiguredGateway)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetVisibleURL(), test_url); - ASSERT_FALSE(prefs->GetBoolean(kShowIPFSPromoInfobar)); - } - - // Try to show infobar second time - it shouldn't be shown - { - ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), test_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_FALSE(infobar); - } - - // Reset infobar state - prefs->SetBoolean(kShowIPFSPromoInfobar, true); - - // Test that infobar shows several times if extra button is pressed - for (int i = 0; i < 2; i++) { - { - ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), test_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_TRUE(infobar); - static_cast(infobar) - ->GetDelegate() - ->ExtraButtonPressed(); - - ASSERT_FALSE(prefs->GetBoolean(kIPFSAutoRedirectToConfiguredGateway)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetVisibleURL(), expected_final_url); - ASSERT_TRUE(prefs->GetBoolean(kShowIPFSPromoInfobar)); - } - } - - // Test accept button, which enables the feature - { - ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), test_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_TRUE(infobar); - static_cast(infobar)->GetDelegate()->Accept(); - - ASSERT_TRUE(prefs->GetBoolean(kIPFSAutoRedirectToConfiguredGateway)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetVisibleURL(), expected_final_url); - ASSERT_FALSE(prefs->GetBoolean(kShowIPFSPromoInfobar)); - } - - // Infobar shouldn't be shown after that - { - ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), test_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_FALSE(infobar); - } -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, IPFSPromoInfobar_NowShown) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, false); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - GURL gateway_url = embedded_test_server()->GetURL("a.com", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - const GURL test_url_1 = embedded_test_server()->GetURL( - "navigate_to.com", base::StringPrintf("/ipfs/%s/wiki/" - "empty.html?query#ref", - kCid1)); - const GURL test_url_2 = - embedded_test_server()->GetURL("navigate_to.com", "/abc"); - - auto find_infobar = - [](infobars::ContentInfoBarManager* content_infobar_manager) - -> infobars::InfoBar* { - const auto it = base::ranges::find( - content_infobar_manager->infobars(), - BraveConfirmInfoBarDelegate::BRAVE_IPFS_INFOBAR_DELEGATE, - &infobars::InfoBar::GetIdentifier); - return it != content_infobar_manager->infobars().cend() ? *it : nullptr; - }; - - // Infobar shouldn't be shown after that - { - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url_2)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_FALSE(infobar); - } - - { - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url_1)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_TRUE(infobar); - } - - { - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url_2)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_FALSE(infobar); - } -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, IPFSFallbackInfobar) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, true); - GURL gateway_url = embedded_test_server()->GetURL("navigate.to", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - GURL gateway = ipfs::GetConfiguredBaseGateway(prefs, chrome::GetChannel()); - - const GURL test_url = embedded_test_server()->GetURL( - "drweb.link", - "/ipns/k2k4r8ni09jro03sto91pyi070ww4x63iwub4x3sc13qn5pwkjxhfdt4"); - - const GURL test_non_ipfs_url = - embedded_test_server()->GetURL("navigate_to.com", "/"); - - GURL::Replacements replace_with_gateway_url; - replace_with_gateway_url.SetHostStr(gateway_url.host_piece()); - const GURL expected_gateway_url = - test_url.ReplaceComponents(replace_with_gateway_url); - - auto find_infobar = - [](infobars::ContentInfoBarManager* content_infobar_manager) - -> infobars::InfoBar* { - for (size_t i = 0; i < content_infobar_manager->infobars().size(); i++) { - infobars::InfoBar* infobar = content_infobar_manager->infobars()[i]; - if (infobar->delegate()->GetIdentifier() == - BraveConfirmInfoBarDelegate::BRAVE_IPFS_FALLBACK_INFOBAR_DELEGATE) { - return infobar; - } - } - return nullptr; - }; - - // Disable IPFS Companion - prefs->SetBoolean(kIPFSCompanionEnabled, false); - { - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - WaitForLoadStopWithoutSuccessCheck(active_contents()); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - // IPFS Fallback Infobar should not be shown - ASSERT_FALSE(infobar); - } - - SetHttpStatusCode(net::HTTP_INTERNAL_SERVER_ERROR); - - { - ui_test_utils::UrlLoadObserver url_observer(expected_gateway_url); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - url_observer.Wait(); - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - // IPFS Fallback Infobar should be shown - ASSERT_TRUE(infobar); - static_cast(infobar)->GetDelegate()->Accept(); - WaitForLoadStopWithoutSuccessCheck(active_contents()); - // Redirected to original address - EXPECT_EQ(active_contents()->GetVisibleURL(), test_url); - } - - { - ui_test_utils::UrlLoadObserver url_observer(expected_gateway_url); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - url_observer.Wait(); - WaitForLoadStopWithoutSuccessCheck(active_contents()); - auto ipfs_address = active_contents()->GetVisibleURL(); - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - // IPFS Fallback Infobar should be shown - ASSERT_TRUE(infobar); - static_cast(infobar)->GetDelegate()->Cancel(); - WaitForLoadStopWithoutSuccessCheck(active_contents()); - // Stayed on the same address - EXPECT_EQ(active_contents()->GetVisibleURL(), ipfs_address); - } - - { - ui_test_utils::UrlLoadObserver url_observer(test_non_ipfs_url); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_non_ipfs_url)); - url_observer.Wait(); - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - // IPFS Fallback Infobar should not be shown - ASSERT_FALSE(infobar); - EXPECT_EQ(active_contents()->GetVisibleURL(), test_non_ipfs_url); - } - - // Enable the IPFS companion - prefs->SetBoolean(kIPFSCompanionEnabled, true); - { - ui_test_utils::UrlLoadObserver url_observer(expected_gateway_url); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - url_observer.Wait(); - // Get last shown infobar - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - // IPFS Fallback infobar should not be shown - ASSERT_FALSE(infobar); - } -} - -IN_PROC_BROWSER_TEST_F(IpfsTabHelperBrowserTest, IPFSAlwaysStartInfobar) { - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(active_contents())); - ipfs::IPFSTabHelper* helper = - ipfs::IPFSTabHelper::FromWebContents(active_contents()); - ASSERT_TRUE(helper); - - auto* prefs = - user_prefs::UserPrefs::Get(active_contents()->GetBrowserContext()); - prefs->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - prefs->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, true); - GURL gateway_url = embedded_test_server()->GetURL("navigate.to", "/"); - prefs->SetString(kIPFSPublicGatewayAddress, gateway_url.spec()); - - GURL gateway = ipfs::GetConfiguredBaseGateway(prefs, chrome::GetChannel()); - - const GURL test_url = embedded_test_server()->GetURL( - "drweb.link", - "/ipns/k2k4r8ni09jro03sto91pyi070ww4x63iwub4x3sc13qn5pwkjxhfdt4"); - const GURL second_tab_test_url = embedded_test_server()->GetURL( - "drweb.link", - "/ipfs/bafybeif2py6p4u763zoj7t2hq6v2nziwv2dwlhbhiibsdsrsx5tw4lle3y"); - const GURL test_non_ipfs_url = - embedded_test_server()->GetURL("navigate_to.com", "/"); - - auto find_infobar = - [](infobars::ContentInfoBarManager* content_infobar_manager) - -> infobars::InfoBar* { - for (infobars::InfoBar* infobar : content_infobar_manager->infobars()) { - if (infobar->delegate()->GetIdentifier() == - BraveConfirmInfoBarDelegate:: - BRAVE_IPFS_ALWAYS_START_INFOBAR_DELEGATE) { - return infobar; - } - } - return nullptr; - }; - - // Do not show infobar if resolve method is not IPFS_LOCAL - prefs->SetBoolean(kIPFSAlwaysStartInfobarShown, false); - { - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_FALSE(infobar); - } - - SetIPFSTabHelperTest(); - - // Show global infobar if resolve method is IPFS_LOCAL - { - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_TRUE(infobar); - - // Openin new tab - ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), test_non_ipfs_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BrowserTestWaitFlags::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - auto* another_tab_infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_TRUE(another_tab_infobar); - } - // Open two IPFS links, show infobar only once - prefs->SetBoolean(kIPFSAlwaysStartInfobarShown, false); - { - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition( - browser(), second_tab_test_url, - WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BrowserTestWaitFlags::BROWSER_TEST_WAIT_FOR_LOAD_STOP)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_TRUE(infobar); - } - - // Do not show infobar if IPFS always start mode is already enabled - prefs->SetBoolean(kIPFSAlwaysStartMode, true); - { - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url)); - ASSERT_TRUE(WaitForLoadStop(active_contents())); - - auto* infobar = find_infobar( - infobars::ContentInfoBarManager::FromWebContents(active_contents())); - ASSERT_FALSE(infobar); - } -} - -#endif // !BUILDFLAG(IS_ANDROID) diff --git a/browser/ipfs/ipfs_tab_helper_unittest.cc b/browser/ipfs/ipfs_tab_helper_unittest.cc deleted file mode 100644 index 30eaa8f4a4e1..000000000000 --- a/browser/ipfs/ipfs_tab_helper_unittest.cc +++ /dev/null @@ -1,727 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_tab_helper.h" - -#include - -#include "base/memory/raw_ptr.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/channel_info.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile.h" -#include "chrome/test/base/testing_profile_manager.h" -#include "components/version_info/channel.h" -#include "content/public/test/browser_task_environment.h" -#include "content/public/test/test_browser_context.h" -#include "content/public/test/test_renderer_host.h" -#include "content/public/test/test_web_contents_factory.h" -#include "content/public/test/web_contents_tester.h" -#include "content/test/test_web_contents.h" -#include "net/http/http_response_headers.h" -#include "services/network/test/test_network_context.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ipfs { - -namespace { -constexpr char kCid1[] = - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi"; -constexpr char kIPNSCid1[] = - "k51qzi5uqu5dlvj2baxnqndepeb86cbk3ng7n3i46uzyxzyqj2xjonzllnv0v8"; -} // namespace - -class FakeIPFSHostResolver : public ipfs::IPFSHostResolver { - public: - FakeIPFSHostResolver() : ipfs::IPFSHostResolver(nullptr) {} - ~FakeIPFSHostResolver() override = default; - void Resolve(const net::HostPortPair& host, - const net::NetworkAnonymizationKey& anonymization_key, - net::DnsQueryType dns_query_type, - HostTextResultsCallback callback) override { - resolve_called_ = true; - if (callback) - std::move(callback).Run(host.host(), dnslink_); - } - - bool resolve_called() const { return resolve_called_; } - - void SetDNSLinkToRespond(const std::string& dnslink) { dnslink_ = dnslink; } - - private: - bool resolve_called_ = false; - std::string dnslink_; -}; - -class IpfsTabHelperUnitTest : public testing::Test { - public: - IpfsTabHelperUnitTest() - : profile_manager_(TestingBrowserProcess::GetGlobal()) {} - ~IpfsTabHelperUnitTest() override = default; - - void SetUp() override { - ASSERT_TRUE(profile_manager_.SetUp()); - test_network_context_ = std::make_unique(); - profile_ = profile_manager_.CreateTestingProfile("TestProfile"); - web_contents_ = content::TestWebContents::Create(profile(), nullptr); - auto ipfs_host_resolver = std::make_unique(); - ipfs_host_resolver_ = ipfs_host_resolver.get(); - ipfs_host_resolver_->SetNetworkContextForTesting( - test_network_context_.get()); - ASSERT_TRUE(web_contents_.get()); - ASSERT_TRUE( - ipfs::IPFSTabHelper::MaybeCreateForWebContents(web_contents_.get())); - - ipfs_tab_helper()->SetResolverForTesting(std::move(ipfs_host_resolver)); - ipfs_tab_helper()->SetRediretCallbackForTesting(base::BindRepeating( - &IpfsTabHelperUnitTest::OnRedirect, base::Unretained(this))); - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL); - } - TestingProfile* profile() { return profile_; } - void SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes type) { - profile_->GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(type)); - } - - void SetAutoRedirectToConfiguredGateway(bool value) { - profile_->GetPrefs()->SetBoolean(kIPFSAutoRedirectToConfiguredGateway, - value); - } - - ipfs::IPFSTabHelper* ipfs_tab_helper() { - return ipfs::IPFSTabHelper::FromWebContents(web_contents_.get()); - } - - ipfs::FakeIPFSHostResolver* ipfs_host_resolver() { - return ipfs_host_resolver_; - } - - content::TestWebContents* web_contents() { return web_contents_.get(); } - - GURL redirect_url() { return redirect_url_; } - - void ResetRedirectUrl() { redirect_url_ = GURL(); } - - private: - void OnRedirect(const GURL& gurl) { redirect_url_ = gurl; } - - GURL redirect_url_; - content::BrowserTaskEnvironment task_environment_; - content::RenderViewHostTestEnabler render_view_host_test_enabler_; - TestingProfileManager profile_manager_; - raw_ptr profile_ = nullptr; - std::unique_ptr web_contents_; - std::unique_ptr test_network_context_; - raw_ptr ipfs_host_resolver_; -}; - -TEST_F(IpfsTabHelperUnitTest, CanResolveURLTest) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - ASSERT_FALSE(helper->CanResolveURL(GURL("ipfs://balblabal"))); - ASSERT_FALSE(helper->CanResolveURL(GURL("file://aa"))); - ASSERT_TRUE(helper->CanResolveURL(GURL("http://a.com"))); - ASSERT_TRUE(helper->CanResolveURL(GURL("https://a.com"))); - - GURL api_server = ipfs::GetAPIServer(chrome::GetChannel()); - ASSERT_FALSE(helper->CanResolveURL(api_server)); - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL)); - - ASSERT_TRUE( - helper->CanResolveURL(GURL("https://" - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3" - "oclgtqy55fbzdi.ipfs.dweb.link/"))); - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - ASSERT_FALSE( - helper->CanResolveURL(GURL("https://" - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3" - "oclgtqy55fbzdi.ipfs.dweb.link/"))); -} - -TEST_F(IpfsTabHelperUnitTest, - TranslateUrlToIpns_When_HasDNSLinkRecord_AndXIPFSPathHeader) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL("https://brantly.eth/page?query#ref")); - helper->SetPageURLForTesting(GURL("https://brantly.eth/page?query#ref")); - - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK"); - headers->AddHeader("x-ipfs-path", "somevalue"); - - ipfs_host_resolver()->SetDNSLinkToRespond("/ipns/brantly.eth/"); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL("ipns://brantly.eth/page?query#ref"), - helper->GetIPFSResolvedURL()); -} - -TEST_F(IpfsTabHelperUnitTest, - DoNotTranslateUrlToIpns_When_HasDNSLinkRecord_AndOriginalPageFails_400) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL("https://brantly.eth/page?query#ref")); - helper->SetPageURLForTesting(GURL("https://brantly.eth/page?query#ref")); - - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 400 Nan"); - ipfs_host_resolver()->SetDNSLinkToRespond("/ipns/brantly.eth/"); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL(), helper->GetIPFSResolvedURL()); -} - -TEST_F(IpfsTabHelperUnitTest, - TranslateUrlToIpns_When_HasDNSLinkRecord_AndOriginalPageFails_500) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL("https://brantly.eth/page?query#ref")); - helper->SetPageURLForTesting(GURL("https://brantly.eth/page?query#ref")); - - auto headers = net::HttpResponseHeaders::TryToCreate( - "HTTP/1.1 500 Internal server error"); - ipfs_host_resolver()->SetDNSLinkToRespond("/ipns/brantly.eth/"); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL("ipns://brantly.eth/page?query#ref"), - helper->GetIPFSResolvedURL()); -} - -TEST_F(IpfsTabHelperUnitTest, - TranslateUrlToIpns_When_HasDNSLinkRecord_AndOriginalPageFails_505) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL("https://brantly.eth/page?query#ref")); - helper->SetPageURLForTesting(GURL("https://brantly.eth/page?query#ref")); - - auto headers = net::HttpResponseHeaders::TryToCreate( - "HTTP/1.1 505 Version not supported"); - ipfs_host_resolver()->SetDNSLinkToRespond("/ipns/brantly.eth/"); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL("ipns://brantly.eth/page?query#ref"), - helper->GetIPFSResolvedURL()); -} - -TEST_F(IpfsTabHelperUnitTest, - DoNotTranslateUrlToIpns_When_NoHeader_And_NoError) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL("https://brantly.eth/page?query#ref")); - helper->SetPageURLForTesting(GURL("https://brantly.eth/page?query#ref")); - - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK"); - - ipfs_host_resolver()->SetDNSLinkToRespond(""); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL(), helper->GetIPFSResolvedURL()); -} - -TEST_F(IpfsTabHelperUnitTest, DNSLinkRecordResolved_AutoRedirectDNSLink) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - GURL gateway = ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - chrome::GetChannel()); - web_contents()->NavigateAndCommit(GURL("https://brantly.eth/page?query#ref")); - - helper->SetPageURLForTesting(GURL("https://brantly.eth/page?query#ref")); - helper->HostResolvedCallback(GURL("https://brantly.eth/page?query#ref"), - GURL("https://brantly.eth/page?query#ref"), - false, std::nullopt, false, "brantly.eth", - "/ipns/brantly.eth/"); - ASSERT_EQ(GURL("ipns://brantly.eth/page?query#ref"), - helper->GetIPFSResolvedURL()); -} - -TEST_F(IpfsTabHelperUnitTest, XIpfsPathHeaderUsed_IfNoDnsLinkRecord_IPFS) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL("https://brantly.eth/page?query#ref")); - helper->SetPageURLForTesting(GURL("https://brantly.eth/page?query#ref")); - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - GURL gateway = ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - chrome::GetChannel()); - - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK"); - headers->AddHeader("x-ipfs-path", base::StringPrintf("/ipfs/%s", kCid1)); - - ipfs_host_resolver()->SetDNSLinkToRespond(""); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - GURL resolved_url = helper->GetIPFSResolvedURL(); - - EXPECT_EQ(resolved_url.spec(), - base::StringPrintf("ipfs://%s?query#ref", kCid1)); -} - -TEST_F(IpfsTabHelperUnitTest, XIpfsPathHeaderUsed_IfNoDnsLinkRecord_IPNS) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL("https://brantly.eth/page?query#ref")); - helper->SetPageURLForTesting(GURL("https://brantly.eth/page?query#ref")); - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - GURL gateway = ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - chrome::GetChannel()); - - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK"); - headers->AddHeader("x-ipfs-path", "/ipns/brantly.eth/"); - - ipfs_host_resolver()->SetDNSLinkToRespond(""); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - GURL resolved_url = helper->GetIPFSResolvedURL(); - - EXPECT_EQ(resolved_url, GURL("ipns://brantly.eth/?query#ref")); -} - -TEST_F(IpfsTabHelperUnitTest, ResolveXIPFSPathUrl) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - { - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - GURL gateway = ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - chrome::GetChannel()); - GURL url = - helper->ResolveXIPFSPathUrl(base::StringPrintf("/ipfs/%s", kCid1)); - EXPECT_EQ(url, GURL(base::StringPrintf("ipfs://%s", kCid1))); - } - - { - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL); - GURL gateway = ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - chrome::GetChannel()); - GURL url = - helper->ResolveXIPFSPathUrl(base::StringPrintf("/ipfs/%s", kCid1)); - EXPECT_EQ(url, GURL(base::StringPrintf("ipfs://%s", kCid1))); - } - - { - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_ASK); - GURL gateway = ipfs::GetConfiguredBaseGateway(profile()->GetPrefs(), - chrome::GetChannel()); - GURL url = - helper->ResolveXIPFSPathUrl(base::StringPrintf("/ipfs/%s", kCid1)); - EXPECT_EQ(url, GURL(base::StringPrintf("ipfs://%s", kCid1))); - } -} - -TEST_F(IpfsTabHelperUnitTest, GatewayResolving) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - GURL api_server = GetAPIServer(chrome::GetChannel()); - helper->SetPageURLForTesting(api_server); - helper->DNSLinkResolved(GURL(), false, false); - ASSERT_FALSE(helper->GetIPFSResolvedURL().is_valid()); - - scoped_refptr response_headers( - base::MakeRefCounted("HTTP/1.1 " + - std::to_string(200))); - - response_headers->AddHeader("x-ipfs-path", - base::StringPrintf("/ipfs/%s", kCid1)); - - helper->MaybeCheckDNSLinkRecord(response_headers.get(), false); - ASSERT_FALSE(helper->ipfs_resolved_url_.is_valid()); - - GURL test_url("ipns://brantly.eth/"); - helper->SetPageURLForTesting(api_server); - helper->DNSLinkResolved(test_url, false, false); - - helper->MaybeCheckDNSLinkRecord(response_headers.get(), false); - ASSERT_FALSE(helper->ipfs_resolved_url_.is_valid()); - - helper->SetPageURLForTesting(api_server); - helper->DNSLinkResolved(test_url, false, false); - helper->UpdateDnsLinkButtonState(); - ASSERT_FALSE(helper->ipfs_resolved_url_.is_valid()); - - helper->SetPageURLForTesting(api_server); - helper->DNSLinkResolved(GURL(), false, false); - helper->MaybeCheckDNSLinkRecord(response_headers.get(), false); - ASSERT_FALSE(helper->ipfs_resolved_url_.is_valid()); -} - -TEST_F(IpfsTabHelperUnitTest, GatewayLikeUrlParsed_AutoRedirectEnabled) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - SetAutoRedirectToConfiguredGateway(true); - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - helper->SetPageURLForTesting( - GURL("https://ipfs.io/ipfs/" - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi/" - "?query#ref")); - - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL("ipfs://" - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqab" - "f3oclgtqy55fbzdi?query#ref")); - } - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - helper->SetPageURLForTesting( - GURL(base::StringPrintf("https://" - "%s.ipfs." - "ipfs.io?query#ref", - kCid1))); - - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://" - "%s.ipfs." - "ipfs.io?query#ref", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL("ipfs://" - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqab" - "f3oclgtqy55fbzdi/?query#ref")); - } - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_ASK); - helper->SetPageURLForTesting( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL("ipfs://" - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqab" - "f3oclgtqy55fbzdi?query#ref")); - } - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_LOCAL); - helper->SetPageURLForTesting( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL("ipfs://" - "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqab" - "f3oclgtqy55fbzdi?query#ref")); - } - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_DISABLED); - helper->SetPageURLForTesting( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL()); - } -} - -TEST_F(IpfsTabHelperUnitTest, - GatewayLikeUrlParsed_AutoRedirectEnabled_WrongFormat) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - SetAutoRedirectToConfiguredGateway(true); - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - helper->SetPageURLForTesting( - GURL(base::StringPrintf("https://ipfs.io/ipxxs/" - "%s/" - "?query#ref", - kCid1))); - - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://ipfs.io/ipxxs/" - "%s/" - "?query#ref", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL()); - } - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - helper->SetPageURLForTesting( - GURL(base::StringPrintf("https://" - "%s." - "ipxxs.ipfs.io?query#ref", - kCid1))); - - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://" - "%s." - "ipxxs.ipfs.io?query#ref", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL()); - } - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - helper->SetPageURLForTesting( - GURL("https://" - "bafy." - "ipfs.ipfs.io?query#ref")); - - web_contents()->NavigateAndCommit( - GURL("https://" - "bafy." - "ipfs.ipfs.io?query#ref")); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL()); - } - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - helper->SetPageURLForTesting( - GURL("https://ipfs.io/ipfs/" - "bafy/" - "?query#ref")); - - web_contents()->NavigateAndCommit( - GURL("https://ipfs.io/ipfs/" - "bafy/" - "?query#ref")); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL()); - } -} - -TEST_F(IpfsTabHelperUnitTest, - GatewayLikeUrlParsed_AutoRedirectEnabled_ConfiguredGatewayIgnored) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - SetAutoRedirectToConfiguredGateway(true); - - { - ResetRedirectUrl(); - - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - SetIPFSDefaultGatewayForTest(GURL("https://a.com/")); - - helper->SetPageURLForTesting( - GURL(base::StringPrintf("https://a.com/ipfs/" - "%s", - kCid1))); - - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://a.com/ipfs/" - "%s", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL()); - } -} - -TEST_F(IpfsTabHelperUnitTest, GatewayLikeUrlParsed_AutoRedirectDisabled) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - SetAutoRedirectToConfiguredGateway(false); - - { - SetIPFSResolveMethodPref(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY); - - helper->SetPageURLForTesting( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - web_contents()->NavigateAndCommit( - GURL(base::StringPrintf("https://ipfs.io/ipfs/" - "%s/" - "?query#ref", - kCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - EXPECT_EQ(redirect_url(), GURL()); - EXPECT_EQ(ipfs_tab_helper()->ipfs_resolved_url_, - GURL(base::StringPrintf("ipfs://" - "%s" - "?query#ref", - kCid1))); - } -} - -TEST_F(IpfsTabHelperUnitTest, GatewayIPNS_ResolveUrl) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit( - GURL("https://ipfs.io/ipns/brantly.eth/page?query#ref")); - helper->SetPageURLForTesting( - GURL("https://ipfs.io/ipns/brantly.eth/page?query#ref")); - - ipfs_host_resolver()->SetDNSLinkToRespond("/ipns/brantly.eth/"); - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK"); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL("ipns://brantly.eth/page?query#ref"), - helper->GetIPFSResolvedURL()); -} - -TEST_F(IpfsTabHelperUnitTest, GatewayIPNS_Redirect) { - SetAutoRedirectToConfiguredGateway(true); - - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit( - GURL("https://ipfs.io/ipns/brantly-eth/page?query#ref")); - helper->SetPageURLForTesting( - GURL("https://ipfs.io/ipns/brantly-eth/page?query#ref")); - - ipfs_host_resolver()->SetDNSLinkToRespond("x"); - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK"); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL("ipns://brantly.eth/page?query#ref"), redirect_url()); -} - -TEST_F(IpfsTabHelperUnitTest, GatewayIPNS_No_Redirect_WhenNoDnsLink) { - SetAutoRedirectToConfiguredGateway(true); - - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit( - GURL("https://ipfs.io/ipns/brantly-eth/page?query#ref")); - helper->SetPageURLForTesting( - GURL("https://ipfs.io/ipns/brantly-eth/page?query#ref")); - - ipfs_host_resolver()->SetDNSLinkToRespond(""); - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK"); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL(), redirect_url()); -} - -TEST_F(IpfsTabHelperUnitTest, GatewayIPNS_Redirect_LibP2PKey) { - SetAutoRedirectToConfiguredGateway(true); - - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL( - base::StringPrintf("https://ipfs.io/ipns/%s/page?query#ref", kIPNSCid1))); - helper->SetPageURLForTesting(GURL( - base::StringPrintf("https://ipfs.io/ipns/%s/page?query#ref", kIPNSCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL(base::StringPrintf("ipns://%s/page?query#ref", kIPNSCid1)), - redirect_url()); -} - -TEST_F(IpfsTabHelperUnitTest, GatewayIPNS_Redirect_LibP2PKey_NoAutoRedirect) { - SetAutoRedirectToConfiguredGateway(false); - - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit(GURL( - base::StringPrintf("https://ipfs.io/ipns/%s/page?query#ref", kIPNSCid1))); - helper->SetPageURLForTesting(GURL( - base::StringPrintf("https://ipfs.io/ipns/%s/page?query#ref", kIPNSCid1))); - - EXPECT_FALSE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL(base::StringPrintf("ipns://%s/page?query#ref", kIPNSCid1)), - helper->GetIPFSResolvedURL()); -} - -TEST_F(IpfsTabHelperUnitTest, GatewayIPNS_NoRedirect_WhenNoDnsLinkRecord) { - auto* helper = ipfs_tab_helper(); - ASSERT_TRUE(helper); - - web_contents()->NavigateAndCommit( - GURL("https://ipfs.io/ipns/brantly.eth/page?query#ref")); - helper->SetPageURLForTesting( - GURL("https://ipfs.io/ipns/brantly.eth/page?query#ref")); - - auto headers = net::HttpResponseHeaders::TryToCreate("HTTP/1.1 200 OK"); - helper->MaybeCheckDNSLinkRecord(headers.get(), false); - - EXPECT_TRUE(ipfs_host_resolver()->resolve_called()); - ASSERT_EQ(GURL(), helper->GetIPFSResolvedURL()); -} - -} // namespace ipfs diff --git a/browser/ipfs/sources.gni b/browser/ipfs/sources.gni deleted file mode 100644 index e8397fd40d99..000000000000 --- a/browser/ipfs/sources.gni +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (c) 2021 The Brave Authors. All rights reserved. -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this file, -# You can obtain one at http://mozilla.org/MPL/2.0/. - -import("//brave/components/ipfs/buildflags/buildflags.gni") -import("//extensions/buildflags/buildflags.gni") - -brave_browser_ipfs_sources = [] -brave_browser_ipfs_deps = [] - -if (enable_ipfs) { - brave_browser_ipfs_sources += [ - "//brave/browser/ipfs/content_browser_client_helper.cc", - "//brave/browser/ipfs/content_browser_client_helper.h", - "//brave/browser/ipfs/import/ipfs_import_controller.cc", - "//brave/browser/ipfs/import/ipfs_import_controller.h", - "//brave/browser/ipfs/import/save_package_observer.cc", - "//brave/browser/ipfs/import/save_package_observer.h", - "//brave/browser/ipfs/ipfs_blob_context_getter_factory.cc", - "//brave/browser/ipfs/ipfs_blob_context_getter_factory.h", - "//brave/browser/ipfs/ipfs_dns_resolver_impl.cc", - "//brave/browser/ipfs/ipfs_dns_resolver_impl.h", - "//brave/browser/ipfs/ipfs_host_resolver.cc", - "//brave/browser/ipfs/ipfs_host_resolver.h", - "//brave/browser/ipfs/ipfs_service_factory.cc", - "//brave/browser/ipfs/ipfs_service_factory.h", - "//brave/browser/ipfs/ipfs_service_impl_delegate.cc", - "//brave/browser/ipfs/ipfs_service_impl_delegate.h", - "//brave/browser/ipfs/ipfs_subframe_navigation_throttle.cc", - "//brave/browser/ipfs/ipfs_subframe_navigation_throttle.h", - "//brave/browser/ipfs/ipfs_tab_helper.cc", - "//brave/browser/ipfs/ipfs_tab_helper.h", - ] - - brave_browser_ipfs_deps += [ - "//base", - "//brave/browser/profiles:util", - "//brave/common", - "//brave/components/ipfs", - "//brave/components/services/ipfs/public/mojom", - "//chrome/browser:browser_process", - "//chrome/browser/profiles:profile", - "//chrome/browser/ui", - "//chrome/common:channel_info", - "//chrome/common:constants", - "//components/keyed_service/content", - "//components/prefs", - "//components/user_prefs", - "//content/public/browser", - "//extensions/buildflags", - "//services/network/public/mojom", - "//ui/base/clipboard", - "//ui/message_center/public/cpp", - "//ui/shell_dialogs", - ] - - if (enable_ipfs_local_node) { - brave_browser_ipfs_sources += [ - "//brave/browser/ipfs/ipfs_local_pin_service_factory.cc", - "//brave/browser/ipfs/ipfs_local_pin_service_factory.h", - ] - } - - if (enable_extensions) { - brave_browser_ipfs_deps += [ - "//extensions/browser", - "//extensions/common", - ] - } -} diff --git a/browser/ipfs/test/BUILD.gn b/browser/ipfs/test/BUILD.gn deleted file mode 100644 index 4b6b0dbff66e..000000000000 --- a/browser/ipfs/test/BUILD.gn +++ /dev/null @@ -1,84 +0,0 @@ -# Copyright (c) 2021 The Brave Authors. All rights reserved. -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this file, -# You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import("//testing/test.gni") - -source_set("unittests") { - testonly = true - sources = [ - "//brave/browser/ipfs/content_browser_client_helper_unittest.cc", - "//brave/browser/ipfs/ipfs_blob_context_getter_factory_unittest.cc", - "//brave/browser/ipfs/ipfs_host_resolver_unittest.cc", - "//brave/browser/ipfs/ipfs_tab_helper_unittest.cc", - "//brave/browser/ipfs/test/ipfs_dns_resolver_impl_unittest.cc", - "//brave/browser/ipfs/test/ipfs_navigation_throttle_unittest.cc", - "//brave/browser/ipfs/test/ipfs_network_utils_unittest.cc", - "//brave/browser/net/ipfs_redirect_network_delegate_helper_unittest.cc", - ] - - deps = [ - "//base/test:test_support", - "//brave/browser", - "//brave/common", - "//brave/components/decentralized_dns/content", - "//brave/components/decentralized_dns/core", - "//brave/components/ipfs", - "//brave/components/tor/buildflags", - "//chrome/common:channel_info", - "//chrome/test:test_support", - "//components/security_interstitials/content:security_interstitial_page", - "//content/test:test_support", - "//net", - "//net:test_support", - "//testing/gtest", - "//url", - ] -} # source_set("unittests") - -source_set("browsertests") { - testonly = true - if (!is_android) { - sources = [ - "//brave/browser/extensions/api/ipfs_apitest.cc", - "//brave/browser/ipfs/import/ipfs_import_controller_browsertest.cc", - "//brave/browser/ipfs/import/save_package_observer_browsertest.cc", - "//brave/browser/ipfs/ipfs_policy_browsertest.cc", - "//brave/browser/ipfs/ipfs_tab_helper_browsertest.cc", - "//brave/browser/ipfs/test/brave_ipfs_client_updater_browsertest.cc", - "//brave/browser/ipfs/test/ipfs_navigation_throttle_browsertest.cc", - "//brave/browser/ipfs/test/ipfs_not_connected_page_browsertest.cc", - "//brave/browser/ipfs/test/ipfs_onboarding_page_browsertest.cc", - "//brave/browser/ipfs/test/ipfs_service_browsertest.cc", - "//brave/browser/ipfs/test/ipns_keys_manager_browsertest.cc", - "//brave/browser/net/ipfs_redirect_network_delegate_helper_browsertest.cc", - ] - - deps = [ - "//base/test:test_support", - "//brave/browser", - "//brave/common:common", - "//brave/components/constants", - "//brave/components/infobars/core", - "//brave/components/ipfs", - "//chrome/browser/ui", - "//chrome/test:test_support", - "//chrome/test:test_support_ui", - "//components/infobars/content", - "//components/network_session_configurator/common:common", - "//components/policy/core/browser", - "//components/policy/core/common:test_support", - "//components/prefs:prefs", - "//components/security_interstitials/content:security_interstitial_page", - "//components/security_interstitials/core:core", - "//components/user_prefs:user_prefs", - "//content/test:test_support", - "//net", - "//net:test_support", - "//testing/gtest", - "//url", - ] - defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] - } -} # source_set("browsertests") diff --git a/browser/ipfs/test/brave_ipfs_client_updater_browsertest.cc b/browser/ipfs/test/brave_ipfs_client_updater_browsertest.cc deleted file mode 100644 index b04fd606c18a..000000000000 --- a/browser/ipfs/test/brave_ipfs_client_updater_browsertest.cc +++ /dev/null @@ -1,145 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/ipfs/brave_ipfs_client_updater.h" - -#include "base/files/file_util.h" -#include "base/path_service.h" -#include "base/test/thread_test_helper.h" -#include "brave/browser/brave_browser_process.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/constants/brave_paths.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "build/build_config.h" -#include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/test/base/ui_test_utils.h" -#include "content/public/test/browser_test.h" - -using extensions::ExtensionBrowserTest; - -static const char kIpfsClientUpdaterComponentTestId[] = - "ngicbhhaldfdgmjhilmnleppfpmkgbbk"; -static const char kIpfsClientUpdaterComponentTestBase64PublicKey[] = - "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAncFKJWCX6RqCRYOR0t5a" - "js7HWIVP3Ne272HZs3MqiaNvo9IikbPd4JnUMeQjLhkXTwxg6Up9Tmrgo3M8T91D" - "dggzpAG4OlhKj3l3N5kZnj/CxQ73YVd41jHAF97lZVoD5VTCGtEelzA5eHI4N4Hd" - "cvMiMvr/Kj9pdlJ+kbg5UZIXAYLXUB/NfBjKlpCTZ+Ys/2nxRN27kUVnrE/gTitE" - "Aj1PZGOxJd1ZeiYc29j0ETf3AmOsZyVrIs6HJzHEJLnYQFaa76dRwVabm1Zt/28T" - "+NJdHcu+jj2LIEcxmZ8TjtbK9kfWORHhA/ELjTx4ScvKfVKJgdLpxy5QOBFFnTLR" - "QQIDAQAB"; - -class BraveIpfsClientUpdaterTest : public ExtensionBrowserTest { - public: - BraveIpfsClientUpdaterTest() = default; - - void SetUpOnMainThread() override { - ExtensionBrowserTest::SetUpOnMainThread(); - InitEmbeddedTestServer(); - } - - void InitEmbeddedTestServer() { - base::FilePath test_data_dir; - base::PathService::Get(brave::DIR_TEST_DATA, &test_data_dir); - embedded_test_server()->ServeFilesFromDirectory(test_data_dir); - ASSERT_TRUE(embedded_test_server()->Start()); - } - - void GetTestDataDir(base::FilePath* test_data_dir) { - base::ScopedAllowBlockingForTesting allow_blocking; - base::PathService::Get(brave::DIR_TEST_DATA, test_data_dir); - } - - bool PathExists(const base::FilePath& file_path) { - base::ScopedAllowBlockingForTesting allow_blocking; - return base::PathExists(file_path); - } - - void SetComponentIdAndBase64PublicKeyForTest( - const std::string& component_id, - const std::string& component_base64_public_key) { - ipfs::BraveIpfsClientUpdater::SetComponentIdAndBase64PublicKeyForTest( - component_id, component_base64_public_key); - } - - bool InstallIpfsClientUpdater() { -#if BUILDFLAG(IS_WIN) - return InstallIpfsClientUpdater("ipfs-client-updater-win"); -#elif BUILDFLAG(IS_MAC) - return InstallIpfsClientUpdater("ipfs-client-updater-mac"); -#elif BUILDFLAG(IS_LINUX) - return InstallIpfsClientUpdater("ipfs-client-updater-linux"); -#else - return false; -#endif - } - - bool InstallIpfsClientUpdater(const std::string& extension_dir) { - base::FilePath test_data_dir; - GetTestDataDir(&test_data_dir); - const extensions::Extension* ipfs_client_updater = - InstallExtension(test_data_dir.AppendASCII("ipfs-client-updater") - .AppendASCII(extension_dir), - 1); - if (!ipfs_client_updater) - return false; - - g_brave_browser_process->ipfs_client_updater()->OnComponentReady( - ipfs_client_updater->id(), ipfs_client_updater->path(), ""); - WaitForIpfsClientUpdaterThread(); - WaitForMainThreadTasksToFinish(); - return true; - } - - void WaitForIpfsClientUpdaterThread() { - scoped_refptr io_helper(new base::ThreadTestHelper( - g_brave_browser_process->ipfs_client_updater()->GetTaskRunner())); - ASSERT_TRUE(io_helper->Run()); - } - - void WaitForMainThreadTasksToFinish() { - base::RunLoop loop; - loop.RunUntilIdle(); - } - - void SetIpfsExecutablePath(const base::FilePath& path) { - g_brave_browser_process->ipfs_client_updater()->SetExecutablePath(path); - } -}; - -// Load the Ipfs client updater extension and verify that it correctly -// installs the client. -IN_PROC_BROWSER_TEST_F(BraveIpfsClientUpdaterTest, IpfsClientInstalls) { - SetComponentIdAndBase64PublicKeyForTest( - kIpfsClientUpdaterComponentTestId, - kIpfsClientUpdaterComponentTestBase64PublicKey); - ASSERT_TRUE(InstallIpfsClientUpdater()); - base::FilePath executable_path = - g_brave_browser_process->ipfs_client_updater()->GetExecutablePath(); - ASSERT_TRUE(PathExists(executable_path)); -} - -IN_PROC_BROWSER_TEST_F(BraveIpfsClientUpdaterTest, IpfsExecutableReady) { - ipfs::IpfsService* ipfs_service = - ipfs::IpfsServiceFactory::GetInstance()->GetForContext(profile()); - ASSERT_TRUE(ipfs_service); - ASSERT_FALSE(ipfs_service->IsIPFSExecutableAvailable()); - ASSERT_TRUE(ipfs_service->GetIpfsExecutablePath().empty()); - SetComponentIdAndBase64PublicKeyForTest( - kIpfsClientUpdaterComponentTestId, - kIpfsClientUpdaterComponentTestBase64PublicKey); - ASSERT_TRUE(InstallIpfsClientUpdater()); - base::FilePath executable_path = - g_brave_browser_process->ipfs_client_updater()->GetExecutablePath(); - ASSERT_TRUE(PathExists(executable_path)); - - EXPECT_EQ(ipfs_service->GetIpfsExecutablePath(), executable_path); - ASSERT_TRUE(ipfs_service->IsIPFSExecutableAvailable()); - - base::FilePath new_path(FILE_PATH_LITERAL("newpath")); - SetIpfsExecutablePath(new_path); - EXPECT_EQ(ipfs_service->GetIpfsExecutablePath(), new_path); - ASSERT_TRUE(ipfs_service->IsIPFSExecutableAvailable()); -} diff --git a/browser/ipfs/test/ipfs_dns_resolver_impl_unittest.cc b/browser/ipfs/test/ipfs_dns_resolver_impl_unittest.cc deleted file mode 100644 index f57619da1f14..000000000000 --- a/browser/ipfs/test/ipfs_dns_resolver_impl_unittest.cc +++ /dev/null @@ -1,45 +0,0 @@ -/* Copyright (c) 2022 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ipfs/ipfs_dns_resolver_impl.h" - -#include -#include - -#include "content/public/browser/network_service_instance.h" -#include "content/public/test/browser_task_environment.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ipfs { - -class IpfsDnsResolverImplUnitTest : public testing::Test { - public: - IpfsDnsResolverImplUnitTest() = default; - IpfsDnsResolverImplUnitTest(const IpfsDnsResolverImplUnitTest&) = delete; - IpfsDnsResolverImplUnitTest& operator=(const IpfsDnsResolverImplUnitTest&) = - delete; - ~IpfsDnsResolverImplUnitTest() override = default; - - void SetUp() override {} - - void TearDown() override {} - content::BrowserTaskEnvironment task_environment_; -}; - -TEST_F(IpfsDnsResolverImplUnitTest, ReconnectOnMojoError) { - std::unique_ptr ipfs_dns_resolver_impl_ = - std::make_unique(); - ipfs_dns_resolver_impl_->receiver_.reset(); - ipfs_dns_resolver_impl_->OnDnsConfigChangeManagerConnectionError(); - EXPECT_FALSE(ipfs_dns_resolver_impl_->receiver_.is_bound()); - { - base::RunLoop loop; - while (!ipfs_dns_resolver_impl_->receiver_.is_bound()) { - loop.RunUntilIdle(); - } - } -} - -} // namespace ipfs diff --git a/browser/ipfs/test/ipfs_navigation_throttle_browsertest.cc b/browser/ipfs/test/ipfs_navigation_throttle_browsertest.cc deleted file mode 100644 index ed61880ca841..000000000000 --- a/browser/ipfs/test/ipfs_navigation_throttle_browsertest.cc +++ /dev/null @@ -1,225 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include - -#include "base/memory/raw_ptr.h" -#include "base/test/scoped_feature_list.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/ipfs/features.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_not_connected_page.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/prefs/pref_service.h" -#include "components/security_interstitials/content/security_interstitial_page.h" -#include "components/security_interstitials/content/security_interstitial_tab_helper.h" -#include "components/security_interstitials/core/controller_client.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "content/public/test/test_navigation_observer.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" - -namespace { - -security_interstitials::SecurityInterstitialPage* GetCurrentInterstitial( - content::WebContents* web_contents) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - web_contents); - if (!helper) { - return nullptr; - } - return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); -} - -security_interstitials::SecurityInterstitialPage::TypeID GetInterstitialType( - content::WebContents* web_contents) { - security_interstitials::SecurityInterstitialPage* page = - GetCurrentInterstitial(web_contents); - if (!page) { - return nullptr; - } - return page->GetTypeForTesting(); -} - -void SendInterstitialCommand( - content::WebContents* web_contents, - security_interstitials::SecurityInterstitialCommand command) { - GetCurrentInterstitial(web_contents) - ->CommandReceived(base::NumberToString(command)); -} - -void SendInterstitialCommandSync( - Browser* browser, - security_interstitials::SecurityInterstitialCommand command) { - content::WebContents* web_contents = - browser->tab_strip_model()->GetActiveWebContents(); - - EXPECT_EQ(ipfs::IPFSNotConnectedPage::kTypeForTesting, - GetInterstitialType(web_contents)); - - content::TestNavigationObserver navigation_observer(web_contents, 1); - SendInterstitialCommand(web_contents, command); - navigation_observer.Wait(); - - EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); -} - -} // namespace - -namespace ipfs { - -class IpfsNavigationThrottleBrowserTest : public InProcessBrowserTest { - public: - IpfsNavigationThrottleBrowserTest() { - feature_list_.InitAndEnableFeature(ipfs::features::kIpfsFeature); - } - - ~IpfsNavigationThrottleBrowserTest() override = default; - - void SetUpOnMainThread() override { - ipfs_service_ = - IpfsServiceFactory::GetInstance()->GetForContext(browser()->profile()); - ASSERT_TRUE(ipfs_service_); - ipfs_service_->SetAllowIpfsLaunchForTest(true); - - ipfs_url_ = GURL( - "http://127.0.0.1:48080/ipfs/" - "QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"); - gateway_url_ = GURL( - "https://dweb.link/ipfs/" - "QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"); - - InProcessBrowserTest::SetUpOnMainThread(); - } - - void ResetTestServer( - const net::EmbeddedTestServer::HandleRequestCallback& callback) { - test_server_ = std::make_unique( - net::test_server::EmbeddedTestServer::TYPE_HTTPS); - test_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); - test_server_->RegisterRequestHandler(callback); - ASSERT_TRUE(test_server_->Start()); - ipfs_service_->SetServerEndpointForTest(test_server_->base_url()); - } - - std::unique_ptr GetConnectedPeersResponse( - const net::test_server::HttpRequest& request, - bool empty) { - if (request.GetURL().path_piece() != kSwarmPeersPath) { - return nullptr; - } - - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - if (empty) { - http_response->set_content(R"({})"); - } else { - http_response->set_content(R"({ - "Peers": [ - { - "Addr": "/ip4/101.101.101.101/tcp/4001", - "Direction": 0, - "Peer": "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ" - }, - { - "Addr": "/ip4/102.102.102.102/tcp/4001", - "Direction": 0, - "Peer": "QmStjfkGsfQGQQm6Gdxin6DvrZsFTmTNoX5oEFMzYrc1PS" - } - ] - })"); - } - - return http_response; - } - - std::unique_ptr HandleGetEmptyConnectedPeers( - const net::test_server::HttpRequest& request) { - return GetConnectedPeersResponse(request, true); - } - - std::unique_ptr HandleGetConnectedPeers( - const net::test_server::HttpRequest& request) { - return GetConnectedPeersResponse(request, false); - } - - IpfsService* ipfs_service() { return ipfs_service_; } - PrefService* GetPrefs() const { return browser()->profile()->GetPrefs(); } - const GURL& ipfs_url() { return ipfs_url_; } - const GURL& gateway_url() { return gateway_url_; } - - private: - std::unique_ptr test_server_; - raw_ptr ipfs_service_ = nullptr; - base::test::ScopedFeatureList feature_list_; - GURL ipfs_url_; - GURL gateway_url_; -}; - -IN_PROC_BROWSER_TEST_F(IpfsNavigationThrottleBrowserTest, - ShowInterstitialForEmptyConnectedPeers) { - ResetTestServer(base::BindRepeating( - &IpfsNavigationThrottleBrowserTest::HandleGetEmptyConnectedPeers, - base::Unretained(this))); - - GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - // Navigate to IPFS URL and check if we'll show the interstitial when there - // are no connected peers. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(IPFSNotConnectedPage::kTypeForTesting, - GetInterstitialType(web_contents)); - EXPECT_FALSE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - - // Send Proceed command and check if we fallback to gateway and pref is set. - SendInterstitialCommandSync( - browser(), - security_interstitials::SecurityInterstitialCommand::CMD_PROCEED); - EXPECT_EQ(gateway_url(), web_contents->GetURL()); - EXPECT_TRUE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - - // Navigate to that URL again and see if we auto fallback to gateway this - // time without interstitials. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(nullptr, GetInterstitialType(web_contents)); - EXPECT_EQ(gateway_url(), web_contents->GetURL()); -} - -IN_PROC_BROWSER_TEST_F(IpfsNavigationThrottleBrowserTest, - NoInterstitialShownForNonEmptyConnectedPeers) { - ResetTestServer(base::BindRepeating( - &IpfsNavigationThrottleBrowserTest::HandleGetConnectedPeers, - base::Unretained(this))); - - EXPECT_FALSE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(nullptr, GetInterstitialType(web_contents)); -} - -} // namespace ipfs diff --git a/browser/ipfs/test/ipfs_navigation_throttle_unittest.cc b/browser/ipfs/test/ipfs_navigation_throttle_unittest.cc deleted file mode 100644 index 086433ce927d..000000000000 --- a/browser/ipfs/test/ipfs_navigation_throttle_unittest.cc +++ /dev/null @@ -1,475 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/ipfs/ipfs_navigation_throttle.h" - -#include -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/test/bind.h" -#include "base/test/scoped_feature_list.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/ipfs/features.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/keys/ipns_keys_manager.h" -#include "brave/components/ipfs/pref_names.h" -#include "brave/components/tor/buildflags/buildflags.h" -#include "chrome/browser/prefs/browser_prefs.h" -#include "chrome/test/base/chrome_render_view_host_test_harness.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile.h" -#include "chrome/test/base/testing_profile_manager.h" -#include "components/security_interstitials/content/security_interstitial_tab_helper.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/test/browser_task_environment.h" -#include "content/public/test/mock_navigation_handle.h" -#include "content/public/test/test_utils.h" -#include "content/public/test/web_contents_tester.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -#if BUILDFLAG(ENABLE_TOR) -#include "brave/browser/tor/tor_profile_manager.h" -#endif - -using content::NavigationThrottle; - -namespace { - -constexpr char kTestProfileName[] = "TestProfile"; - -const GURL& GetIPFSSchemeURL() { - static const GURL ipfs_url( - "ipfs://bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq/"); - return ipfs_url; -} - -const GURL& GetIPFSURL() { - static const GURL ipfs_url( - "http://localhost:48080/ipfs/" - "bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq/wiki/" - "Vincent_van_Gogh.html"); // NOLINT - return ipfs_url; -} - -const GURL& GetIPNSURL() { - static const GURL ipns_url( - "http://localhost:48080/ipns/tr.wikipedia-on-ipfs.org/wiki/" - "Anasayfa.html"); // NOLINT - return ipns_url; -} - -const GURL& GetPublicGatewayURL() { - static const GURL public_gw_url( - "https://dweb.link/ipfs/QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"); - return public_gw_url; -} - -const GURL& GetNonIPFSURL() { - static const GURL non_ipfs_url("http://github.com/ipfs/go-ipfs"); - return non_ipfs_url; -} - -} // namespace - -namespace ipfs { - -class IpfsNavigationThrottleUnitTest : public testing::Test { - public: - IpfsNavigationThrottleUnitTest() = default; - IpfsNavigationThrottleUnitTest(const IpfsNavigationThrottleUnitTest&) = - delete; - IpfsNavigationThrottleUnitTest& operator=( - const IpfsNavigationThrottleUnitTest&) = delete; - ~IpfsNavigationThrottleUnitTest() override = default; - - void SetUp() override { - feature_list_.InitAndEnableFeature(ipfs::features::kIpfsFeature); - TestingBrowserProcess* browser_process = TestingBrowserProcess::GetGlobal(); - profile_manager_ = std::make_unique(browser_process); - ASSERT_TRUE(profile_manager_->SetUp()); - - profile_ = profile_manager_->CreateTestingProfile(kTestProfileName); - - web_contents_ = - content::WebContentsTester::CreateTestWebContents(profile_, nullptr); - locale_ = "en-US"; - } - - void TearDown() override { - navigation_handles_.clear(); - web_contents_.reset(); - profile_ = nullptr; - profile_manager_->DeleteTestingProfile(kTestProfileName); - } - - content::WebContents* web_contents() { return web_contents_.get(); } - - std::unique_ptr CreateDeferredNavigation( - IpfsService* service, - const base::RepeatingClosure& resume_callback) { - auto test_handle = - std::make_unique(web_contents()); - test_handle->set_url(GetIPFSURL()); - std::unique_ptr throttle = - IpfsNavigationThrottle::MaybeCreateThrottleFor( - test_handle.get(), service, profile_->GetPrefs(), locale()); - throttle->set_resume_callback_for_testing(resume_callback); - navigation_handles_.push_back(std::move(test_handle)); - EXPECT_EQ(NavigationThrottle::DEFER, throttle->WillStartRequest().action()) - << GetIPFSURL(); - return throttle; - } - - IpfsService* ipfs_service(content::BrowserContext* context) { - return IpfsServiceFactory::GetForContext(context); - } - - // Helper that creates simple test guest profile. - std::unique_ptr CreateGuestProfile() { - TestingProfile::Builder profile_builder; - profile_builder.SetGuestSession(); - return profile_builder.Build(); - } - - Profile* profile() { return profile_; } - - const std::string& locale() { return locale_; } - - private: - content::BrowserTaskEnvironment task_environment_; - content::RenderViewHostTestEnabler test_render_host_factories_; - std::unique_ptr web_contents_; - raw_ptr profile_ = nullptr; - std::unique_ptr profile_manager_; - base::test::ScopedFeatureList feature_list_; - std::string locale_; - - // Storage for all navigation handles used by `IpfsNavigationThrottle` - // instances during tests. - std::vector> - navigation_handles_; -}; - -TEST_F(IpfsNavigationThrottleUnitTest, DeferMultipleUntilIpfsProcessLaunched) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - auto* service = ipfs_service(profile()); - ASSERT_TRUE(service); - service->SetSkipGetConnectedPeersCallbackForTest(true); - service->GetIpnsKeysManager()->SetLoadCallbackForTest(base::DoNothing()); - bool was_navigation_resumed1 = false; - auto throttle1 = CreateDeferredNavigation( - service, - base::BindLambdaForTesting([&]() { was_navigation_resumed1 = true; })); - - bool was_navigation_resumed2 = false; - auto throttle2 = CreateDeferredNavigation( - service, - base::BindLambdaForTesting([&]() { was_navigation_resumed2 = true; })); - - bool was_navigation_resumed3 = false; - auto throttle3 = CreateDeferredNavigation( - service, - base::BindLambdaForTesting([&]() { was_navigation_resumed3 = true; })); - - service->SetAllowIpfsLaunchForTest(true); - service->RunLaunchDaemonCallbackForTest(true); - EXPECT_FALSE(was_navigation_resumed1); - EXPECT_FALSE(was_navigation_resumed2); - EXPECT_FALSE(was_navigation_resumed3); - auto peers = std::vector{ - "/ip4/101.101.101.101/tcp/4001/p2p/" - "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"}; - throttle1->OnGetConnectedPeers(true, peers); - throttle2->OnGetConnectedPeers(true, peers); - throttle3->OnGetConnectedPeers(true, peers); - EXPECT_TRUE(was_navigation_resumed1); - EXPECT_TRUE(was_navigation_resumed2); - EXPECT_TRUE(was_navigation_resumed3); -} - -TEST_F(IpfsNavigationThrottleUnitTest, SequentialRequests) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - auto* service = ipfs_service(profile()); - ASSERT_TRUE(service); - service->SetSkipGetConnectedPeersCallbackForTest(true); - service->SetGetConnectedPeersCalledForTest(false); - bool was_navigation_resumed1 = false; - auto throttle1 = CreateDeferredNavigation( - service, - base::BindLambdaForTesting([&]() { was_navigation_resumed1 = true; })); - - bool was_navigation_resumed2 = false; - auto throttle2 = CreateDeferredNavigation( - service, - base::BindLambdaForTesting([&]() { was_navigation_resumed2 = true; })); - - service->SetAllowIpfsLaunchForTest(true); - service->GetIpnsKeysManager()->SetLoadCallbackForTest(base::DoNothing()); - service->RunLaunchDaemonCallbackForTest(true); - throttle1->OnIpfsLaunched(true); - EXPECT_FALSE(was_navigation_resumed1); - EXPECT_FALSE(was_navigation_resumed2); - - auto peers = std::vector(); - throttle1->OnGetConnectedPeers(true, peers); - EXPECT_FALSE(was_navigation_resumed1); - EXPECT_FALSE(was_navigation_resumed2); - - peers = std::vector{ - "/ip4/101.101.101.101/tcp/4001/p2p/" - "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"}; - throttle1->OnGetConnectedPeers(true, peers); - EXPECT_TRUE(was_navigation_resumed1); - EXPECT_FALSE(was_navigation_resumed2); - throttle2->OnGetConnectedPeers(true, peers); - EXPECT_TRUE(was_navigation_resumed2); - auto throttle3 = CreateDeferredNavigation(service, base::RepeatingClosure()); - - ASSERT_TRUE(service->WasConnectedPeersCalledForTest()); -} - -TEST_F(IpfsNavigationThrottleUnitTest, DeferUntilPeersFetched) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - auto* service = ipfs_service(profile()); - ASSERT_TRUE(service); - service->SetSkipGetConnectedPeersCallbackForTest(true); - - service->SetAllowIpfsLaunchForTest(true); - service->GetIpnsKeysManager()->SetLoadCallbackForTest(base::DoNothing()); - service->RunLaunchDaemonCallbackForTest(true); - - bool was_navigation_resumed1 = false; - auto throttle1 = CreateDeferredNavigation( - service, - base::BindLambdaForTesting([&]() { was_navigation_resumed1 = true; })); - - bool was_navigation_resumed2 = false; - auto throttle2 = CreateDeferredNavigation( - service, - base::BindLambdaForTesting([&]() { was_navigation_resumed2 = true; })); - EXPECT_FALSE(was_navigation_resumed1); - EXPECT_FALSE(was_navigation_resumed2); - - auto peers = std::vector(); - throttle1->OnGetConnectedPeers(true, peers); - EXPECT_FALSE(was_navigation_resumed1); - EXPECT_FALSE(was_navigation_resumed2); - - throttle2->OnGetConnectedPeers(true, peers); - EXPECT_FALSE(was_navigation_resumed1); - EXPECT_FALSE(was_navigation_resumed2); - - peers = std::vector{ - "/ip4/101.101.101.101/tcp/4001/p2p/" - "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"}; - throttle1->OnGetConnectedPeers(true, peers); - EXPECT_TRUE(was_navigation_resumed1); - EXPECT_FALSE(was_navigation_resumed2); - - throttle2->OnGetConnectedPeers(true, peers); - EXPECT_TRUE(was_navigation_resumed1); - EXPECT_TRUE(was_navigation_resumed2); -} - -TEST_F(IpfsNavigationThrottleUnitTest, DeferUntilIpfsProcessLaunched) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - auto peers = std::vector{ - "/ip4/101.101.101.101/tcp/4001/p2p/" - "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"}; - - auto* service = ipfs_service(profile()); - ASSERT_TRUE(service); - service->SetSkipGetConnectedPeersCallbackForTest(true); - service->GetIpnsKeysManager()->SetLoadCallbackForTest(base::DoNothing()); - - content::MockNavigationHandle test_handle(web_contents()); - test_handle.set_url(GetIPFSURL()); - auto throttle = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, service, profile()->GetPrefs(), locale()); - ASSERT_TRUE(throttle != nullptr); - bool was_navigation_resumed = false; - throttle->set_resume_callback_for_testing( - base::BindLambdaForTesting([&]() { was_navigation_resumed = true; })); - EXPECT_EQ(NavigationThrottle::DEFER, throttle->WillStartRequest().action()) - << GetIPFSURL(); - service->SetAllowIpfsLaunchForTest(true); - service->RunLaunchDaemonCallbackForTest(true); - EXPECT_FALSE(was_navigation_resumed); - - was_navigation_resumed = false; - EXPECT_EQ(NavigationThrottle::DEFER, throttle->WillStartRequest().action()) - << GetIPFSURL(); - throttle->OnGetConnectedPeers(true, peers); - EXPECT_TRUE(was_navigation_resumed); - - service->SetAllowIpfsLaunchForTest(false); - - was_navigation_resumed = false; - test_handle.set_url(GetIPNSURL()); - EXPECT_EQ(NavigationThrottle::DEFER, throttle->WillStartRequest().action()) - << GetIPNSURL(); - service->SetAllowIpfsLaunchForTest(true); - service->RunLaunchDaemonCallbackForTest(true); - EXPECT_FALSE(was_navigation_resumed); - - was_navigation_resumed = false; - EXPECT_EQ(NavigationThrottle::DEFER, throttle->WillStartRequest().action()) - << GetIPNSURL(); - throttle->OnGetConnectedPeers(true, peers); - EXPECT_TRUE(was_navigation_resumed); -} - -TEST_F(IpfsNavigationThrottleUnitTest, ProceedForGatewayNodeMode) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_GATEWAY)); - - content::MockNavigationHandle test_handle(web_contents()); - test_handle.set_url(GetIPFSURL()); - auto throttle = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, ipfs_service(profile()), profile()->GetPrefs(), locale()); - ASSERT_TRUE(throttle != nullptr); - EXPECT_EQ(NavigationThrottle::PROCEED, throttle->WillStartRequest().action()) - << GetIPFSURL(); - - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_DISABLED)); - EXPECT_EQ(NavigationThrottle::PROCEED, throttle->WillStartRequest().action()) - << GetIPFSURL(); -} - -TEST_F(IpfsNavigationThrottleUnitTest, ProceedForAskNodeMode) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - content::MockNavigationHandle test_handle(web_contents()); - test_handle.set_url(GetIPFSURL()); - auto throttle = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, ipfs_service(profile()), profile()->GetPrefs(), locale()); - ASSERT_TRUE(throttle != nullptr); - EXPECT_EQ(NavigationThrottle::PROCEED, throttle->WillStartRequest().action()) - << GetIPFSURL(); - - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_DISABLED)); - EXPECT_EQ(NavigationThrottle::PROCEED, throttle->WillStartRequest().action()) - << GetIPFSURL(); -} - -TEST_F(IpfsNavigationThrottleUnitTest, ShowInterstitial) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - content::MockNavigationHandle test_handle(web_contents()); - test_handle.set_url(GetIPFSSchemeURL()); - - auto throttle = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, ipfs_service(profile()), profile()->GetPrefs(), locale()); - ASSERT_TRUE(throttle != nullptr); - EXPECT_EQ(NavigationThrottle::CANCEL, throttle->WillStartRequest().action()); - - ASSERT_TRUE( - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - web_contents()) - ->IsInterstitialPendingForNavigation(test_handle.GetNavigationId())); -} - -TEST_F(IpfsNavigationThrottleUnitTest, ShowInterstitialAfterNavigationFails) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - content::MockNavigationHandle test_handle(web_contents()); - test_handle.set_url(GetNonIPFSURL()); - - auto throttle = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, ipfs_service(profile()), profile()->GetPrefs(), locale()); - ASSERT_TRUE(throttle != nullptr); - EXPECT_EQ(NavigationThrottle::PROCEED, throttle->WillStartRequest().action()) - << GetIPFSURL(); - - test_handle.set_net_error_code(net::ERR_IPFS_RESOLVE_METHOD_NOT_SELECTED); - EXPECT_EQ(NavigationThrottle::CANCEL, throttle->WillFailRequest().action()); - ASSERT_TRUE( - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - web_contents()) - ->IsInterstitialPendingForNavigation(test_handle.GetNavigationId())); -} - -TEST_F(IpfsNavigationThrottleUnitTest, ProceedForNonLocalGatewayURL) { - profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - content::MockNavigationHandle test_handle(web_contents()); - test_handle.set_url(GetPublicGatewayURL()); - auto throttle = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, ipfs_service(profile()), profile()->GetPrefs(), locale()); - ASSERT_TRUE(throttle != nullptr); - EXPECT_EQ(NavigationThrottle::PROCEED, throttle->WillStartRequest().action()) - << GetPublicGatewayURL(); - - test_handle.set_url(GetNonIPFSURL()); - EXPECT_EQ(NavigationThrottle::PROCEED, throttle->WillStartRequest().action()) - << GetNonIPFSURL(); -} - -TEST_F(IpfsNavigationThrottleUnitTest, Instantiation) { - content::MockNavigationHandle test_handle(web_contents()); - auto throttle = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &test_handle, ipfs_service(profile()), profile()->GetPrefs(), locale()); - EXPECT_TRUE(throttle != nullptr); - - // Disable in OTR profile. - auto otr_web_contents = content::WebContentsTester::CreateTestWebContents( - profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true), nullptr); - content::MockNavigationHandle otr_test_handle(otr_web_contents.get()); - auto throttle_in_otr = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &otr_test_handle, - ipfs_service(profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true)), - profile()->GetPrefs(), locale()); - EXPECT_EQ(throttle_in_otr, nullptr); - - // Disable in guest sessions. - auto guest_profile = CreateGuestProfile(); - auto guest_web_contents = content::WebContentsTester::CreateTestWebContents( - guest_profile.get(), nullptr); - content::MockNavigationHandle guest_test_handle(guest_web_contents.get()); - auto throttle_in_guest = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &guest_test_handle, ipfs_service(guest_profile.get()), - profile()->GetPrefs(), locale()); - EXPECT_EQ(throttle_in_guest, nullptr); -} - -#if BUILDFLAG(ENABLE_TOR) -TEST_F(IpfsNavigationThrottleUnitTest, NotInstantiatedInTor) { - Profile* tor_profile = - TorProfileManager::GetInstance().GetTorProfile(profile()); - ASSERT_TRUE(tor_profile->IsTor()); - ASSERT_TRUE(tor_profile->IsOffTheRecord()); - ASSERT_EQ(tor_profile->GetOriginalProfile(), profile()); - - auto tor_web_contents = - content::WebContentsTester::CreateTestWebContents(tor_profile, nullptr); - content::MockNavigationHandle tor_test_handle(tor_web_contents.get()); - auto throttle_in_tor = IpfsNavigationThrottle::MaybeCreateThrottleFor( - &tor_test_handle, ipfs_service(tor_profile), profile()->GetPrefs(), - locale()); - EXPECT_EQ(throttle_in_tor, nullptr); -} -#endif - -} // namespace ipfs diff --git a/browser/ipfs/test/ipfs_network_utils_unittest.cc b/browser/ipfs/test/ipfs_network_utils_unittest.cc deleted file mode 100644 index 6736caf8e9a5..000000000000 --- a/browser/ipfs/test/ipfs_network_utils_unittest.cc +++ /dev/null @@ -1,145 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/ipfs/ipfs_network_utils.h" - -#include -#include -#include - -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "brave/browser/ipfs/ipfs_blob_context_getter_factory.h" -#include "chrome/test/base/testing_profile.h" -#include "content/public/test/browser_task_environment.h" -#include "services/network/public/cpp/data_element.h" -#include "services/network/public/cpp/resource_request.h" -#include "storage/browser/blob/blob_data_builder.h" -#include "storage/browser/blob/blob_data_item.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ipfs { - -class IpfsNetwrokUtilsUnitTest : public testing::Test { - public: - IpfsNetwrokUtilsUnitTest() = default; - ~IpfsNetwrokUtilsUnitTest() override = default; - - void SetUp() override { - blob_getter_factory_ = - std::make_unique(&profile_); - } - - base::FilePath CreateCustomTestFile(const base::FilePath& dir, - const std::string& filename, - const std::string& content) { - base::FilePath file_path = dir.AppendASCII(filename); - - base::WriteFile(file_path, content); - return file_path; - } - - IpfsBlobContextGetterFactory* blob_getter_factory() { - return blob_getter_factory_.get(); - } - - void ValidateRequest(base::OnceClosure callback, - std::unique_ptr request) { - ASSERT_TRUE(request.get()); - ASSERT_EQ(request->request_body->elements()->size(), size_t(1)); - ASSERT_EQ(request->request_body->elements()->front().type(), - network::mojom::DataElementDataView::Tag::kDataPipe); - if (callback) - std::move(callback).Run(); - } - - private: - content::BrowserTaskEnvironment task_environment_; - TestingProfile profile_; - std::unique_ptr blob_getter_factory_; -}; - -TEST_F(IpfsNetwrokUtilsUnitTest, AddMultipartHeaderForUploadWithFileName) { - const char ref_output[] = - "--boundary\r\nContent-Disposition: form-data; name=\"value name\"; " - "filename=\"value\"\r\nContent-Type: content type\r\n\r\n" - "--boundary\r\nAbspath: file_abs_path\r\nContent-Disposition: form-data; " - "name=\"value name\"; " - "filename=\"value\"\r\nContent-Type: \r\n\r\n"; - std::string post_data; - AddMultipartHeaderForUploadWithFileName("value name", "value", std::string(), - "boundary", "content type", - &post_data); - AddMultipartHeaderForUploadWithFileName( - "value name", "value", "file_abs_path", "boundary", "", &post_data); - EXPECT_STREQ(ref_output, post_data.c_str()); -} - -TEST_F(IpfsNetwrokUtilsUnitTest, FileSizeCalculation) { - base::ScopedTempDir dir; - ASSERT_TRUE(dir.CreateUniqueTempDir()); - base::FilePath file_path = - dir.GetPath().Append(FILE_PATH_LITERAL("test.file")); - - std::string content = "test\n\rmultiline\n\rcontent"; - ASSERT_TRUE(base::WriteFile(file_path, content)); - EXPECT_EQ(CalculateFileSize(file_path), (int64_t)content.size()); - - base::FilePath nonexistent_file_path = - dir.GetPath().Append(FILE_PATH_LITERAL("fake.file")); - EXPECT_EQ(CalculateFileSize(nonexistent_file_path), -1); -} - -TEST_F(IpfsNetwrokUtilsUnitTest, CreateRequestForFileTest) { - base::ScopedTempDir dir; - ASSERT_TRUE(dir.CreateUniqueTempDir()); - std::string content = "test\n\rmultiline\n\rcontent"; - std::string filename = "test_name"; - base::FilePath upload_file_path = - CreateCustomTestFile(dir.GetPath(), filename, content); - size_t file_size = content.size(); - std::string mime_type = "test/type"; - std::string mime_boundary = "mime_boundary"; - base::RunLoop run_loop; - auto upload_callback = - base::BindOnce(&IpfsNetwrokUtilsUnitTest::ValidateRequest, - base::Unretained(this), run_loop.QuitClosure()); - CreateRequestForFile(upload_file_path, blob_getter_factory(), mime_type, - filename, std::move(upload_callback), file_size); - run_loop.Run(); -} - -TEST_F(IpfsNetwrokUtilsUnitTest, CreateRequestForTextTest) { - std::string text = "test\n\rmultiline\n\rcontent"; - std::string filename = "test_name"; - std::string mime_type = "test/type"; - std::string mime_boundary = "mime_boundary"; - base::RunLoop run_loop; - auto upload_callback = - base::BindOnce(&IpfsNetwrokUtilsUnitTest::ValidateRequest, - base::Unretained(this), run_loop.QuitClosure()); - CreateRequestForText(text, filename, blob_getter_factory(), - std::move(upload_callback)); - run_loop.Run(); -} - -TEST_F(IpfsNetwrokUtilsUnitTest, CreateRequestForFolderTest) { - base::ScopedTempDir dir; - ASSERT_TRUE(dir.CreateUniqueTempDir()); - std::string content = "test\n\rmultiline\n\rcontent"; - std::string filename = "test_name"; - CreateCustomTestFile(dir.GetPath(), filename, content); - std::string mime_type = "test/type"; - std::string mime_boundary = "mime_boundary"; - base::RunLoop run_loop; - auto upload_callback = - base::BindOnce(&IpfsNetwrokUtilsUnitTest::ValidateRequest, - base::Unretained(this), run_loop.QuitClosure()); - CreateRequestForFolder(dir.GetPath(), blob_getter_factory(), - std::move(upload_callback)); - run_loop.Run(); -} - -} // namespace ipfs diff --git a/browser/ipfs/test/ipfs_not_connected_page_browsertest.cc b/browser/ipfs/test/ipfs_not_connected_page_browsertest.cc deleted file mode 100644 index 7be1595379e7..000000000000 --- a/browser/ipfs/test/ipfs_not_connected_page_browsertest.cc +++ /dev/null @@ -1,170 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include - -#include "base/memory/raw_ptr.h" -#include "base/test/scoped_feature_list.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/ipfs/features.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_not_connected_page.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/prefs/pref_service.h" -#include "components/security_interstitials/content/security_interstitial_page.h" -#include "components/security_interstitials/content/security_interstitial_tab_helper.h" -#include "components/security_interstitials/core/controller_client.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "content/public/test/test_navigation_observer.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" - -namespace { - -security_interstitials::SecurityInterstitialPage* GetCurrentInterstitial( - content::WebContents* web_contents) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - web_contents); - if (!helper) { - return nullptr; - } - return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); -} - -security_interstitials::SecurityInterstitialPage::TypeID GetInterstitialType( - content::WebContents* web_contents) { - security_interstitials::SecurityInterstitialPage* page = - GetCurrentInterstitial(web_contents); - if (!page) { - return nullptr; - } - return page->GetTypeForTesting(); -} - -void ExecuteInterstitialScript(Browser* browser, const std::string& script) { - content::WebContents* web_contents = - browser->tab_strip_model()->GetActiveWebContents(); - - EXPECT_EQ(ipfs::IPFSNotConnectedPage::kTypeForTesting, - GetInterstitialType(web_contents)); - - content::TestNavigationObserver navigation_observer(web_contents, 1); - EXPECT_TRUE(content::ExecJs(web_contents, script)); - - navigation_observer.Wait(); - - EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); -} - -} // namespace - -namespace ipfs { - -class IpfsNotConnectedPageBrowserTest : public InProcessBrowserTest { - public: - IpfsNotConnectedPageBrowserTest() { - feature_list_.InitAndEnableFeature(ipfs::features::kIpfsFeature); - } - - ~IpfsNotConnectedPageBrowserTest() override = default; - - void SetUpOnMainThread() override { - ipfs_service_ = - IpfsServiceFactory::GetInstance()->GetForContext(browser()->profile()); - ASSERT_TRUE(ipfs_service_); - ipfs_service_->SetAllowIpfsLaunchForTest(true); - - ipfs_url_ = GURL( - "http://127.0.0.1:48080/ipfs/" - "QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"); - gateway_url_ = GURL( - "https://dweb.link/ipfs/" - "QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"); - - InProcessBrowserTest::SetUpOnMainThread(); - } - - void ResetTestServer( - const net::EmbeddedTestServer::HandleRequestCallback& callback) { - test_server_ = std::make_unique( - net::test_server::EmbeddedTestServer::TYPE_HTTPS); - test_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); - test_server_->RegisterRequestHandler(callback); - ASSERT_TRUE(test_server_->Start()); - ipfs_service_->SetServerEndpointForTest(test_server_->base_url()); - } - - std::unique_ptr HandleGetEmptyConnectedPeers( - const net::test_server::HttpRequest& request) { - if (request.GetURL().path_piece() != kSwarmPeersPath) { - return nullptr; - } - - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(R"({})"); - - return http_response; - } - - IpfsService* ipfs_service() { return ipfs_service_; } - PrefService* GetPrefs() const { return browser()->profile()->GetPrefs(); } - const GURL& ipfs_url() { return ipfs_url_; } - const GURL& gateway_url() { return gateway_url_; } - - private: - std::unique_ptr test_server_; - raw_ptr ipfs_service_ = nullptr; - base::test::ScopedFeatureList feature_list_; - GURL ipfs_url_; - GURL gateway_url_; -}; - -IN_PROC_BROWSER_TEST_F(IpfsNotConnectedPageBrowserTest, - ShowAndProceedInterstitialForEmptyConnectedPeers) { - ResetTestServer(base::BindRepeating( - &IpfsNotConnectedPageBrowserTest::HandleGetEmptyConnectedPeers, - base::Unretained(this))); - - GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - // Navigate to IPFS URL and check if we'll show the interstitial when there - // are no connected peers. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(IPFSNotConnectedPage::kTypeForTesting, - GetInterstitialType(web_contents)); - EXPECT_FALSE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - - // Send Proceed command and check if we fallback to gateway and pref is set. - ExecuteInterstitialScript( - browser(), "document.querySelector('#primary-button').click();"); - EXPECT_EQ(gateway_url(), web_contents->GetURL()); - EXPECT_TRUE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - - // Navigate to that URL again and see if we auto fallback to gateway this - // time without interstitials. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(nullptr, GetInterstitialType(web_contents)); - EXPECT_EQ(gateway_url(), web_contents->GetURL()); -} - -} // namespace ipfs diff --git a/browser/ipfs/test/ipfs_onboarding_page_browsertest.cc b/browser/ipfs/test/ipfs_onboarding_page_browsertest.cc deleted file mode 100644 index fe1354047ab1..000000000000 --- a/browser/ipfs/test/ipfs_onboarding_page_browsertest.cc +++ /dev/null @@ -1,294 +0,0 @@ -/* Copyright (c) 2021 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include - -#include "base/memory/raw_ptr.h" -#include "base/test/scoped_feature_list.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/components/ipfs/features.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_onboarding_page.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/channel_info.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/prefs/pref_service.h" -#include "components/security_interstitials/content/security_interstitial_page.h" -#include "components/security_interstitials/content/security_interstitial_tab_helper.h" -#include "components/security_interstitials/core/controller_client.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "content/public/test/test_navigation_observer.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" - -namespace { - -const char kChromeIPFSSettingsURL[] = "chrome://settings/ipfs"; - -security_interstitials::SecurityInterstitialPage* GetCurrentInterstitial( - content::WebContents* web_contents) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - web_contents); - if (!helper) { - return nullptr; - } - return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); -} - -security_interstitials::SecurityInterstitialPage::TypeID GetInterstitialType( - content::WebContents* web_contents) { - security_interstitials::SecurityInterstitialPage* page = - GetCurrentInterstitial(web_contents); - if (!page) { - return nullptr; - } - return page->GetTypeForTesting(); -} - -void ExecuteInterstitialScript(Browser* browser, const std::string& script) { - content::WebContents* web_contents = - browser->tab_strip_model()->GetActiveWebContents(); - - EXPECT_EQ(ipfs::IPFSOnboardingPage::kTypeForTesting, - GetInterstitialType(web_contents)); - - content::TestNavigationObserver navigation_observer(web_contents, 1); - EXPECT_TRUE(content::ExecJs(web_contents, script)); - - navigation_observer.Wait(); - - EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents)); -} - -} // namespace - -namespace ipfs { - -class IpfsOnboardingPageBrowserTest : public InProcessBrowserTest { - public: - IpfsOnboardingPageBrowserTest() { - feature_list_.InitAndEnableFeature(ipfs::features::kIpfsFeature); - } - - ~IpfsOnboardingPageBrowserTest() override = default; - - void SetUpOnMainThread() override { - ipfs_service_ = - IpfsServiceFactory::GetInstance()->GetForContext(browser()->profile()); - ASSERT_TRUE(ipfs_service_); - ipfs_service_->SetAllowIpfsLaunchForTest(true); - - ipfs_url_ = GURL("ipfs://QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"); - - gateway_url_ = GURL( - "https://dweb.link/ipfs/" - "QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"); - - local_node_url_ = GURL( - "http://localhost:48080/ipfs/" - "QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"); - - InProcessBrowserTest::SetUpOnMainThread(); - } - - void ResetTestServer( - const net::EmbeddedTestServer::HandleRequestCallback& callback) { - test_server_ = std::make_unique( - net::test_server::EmbeddedTestServer::TYPE_HTTPS); - test_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); - test_server_->RegisterRequestHandler(callback); - ASSERT_TRUE(test_server_->Start()); - ipfs_service_->SetServerEndpointForTest(test_server_->base_url()); - } - - std::unique_ptr HandleGetConnectedPeers( - const net::test_server::HttpRequest& request) { - if (request.GetURL().path_piece() != kSwarmPeersPath) { - return nullptr; - } - - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(R"({ - "Peers": [ - { - "Addr": "/ip4/101.101.101.101/tcp/4001", - "Direction": 0, - "Peer": "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ" - }, - { - "Addr": "/ip4/102.102.102.102/tcp/4001", - "Direction": 0, - "Peer": "QmStjfkGsfQGQQm6Gdxin6DvrZsFTmTNoX5oEFMzYrc1PS" - } - ] - })"); - - return http_response; - } - - IpfsService* ipfs_service() { return ipfs_service_; } - PrefService* GetPrefs() const { return browser()->profile()->GetPrefs(); } - const GURL& ipfs_url() { return ipfs_url_; } - const GURL& gateway_url() { return gateway_url_; } - - const GURL GetResolvedNodeURL() { - GURL local_gateway = ipfs::GetDefaultIPFSLocalGateway(chrome::GetChannel()); - GURL::Replacements replacements; - replacements.SetPathStr(local_node_url_.path_piece()); - return local_gateway.ReplaceComponents(replacements); - } - - private: - std::unique_ptr test_server_; - raw_ptr ipfs_service_ = nullptr; - base::test::ScopedFeatureList feature_list_; - GURL ipfs_url_; - GURL gateway_url_; - GURL local_node_url_; -}; - -IN_PROC_BROWSER_TEST_F(IpfsOnboardingPageBrowserTest, ShowAndUseLocalNode) { - ResetTestServer(base::BindRepeating( - &IpfsOnboardingPageBrowserTest::HandleGetConnectedPeers, - base::Unretained(this))); - - GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - // Navigate to IPFS URL and check if we'll show the interstitial when there - // are no connected peers. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(IPFSOnboardingPage::kTypeForTesting, - GetInterstitialType(web_contents)); - EXPECT_FALSE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - - // Send Proceed command and check if we fallback to gateway and pref is set. - ExecuteInterstitialScript( - browser(), "document.querySelector('#local-node-button').click();"); - GURL resolved_url = GetResolvedNodeURL(); - EXPECT_EQ(resolved_url, web_contents->GetURL()); - EXPECT_EQ(GetPrefs()->GetInteger(kIPFSResolveMethod), - static_cast(IPFSResolveMethodTypes::IPFS_LOCAL)); - - // Navigate to that URL again and see if we auto fallback to gateway this - // time without interstitials. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(nullptr, GetInterstitialType(web_contents)); - EXPECT_EQ(resolved_url, web_contents->GetURL()); -} - -IN_PROC_BROWSER_TEST_F(IpfsOnboardingPageBrowserTest, ShowAndUseGateway) { - ResetTestServer(base::BindRepeating( - &IpfsOnboardingPageBrowserTest::HandleGetConnectedPeers, - base::Unretained(this))); - - GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - // Navigate to IPFS URL and check if we'll show the interstitial when there - // are no connected peers. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(IPFSOnboardingPage::kTypeForTesting, - GetInterstitialType(web_contents)); - EXPECT_FALSE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - - // Send Proceed command and check if we fallback to gateway and pref is set. - ExecuteInterstitialScript( - browser(), "document.querySelector('#public-gateway-button').click();"); - EXPECT_EQ(gateway_url(), web_contents->GetURL()); - EXPECT_EQ(GetPrefs()->GetInteger(kIPFSResolveMethod), - static_cast(IPFSResolveMethodTypes::IPFS_GATEWAY)); - - // Navigate to that URL again and see if we auto fallback to gateway this - // time without interstitials. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(nullptr, GetInterstitialType(web_contents)); - EXPECT_EQ(gateway_url(), web_contents->GetURL()); -} - -IN_PROC_BROWSER_TEST_F(IpfsOnboardingPageBrowserTest, LearnMore) { - ResetTestServer(base::BindRepeating( - &IpfsOnboardingPageBrowserTest::HandleGetConnectedPeers, - base::Unretained(this))); - - GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - // Navigate to IPFS URL and check if we'll show the interstitial when there - // are no connected peers. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(IPFSOnboardingPage::kTypeForTesting, - GetInterstitialType(web_contents)); - EXPECT_FALSE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - - // Send Proceed command and check if we fallback to gateway and pref is set. - EXPECT_TRUE(content::ExecJs( - web_contents, "document.querySelector('#learn-more').click();")); - EXPECT_EQ(GetPrefs()->GetInteger(kIPFSResolveMethod), - static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 2); - web_contents = browser()->tab_strip_model()->GetWebContentsAt(1); - EXPECT_EQ(GURL(kIPFSLearnMorePrivacyURL), web_contents->GetURL()); -} - -IN_PROC_BROWSER_TEST_F(IpfsOnboardingPageBrowserTest, OpenSettings) { - ResetTestServer(base::BindRepeating( - &IpfsOnboardingPageBrowserTest::HandleGetConnectedPeers, - base::Unretained(this))); - - GetPrefs()->SetInteger(kIPFSResolveMethod, - static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - // Navigate to IPFS URL and check if we'll show the interstitial when there - // are no connected peers. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), ipfs_url())); - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - EXPECT_TRUE(WaitForRenderFrameReady(web_contents->GetPrimaryMainFrame())); - EXPECT_EQ(IPFSOnboardingPage::kTypeForTesting, - GetInterstitialType(web_contents)); - EXPECT_FALSE(GetPrefs()->GetBoolean(kIPFSAutoFallbackToGateway)); - - // Send Proceed command and check if we fallback to gateway and pref is set. - EXPECT_TRUE(content::ExecJs( - web_contents, "document.querySelector('#open-settings').click();")); - EXPECT_EQ(GetPrefs()->GetInteger(kIPFSResolveMethod), - static_cast(IPFSResolveMethodTypes::IPFS_ASK)); - - EXPECT_EQ(browser()->tab_strip_model()->GetTabCount(), 2); - web_contents = browser()->tab_strip_model()->GetWebContentsAt(1); - EXPECT_EQ(GURL(kChromeIPFSSettingsURL), web_contents->GetURL()); -} - -} // namespace ipfs diff --git a/browser/ipfs/test/ipfs_service_browsertest.cc b/browser/ipfs/test/ipfs_service_browsertest.cc deleted file mode 100644 index ca4ad6777691..000000000000 --- a/browser/ipfs/test/ipfs_service_browsertest.cc +++ /dev/null @@ -1,1783 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include -#include -#include - -#include "base/base64.h" -#include "base/hash/hash.h" -#include "base/memory/raw_ptr.h" -#include "base/path_service.h" -#include "base/run_loop.h" -#include "base/strings/strcat.h" -#include "base/strings/stringprintf.h" -#include "base/test/bind.h" -#include "base/test/mock_callback.h" -#include "base/test/scoped_feature_list.h" -#include "brave/browser/brave_browser_process.h" -#include "brave/browser/ipfs/ipfs_blob_context_getter_factory.h" -#include "brave/browser/ipfs/ipfs_dns_resolver_impl.h" -#include "brave/browser/ipfs/ipfs_service_factory.h" -#include "brave/browser/ipfs/ipfs_service_impl_delegate.h" -#include "brave/components/constants/brave_paths.h" -#include "brave/components/ipfs/blob_context_getter_factory.h" -#include "brave/components/ipfs/brave_ipfs_client_updater.h" -#include "brave/components/ipfs/features.h" -#include "brave/components/ipfs/import/imported_data.h" -#include "brave/components/ipfs/ipfs_constants.h" -#include "brave/components/ipfs/ipfs_service.h" -#include "brave/components/ipfs/ipfs_utils.h" -#include "brave/components/ipfs/pref_names.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/net/secure_dns_config.h" -#include "chrome/browser/net/stub_resolver_config_reader.h" -#include "chrome/browser/net/system_network_context_manager.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/channel_info.h" -#include "chrome/common/pref_names.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "components/infobars/core/confirm_infobar_delegate.h" -#include "components/infobars/core/infobar.h" -#include "components/prefs/pref_service.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/network_service_instance.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "content/public/test/content_mock_cert_verifier.h" -#include "net/base/registry_controlled_domains/registry_controlled_domain.h" -#include "net/dns/mock_host_resolver.h" -#include "net/dns/public/secure_dns_mode.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" -#include "net/test/url_request/url_request_failed_job.h" - -namespace { -const char kTestLinkImportPath[] = "/link.png"; -const char kUnavailableLinkImportPath[] = "/unavailable.png"; - -std::string GetFileNameForText(const std::string& text, - const std::string& host) { - size_t key = base::FastHash(base::as_bytes(base::make_span(text))); - std::string filename = host; - filename += "_"; - filename += std::to_string(key); - return filename; -} - -class FakeIpfsService : public ipfs::IpfsService { - public: - FakeIpfsService( - PrefService* prefs, - scoped_refptr url_loader_factory, - ipfs::BlobContextGetterFactoryPtr blob_getter_factory, - ipfs::BraveIpfsClientUpdater* updater, - const base::FilePath& user_dir, - version_info::Channel channel) - : ipfs::IpfsService( - prefs, - url_loader_factory, - std::move(blob_getter_factory), - updater, - user_dir, - channel, - std::make_unique(), - std::make_unique(prefs, nullptr)) {} - ~FakeIpfsService() override = default; - - void LaunchDaemon(BoolCallback callback) override { - launched_ = true; - if (callback) { - std::move(callback).Run(launch_result_); - } - } - - void RestartDaemon() override { launched_ = true; } - - void SetLaunchResult(bool result) { launch_result_ = result; } - void SetLaunched(bool launched) { launched_ = launched; } - bool WasLaunched() { return launched_; } - - private: - bool launch_result_ = true; - bool launched_ = false; -}; - -infobars::InfoBar* FindInfobar( - infobars::ContentInfoBarManager* content_infobar_manager, - const infobars::InfoBarDelegate::InfoBarIdentifier& type) { - for (infobars::InfoBar* infobar : content_infobar_manager->infobars()) { - if (infobar->delegate()->GetIdentifier() == type) { - return infobar; - } - } - return nullptr; -} - -} // namespace - -namespace ipfs { - -class IpfsServiceBrowserTest : public InProcessBrowserTest { - public: - IpfsServiceBrowserTest() { - feature_list_.InitAndEnableFeature(ipfs::features::kIpfsFeature); - } - - ~IpfsServiceBrowserTest() override = default; - - void SetUpOnMainThread() override { - ipfs_service_ = - IpfsServiceFactory::GetInstance()->GetForContext(browser()->profile()); - ASSERT_TRUE(ipfs_service_); - ipfs_service_->SetAllowIpfsLaunchForTest(true); - mock_cert_verifier_.mock_cert_verifier()->set_default_result(net::OK); - host_resolver()->AddRule("*", "127.0.0.1"); - InProcessBrowserTest::SetUpOnMainThread(); - base::FilePath user_dir = base::FilePath(FILE_PATH_LITERAL("test")); - auto context_getter = - std::make_unique(browser()->profile()); - fake_service_ = std::make_unique( - nullptr, nullptr, std::move(context_getter), nullptr, user_dir, - chrome::GetChannel()); - } - - void ResetTestServer( - const net::EmbeddedTestServer::HandleRequestCallback& callback) { - test_server_ = std::make_unique( - net::test_server::EmbeddedTestServer::TYPE_HTTPS); - test_server_->RegisterRequestHandler(callback); - ASSERT_TRUE(test_server_->Start()); - ipfs_service_->SetServerEndpointForTest(test_server_->base_url()); - } - - void ShutDownTestServer() { - ASSERT_TRUE(test_server_->ShutdownAndWaitUntilComplete()); - } - - GURL GetURL(const std::string& host, const std::string& path) { - return test_server_->GetURL(host, path); - } - - void SetUpCommandLine(base::CommandLine* command_line) override { - InProcessBrowserTest::SetUpCommandLine(command_line); - mock_cert_verifier_.SetUpCommandLine(command_line); - } - - void SetUpInProcessBrowserTestFixture() override { - InProcessBrowserTest::SetUpInProcessBrowserTestFixture(); - mock_cert_verifier_.SetUpInProcessBrowserTestFixture(); - } - - void TearDownInProcessBrowserTestFixture() override { - mock_cert_verifier_.TearDownInProcessBrowserTestFixture(); - InProcessBrowserTest::TearDownInProcessBrowserTestFixture(); - } - - std::unique_ptr HandleGetConnectedPeers( - const net::test_server::HttpRequest& request) { - if (request.GetURL().path_piece() != kSwarmPeersPath) { - return nullptr; - } - - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(R"({ - "Peers": [ - { - "Addr": "/ip4/101.101.101.101/tcp/4001", - "Direction": 0, - "Peer": "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ" - }, - { - "Addr": "/ip4/102.102.102.102/tcp/4001", - "Direction": 0, - "Peer": "QmStjfkGsfQGQQm6Gdxin6DvrZsFTmTNoX5oEFMzYrc1PS" - } - ] - })"); - - return http_response; - } - - std::unique_ptr HandleGetAddressesConfig( - const net::test_server::HttpRequest& request) { - const GURL gurl = request.GetURL(); - std::string queryStr; - base::StrAppend(&queryStr, {kArgQueryParam, "=", kAddressesField}); - if (gurl.path_piece() != kConfigPath && gurl.query_piece() != queryStr) { - return nullptr; - } - - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(R"({ - "Key": "Addresses", - "Value": - { - "API": "/ip4/127.0.0.1/tcp/45001", - "Announce": [], - "Gateway": "/ip4/127.0.0.1/tcp/48080", - "NoAnnounce": [], - "Swarm": [ - "/ip4/0.0.0.0/tcp/4001", - "/ip6/::/tcp/4001", - "/ip4/0.0.0.0/udp/4001/quic", - "/ip6/::/udp/4001/quic" - ] - } - })"); - - return http_response; - } - - std::unique_ptr HandleGetRepoStats( - const net::test_server::HttpRequest& request) { - const GURL gurl = request.GetURL(); - std::string queryStr; - base::StrAppend(&queryStr, {kRepoStatsHumanReadableParamName, "=", - kRepoStatsHumanReadableParamValue}); - if (gurl.path_piece() != kRepoStatsPath && gurl.query_piece() != queryStr) { - return nullptr; - } - - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(R"({ - "NumObjects": 113, - "RepoPath": "/some/path/to/repo", - "RepoSize": 123456789, - "StorageMax": 9000000000, - "Version": "fs-repo@10" - })"); - - return http_response; - } - - std::unique_ptr HandleImportRequestsFail( - const net::test_server::HttpRequest& request) { - const GURL gurl = request.GetURL(); - if (gurl.path_piece() == kImportAddPath || - gurl.path_piece() == kUnavailableLinkImportPath) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_INTERNAL_SERVER_ERROR); - - return http_response; - } - - if (gurl.path_piece() == kTestLinkImportPath) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content("test"); - return http_response; - } - - return nullptr; - } - - std::unique_ptr HandlePreWarmRequest( - const net::test_server::HttpRequest& request) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - return http_response; - } - - std::unique_ptr HandleSecondImportRequests( - const std::string& expected_result, - const net::test_server::HttpRequest& request) { - const GURL gurl = request.GetURL(); - if (gurl.path_piece() == kImportAddPath) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(expected_result); - return http_response; - } - return HandleImportRequests(expected_result, request); - } - - std::unique_ptr HandleImportRequests( - const std::string& expected_response, - const net::test_server::HttpRequest& request) { - const GURL gurl = request.GetURL(); - if (gurl.path_piece() == kAPIPublishNameEndpoint) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(expected_response); - return http_response; - } - if (gurl.path_piece() == kImportAddPath) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(expected_response); - return http_response; - } - - if (gurl.path_piece() == kImportMakeDirectoryPath) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(expected_response); - return http_response; - } - - if (gurl.path_piece() == kImportCopyPath) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(expected_response); - return http_response; - } - - if (gurl.path_piece() == kTestLinkImportPath) { - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(expected_response); - return http_response; - } - - return nullptr; - } - - std::unique_ptr HandleGetNodeInfo( - const net::test_server::HttpRequest& request) { - const GURL gurl = request.GetURL(); - if (gurl.path_piece() != kNodeInfoPath) { - return nullptr; - } - - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(R"({ - "Addresses": ["111.111.111.111"], - "AgentVersion": "1.2.3.4", - "ID": "idididid", - "ProtocolVersion": "5.6.7.8", - "Protocols": ["one", "two"], - "PublicKey": "public_key" - })"); - - return http_response; - } - - std::unique_ptr HandleGarbageCollection( - const net::test_server::HttpRequest& request) { - const GURL gurl = request.GetURL(); - if (gurl.path_piece() != kGarbageCollectionPath) { - return nullptr; - } - - auto http_response = - std::make_unique(); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("application/json"); - http_response->set_content(R"({ - "Error": "", - "/": { - "Key": "{cid}" - } - })"); - - return http_response; - } - - std::unique_ptr HandleRequestServerError( - const net::test_server::HttpRequest& request) { - auto http_response = - std::make_unique(); - http_response->set_content_type("text/html"); - http_response->set_code(net::HTTP_INTERNAL_SERVER_ERROR); - return http_response; - } - - std::unique_ptr HandlePublicGatewayRequest( - const net::test_server::HttpRequest& request) { - auto http_response = - std::make_unique(); - http_response->set_content_type("text/html"); - - // IPFS gateways set this - http_response->AddCustomHeader("access-control-allow-origin", "*"); - http_response->AddCustomHeader("x-ipfs-path", "/ipfs/Qmm"); - http_response->set_code(net::HTTP_OK); - - return http_response; - } - - std::unique_ptr HandleEmbeddedSrvrRequest( - const net::test_server::HttpRequest& request) { - auto http_response = - std::make_unique(); - http_response->set_content_type("text/html"); - - // IPFS gateways set this - http_response->AddCustomHeader("access-control-allow-origin", "*"); - - std::string request_path = request.GetURL().path(); - http_response->set_code(net::HTTP_NOT_FOUND); - if (request_path == "/simple_content") { - http_response->set_content("simple content"); - http_response->set_code(net::HTTP_OK); - } else if (request_path == "/simple_content_2") { - http_response->set_content("simple content 2"); - http_response->set_code(net::HTTP_OK); - } else if (request_path == "/simple.html") { - http_response->set_content("simple.html"); - http_response->AddCustomHeader("x-ipfs-path", "/simple.html"); - http_response->set_code(net::HTTP_OK); - } else if (request_path == "/gateway_redirect") { - http_response->set_content("Welcome to IPFS :-)"); - http_response->set_code(net::HTTP_OK); - } else if (request_path == "/ipfs/bafkqae2xmvwgg33nmuqhi3zajfiemuzahiwss") { - http_response->set_content("Welcome to IPFS :-)"); - if (request.GetURL().host() == "127.0.0.1") { - http_response->set_code(net::HTTP_TEMPORARY_REDIRECT); - GURL new_location( - GetURL("bafkqae2xmvwgg33nmuqhi3zajfiemuzahiwss.ipfs.a.com", - "/gateway_redirect")); - http_response->AddCustomHeader("Location", new_location.spec()); - } - } else if (request_path == "/iframe.html") { - http_response->set_content( - "" - "" - "" - ""); - http_response->set_code(net::HTTP_OK); - } else if (request_path == - "/ipfs/" - "Qmc2JTQo4iXf24g98otZmGFQq176eQ2Cdbb88qA5ToMEvC") { - http_response->set_code(net::HTTP_TEMPORARY_REDIRECT); - GURL new_location(ipfs::GetIPFSGatewayURL( - "Qmc2JTQo4iXf24g98otZmGFQq176eQ2Cdbb88qA5ToMEvC", "simple_content", - GetDefaultIPFSGateway(browser()->profile()->GetPrefs()))); - http_response->AddCustomHeader("Location", new_location.spec()); - } else if (request_path == - "/ipfs/" - "Qmc2JTQo4iXf24g98otZmGFQq176eQ2Cdbb88qA5ToMEvC/2") { - http_response->set_code(net::HTTP_TEMPORARY_REDIRECT); - GURL new_location(ipfs::GetIPFSGatewayURL( - "Qmc2JTQo4iXf24g98otZmGFQq176eQ2Cdbb88qA5ToMEvC", "simple_content_2", - GetDefaultIPFSGateway(browser()->profile()->GetPrefs()))); - http_response->AddCustomHeader("Location", new_location.spec()); - } else if (request_path == - "/ipfs/" - "bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq") { - http_response->set_content("test content 1"); - http_response->set_code(net::HTTP_OK); - } else if (request_path == - "/ipfs/" - "dbafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq") { - http_response->set_content_type("image/png"); - std::string image; - std::string base64_image = - "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQYV2NIbbj6HwAF" - "w" - "gK6ho3LlwAAAABJRU5ErkJggg=="; - base::Base64Decode(base64_image, &image); - http_response->set_content(image); - } - - return http_response; - } - - const std::vector& GetExpectedPeers() { - static std::vector peers{ - "/ip4/101.101.101.101/tcp/4001/p2p/" - "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ", // NOLINT - "/ip4/102.102.102.102/tcp/4001/p2p/" - "QmStjfkGsfQGQQm6Gdxin6DvrZsFTmTNoX5oEFMzYrc1PS" // NOLINT - }; - return peers; - } - - const std::vector& GetExpectedSwarm() { - static std::vector swarm{ - "/ip4/0.0.0.0/tcp/4001", "/ip6/::/tcp/4001", - "/ip4/0.0.0.0/udp/4001/quic", "/ip6/::/udp/4001/quic"}; - return swarm; - } - - IpfsService* ipfs_service() { return ipfs_service_; } - - void OnGetConnectedPeersSuccess(bool success, - const std::vector& peers) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_TRUE(success); - EXPECT_EQ(peers, GetExpectedPeers()); - } - - void OnValidateGatewaySuccess(bool success) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_TRUE(success); - } - - void OnValidateGatewayFail(bool success) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_FALSE(success); - } - - void OnGetConnectedPeersFail(bool success, - const std::vector& peers) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_FALSE(success); - EXPECT_EQ(peers, std::vector{}); - } - - void OnGetConnectedPeersAfterRetry(bool success, - const std::vector& peers) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_FALSE(success); - EXPECT_EQ(peers, std::vector{}); - EXPECT_EQ(ipfs_service()->GetLastPeersRetryForTest(), 0); - } - - void OnGetAddressesConfigSuccess(bool success, - const AddressesConfig& config) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_TRUE(success); - EXPECT_EQ(config.api, "/ip4/127.0.0.1/tcp/45001"); - EXPECT_EQ(config.gateway, "/ip4/127.0.0.1/tcp/48080"); - EXPECT_EQ(config.swarm, GetExpectedSwarm()); - } - - void OnGetAddressesConfigFail(bool success, const AddressesConfig& config) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_FALSE(success); - EXPECT_EQ(config.api, ""); - EXPECT_EQ(config.gateway, ""); - EXPECT_EQ(config.swarm, std::vector{}); - } - - void OnGetRepoStatsSuccess(bool success, const RepoStats& stats) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_TRUE(success); - EXPECT_EQ(stats.objects, uint64_t(113)); - EXPECT_EQ(stats.size, uint64_t(123456789)); - EXPECT_EQ(stats.storage_max, uint64_t(9000000000)); - EXPECT_EQ(stats.path, "/some/path/to/repo"); - ASSERT_EQ(stats.version, "fs-repo@10"); - } - - void OnGetRepoStatsFail(bool success, const RepoStats& stats) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_FALSE(success); - EXPECT_EQ(stats.objects, uint64_t(0)); - EXPECT_EQ(stats.size, uint64_t(0)); - EXPECT_EQ(stats.storage_max, uint64_t(0)); - EXPECT_EQ(stats.path, ""); - ASSERT_EQ(stats.version, ""); - } - - void OnGetNodeInfoSuccess(bool success, const NodeInfo& info) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - - EXPECT_EQ(info.id, "idididid"); - ASSERT_EQ(info.version, "1.2.3.4"); - } - - void OnGetNodeInfoFail(bool success, const NodeInfo& info) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - EXPECT_EQ(info.id, ""); - ASSERT_EQ(info.version, ""); - } - - void OnGarbageCollectionSuccess(bool success, const std::string& error) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - ASSERT_TRUE(success); - EXPECT_EQ(error, ""); - } - - void OnPublishCompletedSuccess(const ipfs::ImportedData& data) { - ASSERT_FALSE(data.hash.empty()); - ASSERT_FALSE(data.filename.empty()); - ASSERT_FALSE(data.directory.empty()); - ASSERT_FALSE(data.published_key.empty()); - ASSERT_EQ(data.state, ipfs::IPFS_IMPORT_SUCCESS); - ASSERT_GT(data.size, -1); - if (wait_for_request_) { - wait_for_request_->Quit(); - } - } - - void OnImportCompletedSuccess(const ipfs::ImportedData& data) { - ASSERT_FALSE(data.hash.empty()); - ASSERT_FALSE(data.filename.empty()); - ASSERT_FALSE(data.directory.empty()); - ASSERT_TRUE(data.published_key.empty()); - ASSERT_EQ(data.state, ipfs::IPFS_IMPORT_SUCCESS); - ASSERT_GT(data.size, -1); - if (wait_for_request_) { - wait_for_request_->Quit(); - } - } - - void OnImportCompletedFail(ipfs::ImportState expected, - const std::string& expected_filename, - const ipfs::ImportedData& data) { - ASSERT_TRUE(data.hash.empty()); - EXPECT_EQ(data.filename, expected_filename); - ASSERT_TRUE(data.directory.empty()); - ASSERT_LE(data.size, -1); - ASSERT_EQ(data.state, expected); - if (wait_for_request_) { - wait_for_request_->Quit(); - } - } - - void OnGarbageCollectionFail(bool success, const std::string& error) { - if (wait_for_request_) { - wait_for_request_->Quit(); - } - ASSERT_FALSE(success); - } - - void WaitForRequest() { - if (wait_for_request_) { - return; - } - - wait_for_request_ = std::make_unique(); - wait_for_request_->Run(); - } - - FakeIpfsService* fake_ipfs_service() { return fake_service_.get(); } - - private: - content::ContentMockCertVerifier mock_cert_verifier_; - std::unique_ptr fake_service_; - std::unique_ptr wait_for_request_; - std::unique_ptr test_server_; - raw_ptr ipfs_service_ = nullptr; - base::test::ScopedFeatureList feature_list_; -}; - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, StartSuccessAndLaunch) { - auto* fake_service = fake_ipfs_service(); - fake_service->SetLaunchResult(true); - base::MockOnceCallback callback_called; - EXPECT_CALL(callback_called, Run()).Times(1); - fake_service->StartDaemonAndLaunch(callback_called.Get()); - fake_service->SetLaunchResult(false); - base::MockOnceCallback callback_not_called; - EXPECT_CALL(callback_not_called, Run()).Times(0); - fake_service->StartDaemonAndLaunch(callback_not_called.Get()); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetConnectedPeers) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleGetConnectedPeers, - base::Unretained(this))); - ipfs_service()->GetConnectedPeers( - base::BindOnce(&IpfsServiceBrowserTest::OnGetConnectedPeersSuccess, - base::Unretained(this)), - std::nullopt); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetConnectedPeersServerError) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleRequestServerError, - base::Unretained(this))); - ipfs_service()->GetConnectedPeers( - base::BindOnce(&IpfsServiceBrowserTest::OnGetConnectedPeersFail, - base::Unretained(this)), - std::nullopt); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetConnectedPeersRetry) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleRequestServerError, - base::Unretained(this))); - ipfs_service()->SetZeroPeersDeltaForTest(true); - ShutDownTestServer(); - ipfs_service()->GetConnectedPeers( - base::BindOnce(&IpfsServiceBrowserTest::OnGetConnectedPeersAfterRetry, - base::Unretained(this)), - 4); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetAddressesConfig) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleGetAddressesConfig, - base::Unretained(this))); - ipfs_service()->GetAddressesConfig( - base::BindOnce(&IpfsServiceBrowserTest::OnGetAddressesConfigSuccess, - base::Unretained(this))); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetAddressesConfigServerError) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleRequestServerError, - base::Unretained(this))); - - ipfs_service()->GetAddressesConfig( - base::BindOnce(&IpfsServiceBrowserTest::OnGetAddressesConfigFail, - base::Unretained(this))); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetRepoStatsServerSuccess) { - ResetTestServer(base::BindRepeating( - &IpfsServiceBrowserTest::HandleGetRepoStats, base::Unretained(this))); - ipfs_service()->GetRepoStats(base::BindOnce( - &IpfsServiceBrowserTest::OnGetRepoStatsSuccess, base::Unretained(this))); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetRepoStatsServerError) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleRequestServerError, - base::Unretained(this))); - - ipfs_service()->GetRepoStats(base::BindOnce( - &IpfsServiceBrowserTest::OnGetRepoStatsFail, base::Unretained(this))); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetNodeInfoServerSuccess) { - ResetTestServer(base::BindRepeating( - &IpfsServiceBrowserTest::HandleGetNodeInfo, base::Unretained(this))); - ipfs_service()->GetNodeInfo(base::BindOnce( - &IpfsServiceBrowserTest::OnGetNodeInfoSuccess, base::Unretained(this))); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, GetNodeInfoServerError) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleRequestServerError, - base::Unretained(this))); - - ipfs_service()->GetNodeInfo(base::BindOnce( - &IpfsServiceBrowserTest::OnGetNodeInfoFail, base::Unretained(this))); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, RunGarbageCollection) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleGarbageCollection, - base::Unretained(this))); - ipfs_service()->RunGarbageCollection( - base::BindOnce(&IpfsServiceBrowserTest::OnGarbageCollectionSuccess, - base::Unretained(this))); - WaitForRequest(); -} - -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, RunGarbageCollectionError) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleRequestServerError, - base::Unretained(this))); - - ipfs_service()->RunGarbageCollection( - base::BindOnce(&IpfsServiceBrowserTest::OnGarbageCollectionFail, - base::Unretained(this))); - WaitForRequest(); -} - -// Make sure an ipfs:// window.fetch does not work within the http:// scheme -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, - CannotFetchIPFSResourcesFromHTTP) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleEmbeddedSrvrRequest, - base::Unretained(this))); - SetIPFSDefaultGatewayForTest(GetURL("a.com", "/")); - ASSERT_TRUE( - ui_test_utils::NavigateToURL(browser(), GetURL("b.com", "/simple.html"))); - content::WebContents* contents = - browser()->tab_strip_model()->GetActiveWebContents(); - auto error_caught = EvalJs(contents, R"( - new Promise(resolve => { - fetch('ipfs://Qmc2JTQo4iXf24g98otZmGFQq176eQ2Cdbb88qA5ToMEvC/2') - .catch((e) => { - resolve(true); - }); - }); - )"); - ASSERT_TRUE(error_caught.error.empty()); - EXPECT_EQ(base::Value(true), error_caught.value); -} - -// Make sure an window.fetch works within the ipfs:// scheme -IN_PROC_BROWSER_TEST_F(IpfsServiceBrowserTest, CanFetchIPFSResourcesFromIPFS) { - ResetTestServer( - base::BindRepeating(&IpfsServiceBrowserTest::HandleEmbeddedSrvrRequest, - base::Unretained(this))); - SetIPFSDefaultGatewayForTest(GetURL("dweb.link", "/")); - browser()->profile()->GetPrefs()->SetInteger( - kIPFSResolveMethod, - static_cast(ipfs::IPFSResolveMethodTypes::IPFS_GATEWAY)); - - GURL url("ipfs://Qmc2JTQo4iXf24g98otZmGFQq176eQ2Cdbb88qA5ToMEvC"); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); - content::WebContents* contents = - browser()->tab_strip_model()->GetActiveWebContents(); - auto got_fetch = EvalJs(contents, R"( - new Promise(resolve => { - fetch('ipfs://Qmc2JTQo4iXf24g98otZmGFQq176eQ2Cdbb88qA5ToMEvC/2') - .then(response => { response.text() - .then((response_text) => { - const result = response_text == 'simple content 2'; - resolve(result); - })}) - .catch((x) => console.log('error: ' + x)); - }); - )"); - ASSERT_TRUE(got_fetch.error.empty()); - EXPECT_EQ(base::Value(true), got_fetch.value); -} - -// Make sure an - diff --git a/utility/brave_content_utility_client.cc b/utility/brave_content_utility_client.cc index ffdbd6125551..0116d8b30eb3 100644 --- a/utility/brave_content_utility_client.cc +++ b/utility/brave_content_utility_client.cc @@ -8,7 +8,6 @@ #include #include -#include "brave/components/ipfs/buildflags/buildflags.h" #include "brave/components/services/bat_ads/bat_ads_service_impl.h" #include "brave/components/services/bat_ads/public/interfaces/bat_ads.mojom.h" #include "brave/components/services/bat_rewards/public/interfaces/rewards_engine_factory.mojom.h" @@ -20,11 +19,6 @@ #include "brave/utility/importer/brave_profile_import_impl.h" #endif -#if BUILDFLAG(ENABLE_IPFS) -#include "brave/components/services/ipfs/ipfs_service_impl.h" -#include "brave/components/services/ipfs/public/mojom/ipfs_service.mojom.h" -#endif - #if BUILDFLAG(ENABLE_TOR) #include "brave/components/services/tor/public/interfaces/tor.mojom.h" #include "brave/components/services/tor/tor_launcher_impl.h" @@ -42,12 +36,6 @@ auto RunBraveProfileImporter( } #endif -#if BUILDFLAG(ENABLE_IPFS) -auto RunIpfsService(mojo::PendingReceiver receiver) { - return std::make_unique(std::move(receiver)); -} -#endif - #if BUILDFLAG(ENABLE_TOR) auto RunTorLauncher(mojo::PendingReceiver receiver) { return std::make_unique(std::move(receiver)); @@ -84,10 +72,6 @@ void BraveContentUtilityClient::RegisterMainThreadServices( services.Add(RunBraveProfileImporter); #endif -#if BUILDFLAG(ENABLE_IPFS) - services.Add(RunIpfsService); -#endif - #if BUILDFLAG(ENABLE_TOR) services.Add(RunTorLauncher); #endif diff --git a/utility/importer/sources.gni b/utility/importer/sources.gni index 2487c8d86ff8..78c8d90017a9 100644 --- a/utility/importer/sources.gni +++ b/utility/importer/sources.gni @@ -3,7 +3,6 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//brave/components/tor/buildflags/buildflags.gni") brave_utility_importer_sources = [] @@ -38,7 +37,3 @@ if (!is_android) { if (enable_tor) { brave_utility_importer_deps += [ "//brave/components/services/tor" ] } - -if (enable_ipfs) { - brave_utility_importer_deps += [ "//brave/components/services/ipfs" ] -} diff --git a/utility/sources.gni b/utility/sources.gni index fe4177bd0aaa..c3f52bb317ef 100644 --- a/utility/sources.gni +++ b/utility/sources.gni @@ -3,7 +3,6 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. -import("//brave/components/ipfs/buildflags/buildflags.gni") import("//brave/components/tor/buildflags/buildflags.gni") import("//brave/utility/importer/sources.gni") @@ -22,7 +21,6 @@ if (is_android) { brave_utility_sources += brave_utility_importer_sources brave_utility_deps = [ - "//brave/components/ipfs/buildflags", "//brave/components/services/bat_ads:lib", "//brave/components/services/bat_ads/public/interfaces", "//brave/components/services/bat_rewards:lib", @@ -35,13 +33,6 @@ brave_utility_deps = [ brave_utility_deps += brave_utility_importer_deps -if (enable_ipfs) { - brave_utility_deps += [ - "//brave/components/services/ipfs", - "//brave/components/services/ipfs/public/mojom", - ] -} - if (enable_tor) { brave_utility_deps += [ "//brave/components/services/tor",