]> git.openstreetmap.org Git - rails.git/blob - lib/osm_community_index/resource_backend.rb
Add frozen_string_literal comments to ruby files
[rails.git] / lib / osm_community_index / resource_backend.rb
1 # frozen_string_literal: true
2
3 # A backend for FrozenRecord
4
5 module OsmCommunityIndex
6   module ResourceBackend
7     def self.filename(_model)
8       "resources.json"
9     end
10
11     def self.load(file_path)
12       resources = JSON.parse(File.read(file_path))
13       resources["resources"].values.map! do |v|
14         v["strings"]["url"] = nil unless valid_url? v["strings"]["url"]
15       end
16       resources["resources"].values
17     end
18
19     # This is to avoid any problems if upstream contains urls with `script:` or
20     # similar schemes, i.e. to guard against supply-chain attacks.
21     # Unfortunately the validates_url gem doesn't support `mailto:` or similar
22     # urls. This method is based on their approach to validation.
23     def self.valid_url?(url)
24       return true if url.nil?
25
26       schemes = %w[http https mailto xmpp]
27       uri = URI.parse(url)
28       scheme = uri&.scheme
29
30       valid_raw_url = scheme && url =~ /\A#{URI::DEFAULT_PARSER.make_regexp([scheme])}\z/
31       valid_scheme = scheme && schemes.include?(scheme)
32       return true if valid_raw_url && valid_scheme
33
34       false
35     rescue URI::InvalidURIError, URI::InvalidComponentError
36       false
37     end
38   end
39 end