Class: Hiera::Backend::Housekeeper_backend

Inherits:
Object
  • Object
show all
Defined in:
lib/hiera/backend/housekeeper_backend.rb

Instance Method Summary collapse

Constructor Details

#initializeHousekeeper_backend

Returns a new instance of Housekeeper_backend.



30
31
32
33
34
35
# File 'lib/hiera/backend/housekeeper_backend.rb', line 30

def initialize
    require 'gpgme'
    @data  = Hash.new
    @cache = Hash.new
    debug("Loaded housekeeper_backend")
end

Instance Method Details

#debug(msg) ⇒ Object



37
38
39
# File 'lib/hiera/backend/housekeeper_backend.rb', line 37

def debug (msg)
    Hiera.debug("[housekeeper_backend]: #{msg}")
end

#decrypt(cipher, gnupghome) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/hiera/backend/housekeeper_backend.rb', line 134

def decrypt(cipher, gnupghome)
    gnupghome_backup = ENV["GNUPGHOME"]
    ENV["GNUPGHOME"] = gnupghome
    debug("GNUPGHOME is #{ENV['GNUPGHOME']}")

    # https://github.com/ueno/ruby-gpgme/issues/31
    GPGME::gpgme_set_engine_info(GPGME::PROTOCOL_OpenPGP, '/usr/bin/gpg', nil)
    ctx = GPGME::Ctx.new({:passphrase_callback => method(:passfunc)})

    if !ctx.keys.empty?
        raw = GPGME::Data.new(cipher)
        txt = GPGME::Data.new

        begin
            txt = ctx.decrypt(raw)
        rescue GPGME::Error::DecryptFailed
            warn("Warning: GPG Decryption failed, check your GPG settings")
        rescue Exception => e
            warn("Warning: General exception decrypting GPG file : #{e.message}")
        ensure
            ENV["GNUPGHOME"] = gnupghome_backup
        end

        txt.seek 0
        result = txt.read

        debug("result is a #{result.class} ctx #{ctx} txt #{txt}")
        return result
    else
        warn("No usable keys found in #{gnupghome}. Check :key_dir value in hiera.yaml is correct")
        nil
    end
end

#lookup(key, scope, order_override, resolution_type) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/hiera/backend/housekeeper_backend.rb', line 46

def lookup(key, scope, order_override, resolution_type)

    debug("Lookup called, key #{key} resolution type is #{resolution_type}")
    answer = nil

    # This should compute ~ on both *nix and *doze
    homes = ["HOME", "HOMEPATH"]
    real_home = homes.detect { |h| ENV[h] != nil }

    key_dir = Backend.parse_string(Config[:gpg][:key_dir], scope) || "#{ENV[real_home]}/.gnupg"
    fqdn    = Socket.gethostbyname(Socket.gethostname).first
    housekeeper_server = Backend.parse_string(Config[:housekeeper][:url], scope)
    housekeeper_keyname = Backend.parse_string(Config[:housekeeper][:keyname], scope) || "housekeeper"
    housekeeper_branch = Backend.parse_string(Config[:housekeeper][:branch], scope) || "master"
    housekeeper_identity = "#{housekeeper_keyname}@#{fqdn}"
    # Unfortunately the way the callback function works means we can only get this into the passphrase
    # method by using an instance variable or by modifying gpgme. I chose the former.
    @housekeeper_keypass = Backend.parse_string(Config[:housekeeper][:keypass], scope) || "housekeeper_bgch"

    Backend.datasources(scope, order_override) do |source|
        gpgfile = HouseKeeperCache.lookup(housekeeper_server, housekeeper_identity, housekeeper_branch, source)

        next if gpgfile == :next

        unless @data.has_key?(gpgfile)
            plain = decrypt(gpgfile, key_dir)

            next if !plain
            next if !plain.kind_of?(String)
            next if plain.empty?
            debug("GPG decrypt returned valid data")

            begin
                @data[gpgfile] = YAML.load(plain)
            rescue
                warn("YAML decoding data in #{gpgfile} failed")
                @data[gpgfile] = {}
            end
        end

        data = @data[gpgfile]
        next if !data
        next if data.empty?
        debug("Data contains valid YAML")

        next unless data.include?(key)
        debug("Key #{key} found in YAML document, Passing answer to hiera")

        parsed_answer = Backend.parse_answer(data[key], scope)

        begin
            case resolution_type
            when :array
                debug("Appending answer array")
                raise Exception, "Hiera type mismatch: expected Array and got #{parsed_answer.class}" unless parsed_answer.kind_of? Array or parsed_answer.kind_of? String
                answer ||= []
                answer << parsed_answer
            when :hash
                debug("Merging answer hash")
                raise Exception, "Hiera type mismatch: expected Hash and got #{parsed_answer.class}" unless parsed_answer.kind_of? Hash
                answer ||= {}
                answer = parsed_answer.merge answer
            else
                debug("Assigning answer variable")
                answer = parsed_answer
                break
            end
        rescue NoMethodError
            raise Exception, "Resolution type is #{resolution_type} but parsed_answer is a #{parsed_answer.class}"
        end

    end
    return answer
end

#passfunc(hook, uid_hint, passphrase_info, prev_was_bad, fd) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/hiera/backend/housekeeper_backend.rb', line 121

def passfunc(hook, uid_hint, passphrase_info, prev_was_bad, fd)
 begin
   system('stty -echo')
   io = IO.for_fd(fd, 'w')
   io.puts("housekeeper_bgch")
   io.flush
 ensure
   (0 ... $_.length).each do |i| $_[i] = ?0 end if $_
   system('stty echo')
 end
 $stderr.puts
end

#stale?(gpgfile) ⇒ Boolean

Returns:

  • (Boolean)


168
169
170
171
172
173
174
175
176
177
178
# File 'lib/hiera/backend/housekeeper_backend.rb', line 168

def stale?(gpgfile)
    # NOTE: The mtime change in a file MUST be > 1 second before being
    #       recognized as stale. File mtime changes within 1 second will
    #       not be recognized.
    stat    = File.stat(gpgfile)
    current = { 'inode' => stat.ino, 'mtime' => stat.mtime, 'size' => stat.size }
    return false if @cache[gpgfile] == current

    @cache[gpgfile] = current
    return true
end

#warn(msg) ⇒ Object



41
42
43
# File 'lib/hiera/backend/housekeeper_backend.rb', line 41

def warn (msg)
    Hiera.warn("[housekeeper_backend]:  #{msg}")
end