Sha256: 011b5bbe68ede93cac132770fd1e06e2178d44d638d973b0ceb76c5e45f58e3c

Contents?: true

Size: 1.93 KB

Versions: 4

Compression:

Stored size: 1.93 KB

Contents

require 'front_end_builds/utils/ssh_pubkey_convert'
require 'base64'
require 'openssl'

module FrontEndBuilds
  class Pubkey < ActiveRecord::Base
    if defined?(ProtectedAttributes) || ::ActiveRecord::VERSION::MAJOR < 4
      attr_accessible :name,
                      :pubkey
    end

    validates :name, presence: true
    validates :pubkey, presence: true

    has_many :builds, class_name: "FrontEndBuilds::Build"

    def fingerprint
      content = pubkey.split(/\s/)[1]

      if content
        Digest::MD5.hexdigest(Base64.decode64(content))
          .scan(/.{1,2}/)
          .join(":")
      else
        'Unknown'
      end
    end

    def ssh_pubkey?
      (type, b64, _) = pubkey.split(/\s/)
      %w{ssh-rsa ssh-dss}.include?(type) && b64.present?
    end

    # Public: In order to verify a signature we need the key to be an OpenSSL
    # RSA PKey and not a string that you would find in an ssh pubkey key. Most
    # people are going to be adding ssh public keys to their build system, this
    # method will covert them to OpenSSL RSA if needed.
    def to_rsa_pkey
      FrontEndBuilds::Utils::SSHPubKeyConvert
        .convert(pubkey)
    end

    # Public: Will verify that the sigurate has access to deploy the build
    # object. The signature includes the endpoint and app name.
    #
    # Returns boolean
    def verify(build)
      # TODO might as well cache this and store in the db so we dont have to
      # convert every time
      pkey = to_rsa_pkey
      signature = Base64.decode64(build.signature)
      digest = OpenSSL::Digest::SHA256.new
      expected = "#{build.app.name}-#{build.endpoint}"

      pkey.verify(digest, signature, expected)
    end

    def last_build
      builds
        .order('created_at desc')
        .limit(1)
        .first
    end

    def serialize
      {
        id: id,
        name: name,
        fingerprint: fingerprint,
        lastUsedAt: last_build.try(:created_at)
      }
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
front_end_builds-0.1.3 app/models/front_end_builds/pubkey.rb
front_end_builds-0.1.2 app/models/front_end_builds/pubkey.rb
front_end_builds-0.1.1 app/models/front_end_builds/pubkey.rb
front_end_builds-0.1.0 app/models/front_end_builds/pubkey.rb