diff --git a/lib/travis/api/v3/github.rb b/lib/travis/api/v3/github.rb index 9ec3f6fc..cb9c389c 100644 --- a/lib/travis/api/v3/github.rb +++ b/lib/travis/api/v3/github.rb @@ -49,5 +49,15 @@ module Travis::API::V3 gh.post(hooks_url, payload) end end + + def upload_key(repository) + keys_path = "repos/#{repository.slug}/keys" + key = gh[keys_path]. + detect { |e| e['key'] == repository.key.encoded_public_key } + + unless key + gh.post keys_path, title: Travis.config.host.to_s, key: repository.key.encoded_public_key + end + end end end diff --git a/lib/travis/api/v3/models/repository.rb b/lib/travis/api/v3/models/repository.rb index b462db88..420a1cb0 100644 --- a/lib/travis/api/v3/models/repository.rb +++ b/lib/travis/api/v3/models/repository.rb @@ -12,6 +12,7 @@ module Travis::API::V3 belongs_to :last_build, class_name: 'Travis::API::V3::Models::Build'.freeze belongs_to :current_build, class_name: 'Travis::API::V3::Models::Build'.freeze + has_one :key, class_name: 'Travis::API::V3::Models::SSLKey'.freeze has_one :default_branch, foreign_key: [:repository_id, :name], primary_key: [:id, :default_branch], diff --git a/lib/travis/api/v3/models/ssl_key.rb b/lib/travis/api/v3/models/ssl_key.rb index eb45758c..75e1e8a2 100644 --- a/lib/travis/api/v3/models/ssl_key.rb +++ b/lib/travis/api/v3/models/ssl_key.rb @@ -1,5 +1,29 @@ module Travis::API::V3 class Models::SSLKey < Model belongs_to :repository + + serialize :private_key, Travis::API::V3::Extensions::EncryptedColumn.new + + def encoded_public_key + key = build_key.public_key + ['ssh-rsa ', "\0\0\0\assh-rsa#{sized_bytes(key.e)}#{sized_bytes(key.n)}"].pack('a*m').gsub("\n", '') + end + + private + + def build_key + @build_key ||= OpenSSL::PKey::RSA.new(private_key) + end + + def sized_bytes(value) + bytes = to_byte_array(value.to_i) + [bytes.size, *bytes].pack('NC*') + end + + def to_byte_array(num, *significant) + return significant if num.between?(-1, 0) and significant[0][7] == num[7] + to_byte_array(*num.divmod(256)) + significant + end + end end diff --git a/lib/travis/api/v3/services/repository/enable.rb b/lib/travis/api/v3/services/repository/enable.rb index 5d43bbe7..d27d73f5 100644 --- a/lib/travis/api/v3/services/repository/enable.rb +++ b/lib/travis/api/v3/services/repository/enable.rb @@ -1,7 +1,14 @@ module Travis::API::V3 class Services::Repository::Enable < Services::Repository::Disable def run! - super(true) + repository = super(true) + + if repository.private? + admin = access_control.admin_for(repository) + github(admin).upload_key(repository) + end + + repository end def check_access(repository)