|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'json' |
| 4 | +require 'net/http' |
| 5 | + |
| 6 | +module Ssg |
| 7 | + # Downloads SCAP datastreams from the SCAP Security Guide |
| 8 | + # https://github.com/ComplianceAsCode/content |
| 9 | + class Downloader |
| 10 | + RELEASES_API = 'https://api.github.com/repos'\ |
| 11 | + '/ComplianceAsCode/content/releases/' |
| 12 | + SSG_DS_REGEX = /scap-security-guide-(\d+\.)+zip$/ |
| 13 | + |
| 14 | + def initialize(version = 'latest') |
| 15 | + @release_uri = URI( |
| 16 | + "#{RELEASES_API}#{'tags/' unless version[/^latest$/]}#{version}" |
| 17 | + ) |
| 18 | + end |
| 19 | + |
| 20 | + def self.download!(versions = []) |
| 21 | + versions.uniq.map do |version| |
| 22 | + [version, new(version).fetch_datastream_file] |
| 23 | + end.to_h |
| 24 | + end |
| 25 | + |
| 26 | + def fetch_datastream_file |
| 27 | + puts "Fetching #{datastream_filename}" |
| 28 | + get_chunked(datastream_uri) |
| 29 | + |
| 30 | + datastream_filename |
| 31 | + end |
| 32 | + |
| 33 | + private |
| 34 | + |
| 35 | + def datastream_uri |
| 36 | + @datastream_uri ||= URI( |
| 37 | + download_urls.find { |url| url[SSG_DS_REGEX] } |
| 38 | + ) |
| 39 | + end |
| 40 | + |
| 41 | + def download_urls |
| 42 | + get_json(@release_uri).dig('assets').map do |asset| |
| 43 | + asset.dig('browser_download_url') |
| 44 | + end |
| 45 | + end |
| 46 | + |
| 47 | + def fetch(request, &block) |
| 48 | + Net::HTTP.start( |
| 49 | + request.uri.host, request.uri.port, |
| 50 | + use_ssl: request.uri.scheme['https'] |
| 51 | + ) do |http| |
| 52 | + check_response(http.request(request, &block), &block) |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + def get(uri, &block) |
| 57 | + fetch(Net::HTTP::Get.new(uri), &block) |
| 58 | + end |
| 59 | + |
| 60 | + def head(uri, &block) |
| 61 | + fetch(Net::HTTP::Head.new(uri), &block) |
| 62 | + end |
| 63 | + |
| 64 | + def check_response(response, &block) |
| 65 | + case response |
| 66 | + when Net::HTTPSuccess |
| 67 | + response |
| 68 | + when Net::HTTPRedirection |
| 69 | + get(URI(response['location']), &block) |
| 70 | + else |
| 71 | + response.value |
| 72 | + end |
| 73 | + end |
| 74 | + |
| 75 | + def get_chunked(uri, filename: datastream_filename) |
| 76 | + head(uri) do |response| |
| 77 | + next unless Net::HTTPSuccess === response |
| 78 | + open(filename, 'wb') do |file| |
| 79 | + response.read_body do |chunk| |
| 80 | + file.write(chunk) |
| 81 | + end |
| 82 | + end |
| 83 | + end |
| 84 | + end |
| 85 | + |
| 86 | + def datastream_filename |
| 87 | + datastream_uri.path.split('/').last[SSG_DS_REGEX] |
| 88 | + end |
| 89 | + |
| 90 | + def get_json(uri) |
| 91 | + JSON.parse(get(uri).body) |
| 92 | + end |
| 93 | + end |
| 94 | +end |
0 commit comments