diff --git a/lib/puppet/provider/user/directoryservice.rb b/lib/puppet/provider/user/directoryservice.rb index a2c561039..767f561f4 100644 --- a/lib/puppet/provider/user/directoryservice.rb +++ b/lib/puppet/provider/user/directoryservice.rb @@ -1,86 +1,621 @@ -require 'puppet/provider/nameservice/directoryservice' +require 'puppet' +require 'facter/util/plist' +require 'base64' -Puppet::Type.type(:user).provide :directoryservice, :parent => Puppet::Provider::NameService::DirectoryService do - desc "User management using DirectoryService on OS X." +Puppet::Type.type(:user).provide :directoryservice do + desc "User management on OS X." - commands :dscl => "/usr/bin/dscl" - confine :operatingsystem => :darwin +## ## +## Provider Settings ## +## ## + + # Provider command declarations + commands :uuidgen => '/usr/bin/uuidgen' + commands :dsimport => '/usr/bin/dsimport' + commands :dscl => '/usr/bin/dscl' + commands :plutil => '/usr/bin/plutil' + commands :dscacheutil => '/usr/bin/dscacheutil' + + # Provider confines and defaults + confine :operatingsystem => :darwin defaultfor :operatingsystem => :darwin - # JJM: DirectoryService can manage passwords. - # This needs to be a special option to dscl though (-passwd) + # Need this to create getter/setter methods automagically + # This command creates methods that return @property_hash[:value] + mk_resource_methods + + # JJM: OS X can manage passwords. has_feature :manages_passwords - # JJM: comment matches up with the /etc/passwd concept of an user - options :comment, :key => "realname" - options :password, :key => "passwd" +## ## +## Class Methods ## +## ## - autogen_defaults :home => "/var/empty", :shell => "/usr/bin/false" + def self.ds_to_ns_attribute_map + # This method exists to map the dscl values to the correct Puppet + # properties. This stays relatively consistent, but who knows what + # Apple will do next year... + { + 'RecordName' => :name, + 'PrimaryGroupID' => :gid, + 'NFSHomeDirectory' => :home, + 'UserShell' => :shell, + 'UniqueID' => :uid, + 'RealName' => :comment, + 'Password' => :password, + 'GeneratedUID' => :guid, + 'IPAddress' => :ip_address, + 'ENetAddress' => :en_address, + 'GroupMembership' => :members, + } + end - verify :gid, "GID must be an integer" do |value| - value.is_a? Integer + def self.ns_to_ds_attribute_map + @ns_to_ds_attribute_map ||= ds_to_ns_attribute_map.invert end - verify :uid, "UID must be an integer" do |value| - value.is_a? Integer + def self.prefetch(resources) + # Prefetching is necessary to use @property_hash inside any setter methods. + # self.prefetch uses self.instances to gather an array of user instances + # on the system, and then populates the @property_hash instance variable + # with attribute data for the specific instance in question (i.e. it + # gathers the 'is' values of the resource into the @property_hash instance + # variable so you don't have to read from the system every time you need + # to gather the 'is' values for a resource. The downside here is that + # populating this instance variable for every resource on the system + # takes time and front-loads your Puppet run. + instances.each do |prov| + if resource = resources[prov.name] + resource.provider = prov + end + end end - def autogen_comment - @resource[:name].capitalize + def self.instances + # This method assembles an array of provider instances containing + # information about every instance of the user type on the system (i.e. + # every user and its attributes). The `puppet resource` command relies + # on self.instances to gather an array of user instances in order to + # display its output. + get_all_users.collect do |user| + self.new(generate_attribute_hash(user)) + end end - # The list of all groups the user is a member of. - # JJM: FIXME: Override this method... - def groups - groups = [] - groups.join(",") + def self.get_all_users + # Return an array of hashes containing information about every user on + # the system. + Plist.parse_xml(dscl '-plist', '.', 'readall', '/Users') end - # This is really lame. We have to iterate over each - # of the groups and add us to them. - def groups=(groups) - # case groups - # when Fixnum - # groups = [groups.to_s] - # when String - # groups = groups.split(/\s*,\s*/) - # else - # raise Puppet::DevError, "got invalid groups value #{groups.class} of type #{groups}" - # end - # # Get just the groups we need to modify - # diff = groups - (@is || []) - # - # data = {} - # open("| #{command(:nireport)} / /groups name users") do |file| - # file.each do |line| - # name, members = line.split(/\s+/) - # - # if members.nil? or members =~ /NoValue/ - # data[name] = [] - # else - # # Add each diff group's current members - # data[name] = members.split(/,/) - # end - # end - # end + def self.generate_attribute_hash(input_hash) + # This method accepts an individual user plist, passed as a hash, and + # strips the dsAttrTypeStandard: prefix that dscl adds for each key. + # An attribute hash is assembled and returned from the properties + # supported by the user type. + attribute_hash = {} + input_hash.keys.each do |key| + ds_attribute = key.sub("dsAttrTypeStandard:", "") + next unless ds_to_ns_attribute_map.keys.include?(ds_attribute) + ds_value = input_hash[key] + case ds_to_ns_attribute_map[ds_attribute] + when :gid, :uid + # OS X stores objects like uid/gid as strings. + # Try casting to an integer for these cases to be + # consistent with the other providers and the group type + # validation + begin + ds_value = Integer(ds_value[0]) + rescue ArgumentError + ds_value = ds_value[0] + end + else ds_value = ds_value[0] + end + attribute_hash[ds_to_ns_attribute_map[ds_attribute]] = ds_value + end + attribute_hash[:ensure] = :present + attribute_hash[:provider] = :directoryservice + attribute_hash[:shadowhashdata] = get_attribute_from_dscl('Users', attribute_hash[:name], 'ShadowHashData') + + ############## + # Get Groups # + ############## + groups_array = [] + get_list_of_groups.each do |group| + if group["dsAttrTypeStandard:GroupMembership"] and group["dsAttrTypeStandard:GroupMembership"].include?(attribute_hash[:name]) + groups_array << group["dsAttrTypeStandard:RecordName"][0] + end + + if group["dsAttrTypeStandard:GroupMembers"] and group["dsAttrTypeStandard:GroupMembers"].include?(attribute_hash[:guid]) + groups_array << group["dsAttrTypeStandard:RecordName"][0] + end + end + attribute_hash[:groups] = groups_array.uniq.sort.join(',') + + ################################ + # Get Password/Salt/Iterations # + ################################ + if (Puppet::Util::Package.versioncmp(Facter.value(:macosx_productversion_major), '10.7') == -1) + attribute_hash[:password] = get_sha1(attribute_hash[:guid]) + else + if attribute_hash[:shadowhashdata].empty? + attribute_hash[:password] = '*' + else + embedded_binary_plist = get_embedded_binary_plist(attribute_hash[:shadowhashdata]) + if embedded_binary_plist['SALTED-SHA512'] + attribute_hash[:password] = get_salted_sha512(embedded_binary_plist) + else + attribute_hash[:password] = get_salted_sha512_pbkdf2('entropy', embedded_binary_plist) + attribute_hash[:salt] = get_salted_sha512_pbkdf2('salt', embedded_binary_plist) + attribute_hash[:iterations] = get_salted_sha512_pbkdf2('iterations', embedded_binary_plist) + end + end + end + + attribute_hash + end + + def self.get_list_of_groups + # Use dscl to retrieve an array of hashes containing attributes about all + # of the local groups on the machine. + @groups ||= Plist.parse_xml(dscl '-plist', '.', 'readall', '/Groups') + end + + def self.get_attribute_from_dscl(path, username, keyname) + # Perform a dscl lookup at the path specified for the specific keyname + # value. The value returned is the first item within the array returned + # from dscl + Plist.parse_xml(dscl '-plist', '.', 'read', "/#{path}/#{username}", keyname) + end + + def self.get_embedded_binary_plist(shadow_hash_data) + # The plist embedded in the ShadowHashData key is a binary plist. The + # facter/util/plist library doesn't read binary plists, so we need to + # extract the binary plist, convert it to XML, and return it. + embedded_binary_plist = Array(shadow_hash_data['dsAttrTypeNative:ShadowHashData'][0].delete(' ')).pack('H*') + convert_binary_to_xml(embedded_binary_plist) + end + + def self.convert_xml_to_binary(plist_data) + # This method will accept a hash that has been returned from Plist::parse_xml + # and convert it to a binary plist (string value). + Puppet.debug('Converting XML plist to binary') + Puppet.debug('Executing: \'plutil -convert binary1 -o - -\'') + IO.popen('plutil -convert binary1 -o - -', mode='r+') do |io| + io.write Plist::Emit.dump(plist_data) + io.close_write + @converted_plist = io.read + end + @converted_plist + end + + def self.convert_binary_to_xml(plist_data) + # This method will accept a binary plist (as a string) and convert it to a + # hash via Plist::parse_xml. + Puppet.debug('Converting binary plist to XML') + Puppet.debug('Executing: \'plutil -convert xml1 -o - -\'') + IO.popen('plutil -convert xml1 -o - -', mode='r+') do |io| + io.write plist_data + io.close_write + @converted_plist = io.read + end + Puppet.debug('Converting XML values to a hash.') + Plist::parse_xml(@converted_plist) + end + + def self.get_salted_sha512(embedded_binary_plist) + # The salted-SHA512 password hash in 10.7 is stored in the 'SALTED-SHA512' + # key as binary data. That data is extracted and converted to a hex string. + embedded_binary_plist['SALTED-SHA512'].string.unpack("H*")[0] + end + + def self.get_salted_sha512_pbkdf2(field, embedded_binary_plist) + # This method reads the passed embedded_binary_plist hash and returns values + # according to which field is passed. Arguments passed are the hash + # containing the value read from the 'ShadowHashData' key in the User's + # plist, and the field to be read (one of 'entropy', 'salt', or 'iterations') + case field + when 'salt', 'entropy' + embedded_binary_plist['SALTED-SHA512-PBKDF2'][field].string.unpack('H*').first + when 'iterations' + Integer(embedded_binary_plist['SALTED-SHA512-PBKDF2'][field]) + else + raise Puppet::Error, 'Puppet has tried to read an incorrect value from the ' + + "SALTED-SHA512-PBKDF2 hash. Acceptable fields are 'salt', " + + "'entropy', or 'iterations'." + end + end + + def self.get_sha1(guid) + # In versions 10.5 and 10.6 of OS X, the password hash is stored in a file + # in the /var/db/shadow/hash directory that matches the GUID of the user. + password_hash = nil + password_hash_file = "#{password_hash_dir}/#{guid}" + if File.exists?(password_hash_file) and File.file?(password_hash_file) + raise Puppet::Error, "Could not read password hash file at #{password_hash_file}" if not File.readable?(password_hash_file) + f = File.new(password_hash_file) + password_hash = f.read + f.close + end + password_hash + end + + +## ## +## Ensurable Methods ## +## ## + + def exists? + begin + dscl '.', 'read', "/Users/#{@resource.name}" + rescue Puppet::ExecutionFailure => e + Puppet.debug("User was not found, dscl returned: #{e.inspect}") + return false + end + true + end + + def create + # This method is called if ensure => present is passed and the exists? + # method returns false. Dscl will directly set most values, but the + # setter methods will be used for any exceptions. + create_new_user(@resource.name) + + # Retrieve the user's GUID + @guid = self.class.get_attribute_from_dscl('Users', @resource.name, 'GeneratedUID')['dsAttrTypeStandard:GeneratedUID'][0] + + # Get an array of valid User type properties + valid_properties = Puppet::Type.type('User').validproperties + + # Iterate through valid User type properties + valid_properties.each do |attribute| + next if attribute == :ensure + value = @resource.should(attribute) + + # Value defaults + if value.nil? + value = case attribute + when :gid + '20' + when :uid + next_system_id + when :comment + @resource.name + when :shell + '/bin/bash' + when :home + "/Users/#{@resource.name}" + else + nil + end + end + + # If a non-numerical gid value is passed, assume it is a group name and + # lookup that group's GID value to use when setting the GID + if (attribute == :gid) and value.class == 'Fixnum' + value = self.class.get_attribute_from_dscl('Groups', value, 'PrimaryGroupID')['dsAttrTypeStandard:PrimaryGroupID'][0] + end + + ## Set values ## + # For the :password and :groups properties, call the setter methods + # to enforce those values. For everything else, use dscl with the + # ns_to_ds_attribute_map to set the appropriate values. + if value != "" and not value.nil? + case attribute + when :password + self.password = value + when :iterations + self.iterations = value + when :salt + self.salt = value + when :groups + value.split(',').each do |group| + merge_attribute_with_dscl('Groups', group, 'GroupMembership', @resource.name) + merge_attribute_with_dscl('Groups', group, 'GroupMembers', @guid) + end + else + merge_attribute_with_dscl('Users', @resource.name, self.class.ns_to_ds_attribute_map[attribute], value) + end + end + end + end + + def delete + # This method is called when ensure => absent has been set. + # Deleting a user is handled by dscl + dscl '.', '-delete', "/Users/#{@resource.name}" + end + +## ## +## Getter/Setter Methods ## +## ## + + def groups=(value) + # In the setter method we're only going to take action on groups for which + # the user is not currently a member. + guid = self.class.get_attribute_from_dscl('Users', @resource.name, 'GeneratedUID')['dsAttrTypeStandard:GeneratedUID'][0] + groups_to_add = value.split(',') - groups.split(',') + groups_to_add.each do |group| + merge_attribute_with_dscl('Groups', group, 'GroupMembership', @resource.name) + merge_attribute_with_dscl('Groups', group, 'GroupMembers', guid) + end + end + + def password=(value) + # If you thought GETTING a password was bad, try SETTING it. This method + # makes me want to cry. A thousand tears... # - # user = @resource[:name] - # data.each do |name, members| - # if members.include? user and groups.include? name - # # I'm in the group and should be - # next - # elsif members.include? user - # # I'm in the group and shouldn't be - # setuserlist(name, members - [user]) - # elsif groups.include? name - # # I'm not in the group and should be - # setuserlist(name, members + [user]) - # else - # # I'm not in the group and shouldn't be - # next - # end - # end + # I've been unsuccessful in tracking down a way to set the password for + # a user using dscl that DOESN'T require passing it as plaintext. We were + # also unable to get dsimport to work like this. Due to these downfalls, + # the sanest method requires opening the user's plist, dropping in the + # password hash, and serializing it back to disk. The problems with THIS + # method revolve around dscl. Any time you directly modify a user's plist, + # you need to flush the cache that dscl maintains. + if (Puppet::Util::Package.versioncmp(Facter.value(:macosx_productversion_major), '10.7') == -1) + write_sha1_hash(value) + else + if Facter.value(:macosx_productversion_major) == '10.7' + if value.length != 136 + raise Puppet::Error, "OS X 10.7 requires a Salted SHA512 hash password of 136 characters. Please check your password and try again." + end + else + if value.length != 256 + raise Puppet::Error, "OS X versions > 10.7 require a Salted SHA512 PBKDF2 password hash of 256 characters. Please check your password and try again." + end + end + + # Methods around setting the password on OS X are the ONLY methods that + # cannot use dscl (because the only way to set it via dscl is by passing + # a plaintext password - which is bad). Because of this, we have to change + # the user's plist directly. DSCL has its own caching mechanism, which + # means that every time we call dscl in this provider we're not directly + # changing values on disk (instead, those calls are cached and written + # to disk according to Apple's prioritization algorithms). When Puppet + # needs to set the password property on OS X > 10.6, the provider has to + # tell dscl to write its cache to disk before modifying the user's + # plist. The 'dscacheutil -flushcache' command does this. Another issue + # is how fast Puppet makes calls to dscl and how long it takes dscl to + # enter those calls into its cache. We have to sleep for 2 seconds before + # flushing the dscl cache to allow all dscl calls to get INTO the cache + # first. This could be made faster (and avoid a sleep call) by finding + # a way to enter calls into the dscl cache faster. A sleep time of 1 + # second would intermittantly require a second Puppet run to set + # properties, so 2 seconds seems to be the minimum working value. + sleep 2 + flush_dscl_cache + write_password_to_users_plist(value) + + # Since we just modified the user's plist, we need to flush the ds cache + # again so dscl can pick up on the changes we made. + flush_dscl_cache + end + end + + def iterations=(value) + # The iterations and salt properties, like the password property, can only + # be modified by directly changing the user's plist. Because of this fact, + # we have to treat the ds cache just like you would in the password= + # method. + if (Puppet::Util::Package.versioncmp(Facter.value(:macosx_productversion_major), '10.7') > 0) + sleep 2 + flush_dscl_cache + users_plist = Plist::parse_xml(plutil '-convert', 'xml1', '-o', '/dev/stdout', "#{users_plist_dir}/#{@resource.name}.plist") + shadow_hash_data = get_shadow_hash_data(users_plist) + set_salted_pbkdf2(users_plist, shadow_hash_data, 'iterations', value) + flush_dscl_cache + end + end + + def salt=(value) + # The iterations and salt properties, like the password property, can only + # be modified by directly changing the user's plist. Because of this fact, + # we have to treat the ds cache just like you would in the password= + # method. + if (Puppet::Util::Package.versioncmp(Facter.value(:macosx_productversion_major), '10.7') > 0) + sleep 2 + flush_dscl_cache + users_plist = Plist::parse_xml(plutil '-convert', 'xml1', '-o', '/dev/stdout', "#{users_plist_dir}/#{@resource.name}.plist") + shadow_hash_data = get_shadow_hash_data(users_plist) + set_salted_pbkdf2(users_plist, shadow_hash_data, 'salt', value) + flush_dscl_cache + end + end + + ##### + # Dynamically create setter methods for dscl properties + ##### + # + # Setter methods are only called when a resource currently has a value for + # that property and it needs changed (true here since all of these values + # have a default that is set in the create method). We don't want to merge + # in additional values if an incorrect value is set, we want to CHANGE it. + # When using the -change argument in dscl, the old value needs to be passed + # first (followed by the new value). Because of this, we get the current + # value from the @property_hash variable and then use the value passed as + # the new value. Because we're prefetching instances of the provider, it's + # possible that the value determined at the start of the run may be stale + # (i.e. someone changed the value by hand during a Puppet run) - if that's + # the case we rescue the error from dscl and alert the user. + # + # In the event that the user doesn't HAVE a value for the attribute, the + # provider should use the -merge option with dscl to add the attribute value + # for the user record + ['home', 'uid', 'gid', 'comment', 'shell'].each do |setter_method| + define_method("#{setter_method}=") do |value| + if @property_hash[setter_method.intern] + begin + dscl '.', '-change', "/Users/#{resource.name}", self.class.ns_to_ds_attribute_map[setter_method.intern], @property_hash[setter_method.intern], value + rescue Puppet::ExecutionFailure => e + raise Puppet::Error, "Cannot set the #{setter_method} value of '#{value}' for user " + + "#{@resource.name} due to the following error: #{e.inspect}" + end + else + begin + dscl '.', '-merge', "/Users/#{resource.name}", self.class.ns_to_ds_attribute_map[setter_method.intern], value + rescue Puppet::ExecutionFailure => e + raise Puppet::Error, "Cannot set the #{setter_method} value of '#{value}' for user " + + "#{@resource.name} due to the following error: #{e.inspect}" + end + end + end + end + + + ## ## + ## Helper Methods ## + ## ## + + def users_plist_dir + '/var/db/dslocal/nodes/Default/users' + end + + def self.password_hash_dir + '/var/db/shadow/hash' + end + + def merge_attribute_with_dscl(path, username, keyname, value) + # This method will merge in a given value using dscl + begin + dscl '.', '-merge', "/#{path}/#{username}", keyname, value + rescue Puppet::ExecutionFailure => detail + raise Puppet::Error, "Could not set the dscl #{keyname} key with value: #{value} - #{detail.inspect}" + end + end + + def create_new_user(username) + # Create the new user with dscl + dscl '.', '-create', "/Users/#{username}" end + def next_system_id(min_id=20) + # Get the next available uid on the system by getting a list of user ids, + # sorting them, grabbing the last one, and adding a 1. Scientific stuff here. + dscl_output = dscl '.', '-list', '/Users', 'uid' + # We're ok with throwing away negative uids here. Also, remove nil values. + user_ids = dscl_output.split.compact.collect { |l| l.to_i if l.match(/^\d+$/) } + ids = user_ids.compact!.sort! { |a,b| a.to_f <=> b.to_f } + # We're just looking for an unused id in our sorted array. + ids.each_index do |i| + next_id = ids[i] + 1 + return next_id if ids[i+1] != next_id and next_id >= min_id + end + end + + def write_password_to_users_plist(value) + # # This method is only called on version 10.7 or greater. On 10.7 machines, + # # passwords are set using a salted-SHA512 hash, and on 10.8 machines, + # # passwords are set using PBKDF2. It's possible to have users on 10.8 + # # who have upgraded from 10.7 and thus have a salted-SHA512 password hash. + # # If we encounter this, do what 10.8 does - remove that key and give them + # # a 10.8-style PBKDF2 password. + users_plist = Plist::parse_xml(plutil '-convert', 'xml1', '-o', '/dev/stdout', "#{users_plist_dir}/#{@resource.name}.plist") + shadow_hash_data = get_shadow_hash_data(users_plist) + if Facter.value(:macosx_productversion_major) == '10.7' + set_salted_sha512(users_plist, shadow_hash_data, value) + else + shadow_hash_data.delete('SALTED-SHA512') if shadow_hash_data['SALTED-SHA512'] + set_salted_pbkdf2(users_plist, shadow_hash_data, 'entropy', value) + end + end + + def flush_dscl_cache + dscacheutil '-flushcache' + end + + def get_shadow_hash_data(users_plist) + # This method will return the binary plist that's embedded in the + # ShadowHashData key of a user's plist, or false if it doesn't exist. + if users_plist['ShadowHashData'] + password_hash_plist = users_plist['ShadowHashData'][0].string + self.class.convert_binary_to_xml(password_hash_plist) + else + false + end + end + + def set_salted_sha512(users_plist, shadow_hash_data, value) + # Puppet requires a salted-sha512 password hash for 10.7 users to be passed + # in Hex, but the embedded plist stores that value as a Base64 encoded + # string. This method converts the string and calls the + # write_users_plist_to_disk method to serialize and write the plist to disk. + unless shadow_hash_data + shadow_hash_data = Hash.new + shadow_hash_data['SALTED-SHA512'] = StringIO.new + end + shadow_hash_data['SALTED-SHA512'].string = Base64.decode64([[value].pack("H*")].pack("m").strip) + binary_plist = self.class.convert_xml_to_binary(shadow_hash_data) + users_plist['ShadowHashData'][0].string = binary_plist + write_users_plist_to_disk(users_plist) + end + + def set_salted_pbkdf2(users_plist, shadow_hash_data, field, value) + # This method accepts a passed value and one of three fields: 'salt', + # 'entropy', or 'iterations'. These fields correspond with the fields + # utilized in a PBKDF2 password hashing system + # (see http://en.wikipedia.org/wiki/PBKDF2 ) where 'entropy' is the + # password hash, 'salt' is the password hash salt value, and 'iterations' + # is an integer recommended to be > 10,000. The remaining arguments are + # the user's plist itself, and the shadow_hash_data hash containing the + # existing PBKDF2 values. + shadow_hash_data = Hash.new unless shadow_hash_data + shadow_hash_data['SALTED-SHA512-PBKDF2'] = Hash.new unless shadow_hash_data['SALTED-SHA512-PBKDF2'] + case field + when 'salt', 'entropy' + shadow_hash_data['SALTED-SHA512-PBKDF2'][field] = StringIO.new unless shadow_hash_data['SALTED-SHA512-PBKDF2'][field] + shadow_hash_data['SALTED-SHA512-PBKDF2'][field].string = Base64.decode64([[value].pack("H*")].pack("m").strip) + when 'iterations' + shadow_hash_data['SALTED-SHA512-PBKDF2'][field] = Integer(value) + else + raise Puppet::Error "Puppet has tried to set an incorrect field for the 'SALTED-SHA512-PBKDF2' hash. Acceptable fields are 'salt', 'entropy', or 'iterations'." + end + + # on 10.8, this field *must* contain 8 stars, or authentication will + # fail. + users_plist['passwd'] = ('*' * 8) + # Convert shadow_hash_data to a binary plist, write that value to the + # users_plist hash, and write the users_plist back to disk. + binary_plist = self.class.convert_xml_to_binary(shadow_hash_data) + users_plist['ShadowHashData'][0].string = binary_plist + write_users_plist_to_disk(users_plist) + end + + def write_users_plist_to_disk(users_plist) + # This method will accept a plist in XML format, save it to disk, convert + # the plist to a binary format, and flush the dscl cache. + Plist::Emit.save_plist(users_plist, "#{users_plist_dir}/#{@resource.name}.plist") + plutil'-convert', 'binary1', "#{users_plist_dir}/#{@resource.name}.plist" + end + + def write_to_file(filename, value) + # This is a simple wrapper method for writing values to a file. + begin + File.open(filename, 'w') { |f| f.write(value)} + rescue Errno::EACCES => detail + raise Puppet::Error, "Could not write to file #{filename}: #{detail}" + end + end + + def write_sha1_hash(value) + users_guid = self.class.get_attribute_from_dscl('Users', @resource.name, 'GeneratedUID')['dsAttrTypeStandard:GeneratedUID'][0] + password_hash_file = "#{self.class.password_hash_dir}/#{users_guid}" + write_to_file(password_hash_file, value) + + # NBK: For shadow hashes, the user AuthenticationAuthority must contain a value of + # ";ShadowHash;". The LKDC in 10.5 makes this more interesting though as it + # will dynamically generate ;Kerberosv5;;username@LKDC:SHA1 attributes if + # missing. Thus we make sure we only set ;ShadowHash; if it is missing, and + # we can do this with the merge command. This allows people to continue to + # use other custom AuthenticationAuthority attributes without stomping on them. + # + # There is a potential problem here in that we're only doing this when setting + # the password, and the attribute could get modified at other times while the + # hash doesn't change and so this doesn't get called at all... but + # without switching all the other attributes to merge instead of create I can't + # see a simple enough solution for this that doesn't modify the user record + # every single time. This should be a rather rare edge case. (famous last words) + + merge_attribute_with_dscl('Users', @resource.name, 'AuthenticationAuthority', ';ShadowHash;') + end end diff --git a/lib/puppet/type/user.rb b/lib/puppet/type/user.rb index 1c655b25e..594323d35 100755 --- a/lib/puppet/type/user.rb +++ b/lib/puppet/type/user.rb @@ -1,525 +1,542 @@ require 'etc' require 'facter' require 'puppet/property/list' require 'puppet/property/ordered_list' require 'puppet/property/keyvalue' module Puppet newtype(:user) do @doc = "Manage users. This type is mostly built to manage system users, so it is lacking some features useful for managing normal users. This resource type uses the prescribed native tools for creating groups and generally uses POSIX APIs for retrieving information about them. It does not directly modify `/etc/passwd` or anything. **Autorequires:** If Puppet is managing the user's primary group (as provided in the `gid` attribute), the user resource will autorequire that group. If Puppet is managing any role accounts corresponding to the user's roles, the user resource will autorequire those role accounts." feature :allows_duplicates, "The provider supports duplicate users with the same UID." feature :manages_homedir, "The provider can create and remove home directories." feature :manages_passwords, "The provider can modify user passwords, by accepting a password hash." feature :manages_password_age, "The provider can set age requirements and restrictions for passwords." feature :manages_solaris_rbac, "The provider can manage roles and normal users" feature :manages_expiry, "The provider can manage the expiry date for a user." feature :system_users, "The provider allows you to create system users with lower UIDs." feature :manages_aix_lam, "The provider can manage AIX Loadable Authentication Module (LAM) system." newproperty(:ensure, :parent => Puppet::Property::Ensure) do newvalue(:present, :event => :user_created) do provider.create end newvalue(:absent, :event => :user_removed) do provider.delete end newvalue(:role, :event => :role_created, :required_features => :manages_solaris_rbac) do provider.create_role end desc "The basic state that the object should be in." # If they're talking about the thing at all, they generally want to # say it should exist. defaultto do if @resource.managed? :present else nil end end def retrieve if provider.exists? if provider.respond_to?(:is_role?) and provider.is_role? return :role else return :present end else return :absent end end end newproperty(:home) do desc "The home directory of the user. The directory must be created separately and is not currently checked for existence." end newproperty(:uid) do desc "The user ID; must be specified numerically. If no user ID is specified when creating a new user, then one will be chosen automatically. This will likely result in the same user having different UIDs on different systems, which is not recommended. This is especially noteworthy when managing the same user on both Darwin and other platforms, since Puppet does UID generation on Darwin, but the underlying tools do so on other platforms. On Windows, this property is read-only and will return the user's security identifier (SID)." munge do |value| case value when String if value =~ /^[-0-9]+$/ value = Integer(value) end end return value end end newproperty(:gid) do desc "The user's primary group. Can be specified numerically or by name. Note that users on Windows systems do not have a primary group; manage groups with the `groups` attribute instead." munge do |value| if value.is_a?(String) and value =~ /^[-0-9]+$/ Integer(value) else value end end def insync?(is) # We know the 'is' is a number, so we need to convert the 'should' to a number, # too. @should.each do |value| return true if number = Puppet::Util.gid(value) and is == number end false end def sync found = false @should.each do |value| if number = Puppet::Util.gid(value) provider.gid = number found = true break end end fail "Could not find group(s) #{@should.join(",")}" unless found # Use the default event. end end newproperty(:comment) do desc "A description of the user. Generally the user's full name." end newproperty(:shell) do desc "The user's login shell. The shell must exist and be executable. This attribute cannot be managed on Windows systems." end newproperty(:password, :required_features => :manages_passwords) do desc %q{The user's password, in whatever encrypted format the local system requires. * Most modern Unix-like systems use salted SHA1 password hashes. You can use Puppet's built-in `sha1` function to generate a hash from a password. * Mac OS X 10.5 and 10.6 also use salted SHA1 hashes. * Mac OS X 10.7 (Lion) uses salted SHA512 hashes. The Puppet Labs [stdlib][] module contains a `str2saltedsha512` function which can generate password hashes for Lion. * Windows passwords can only be managed in cleartext, as there is no Windows API for setting the password hash. [stdlib]: https://github.com/puppetlabs/puppetlabs-stdlib/ Be sure to enclose any value that includes a dollar sign ($) in single quotes (') to avoid accidental variable interpolation.} validate do |value| raise ArgumentError, "Passwords cannot include ':'" if value.is_a?(String) and value.include?(":") end def change_to_s(currentvalue, newvalue) if currentvalue == :absent return "created password" else return "changed password" end end def is_to_s( currentvalue ) return '[old password hash redacted]' end def should_to_s( newvalue ) return '[new password hash redacted]' end end newproperty(:password_min_age, :required_features => :manages_password_age) do desc "The minimum number of days a password must be used before it may be changed." munge do |value| case value when String Integer(value) else value end end validate do |value| if value.to_s !~ /^-?\d+$/ raise ArgumentError, "Password minimum age must be provided as a number." end end end newproperty(:password_max_age, :required_features => :manages_password_age) do desc "The maximum number of days a password may be used before it must be changed." munge do |value| case value when String Integer(value) else value end end validate do |value| if value.to_s !~ /^-?\d+$/ raise ArgumentError, "Password maximum age must be provided as a number." end end end newproperty(:groups, :parent => Puppet::Property::List) do desc "The groups to which the user belongs. The primary group should not be listed, and groups should be identified by name rather than by GID. Multiple groups should be specified as an array." validate do |value| if value =~ /^\d+$/ raise ArgumentError, "Group names must be provided, not GID numbers." end raise ArgumentError, "Group names must be provided as an array, not a comma-separated list." if value.include?(",") raise ArgumentError, "Group names must not be empty. If you want to specify \"no groups\" pass an empty array" if value.empty? end end newparam(:name) do desc "The user name. While naming limitations vary by operating system, it is advisable to restrict names to the lowest common denominator, which is a maximum of 8 characters beginning with a letter. Note that Puppet considers user names to be case-sensitive, regardless of the platform's own rules; be sure to always use the same case when referring to a given user." isnamevar end newparam(:membership) do desc "Whether specified groups should be considered the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of groups to which the user belongs. Defaults to `minimum`." newvalues(:inclusive, :minimum) defaultto :minimum end newparam(:system, :boolean => true) do desc "Whether the user is a system user, according to the OS's criteria; on most platforms, a UID less than or equal to 500 indicates a system user. Defaults to `false`." newvalues(:true, :false) defaultto false end newparam(:allowdupe, :boolean => true) do desc "Whether to allow duplicate UIDs. Defaults to `false`." newvalues(:true, :false) defaultto false end newparam(:managehome, :boolean => true) do desc "Whether to manage the home directory when managing the user. This will create the home directory when `ensure => present`, and delete the home directory when `ensure => absent`. Defaults to `false`." newvalues(:true, :false) defaultto false validate do |val| if val.to_s == "true" raise ArgumentError, "User provider #{provider.class.name} can not manage home directories" unless provider.class.manages_homedir? end end end newproperty(:expiry, :required_features => :manages_expiry) do desc "The expiry date for this user. Must be provided in a zero-padded YYYY-MM-DD format --- e.g. 2010-02-19." validate do |value| if value !~ /^\d{4}-\d{2}-\d{2}$/ raise ArgumentError, "Expiry dates must be YYYY-MM-DD" end end end # Autorequire the group, if it's around autorequire(:group) do autos = [] if obj = @parameters[:gid] and groups = obj.shouldorig groups = groups.collect { |group| if group =~ /^\d+$/ Integer(group) else group end } groups.each { |group| case group when Integer if resource = catalog.resources.find { |r| r.is_a?(Puppet::Type.type(:group)) and r.should(:gid) == group } autos << resource end else autos << group end } end if obj = @parameters[:groups] and groups = obj.should autos += groups.split(",") end autos end # Provide an external hook. Yay breaking out of APIs. def exists? provider.exists? end def retrieve absent = false properties.inject({}) { |prophash, property| current_value = :absent if absent prophash[property] = :absent else current_value = property.retrieve prophash[property] = current_value end if property.name == :ensure and current_value == :absent absent = true end prophash } end newproperty(:roles, :parent => Puppet::Property::List, :required_features => :manages_solaris_rbac) do desc "The roles the user has. Multiple roles should be specified as an array." def membership :role_membership end validate do |value| if value =~ /^\d+$/ raise ArgumentError, "Role names must be provided, not numbers" end raise ArgumentError, "Role names must be provided as an array, not a comma-separated list" if value.include?(",") end end #autorequire the roles that the user has autorequire(:user) do reqs = [] if roles_property = @parameters[:roles] and roles = roles_property.should reqs += roles.split(',') end reqs end newparam(:role_membership) do desc "Whether specified roles should be considered the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of roles the user has. Defaults to `minimum`." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:auths, :parent => Puppet::Property::List, :required_features => :manages_solaris_rbac) do desc "The auths the user has. Multiple auths should be specified as an array." def membership :auth_membership end validate do |value| if value =~ /^\d+$/ raise ArgumentError, "Auth names must be provided, not numbers" end raise ArgumentError, "Auth names must be provided as an array, not a comma-separated list" if value.include?(",") end end newparam(:auth_membership) do desc "Whether specified auths should be considered the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of auths the user has. Defaults to `minimum`." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:profiles, :parent => Puppet::Property::OrderedList, :required_features => :manages_solaris_rbac) do desc "The profiles the user has. Multiple profiles should be specified as an array." def membership :profile_membership end validate do |value| if value =~ /^\d+$/ raise ArgumentError, "Profile names must be provided, not numbers" end raise ArgumentError, "Profile names must be provided as an array, not a comma-separated list" if value.include?(",") end end newparam(:profile_membership) do desc "Whether specified roles should be treated as the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of roles of which the user is a member. Defaults to `minimum`." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:keys, :parent => Puppet::Property::KeyValue, :required_features => :manages_solaris_rbac) do desc "Specify user attributes in an array of key = value pairs." def membership :key_membership end validate do |value| raise ArgumentError, "Key/value pairs must be separated by an =" unless value.include?("=") end end newparam(:key_membership) do desc "Whether specified key/value pairs should be considered the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of the user's attributes. Defaults to `minimum`." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:project, :required_features => :manages_solaris_rbac) do desc "The name of the project associated with a user." end newparam(:ia_load_module, :required_features => :manages_aix_lam) do desc "The name of the I&A module to use to manage this user." end newproperty(:attributes, :parent => Puppet::Property::KeyValue, :required_features => :manages_aix_lam) do desc "Specify AIX attributes for the user in an array of attribute = value pairs." def membership :attribute_membership end def delimiter " " end validate do |value| raise ArgumentError, "Attributes value pairs must be separated by an =" unless value.include?("=") end end newparam(:attribute_membership) do desc "Whether specified attribute value pairs should be treated as the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of attribute/value pairs for the user. Defaults to `minimum`." newvalues(:inclusive, :minimum) defaultto :minimum end + newproperty(:salt) do + desc "This is the 32 byte salt used to generate the PBKDF2 password used in + OS X" + end + + newproperty(:iterations) do + desc "This is the number of iterations of a chained computation of the + password hash (http://en.wikipedia.org/wiki/PBKDF2). This parameter + is used in OS X" + munge do |value| + if value.is_a?(String) and value =~/^[-0-9]+$/ + Integer(value) + else + value + end + end + end end end diff --git a/spec/unit/provider/nameservice/directoryservice_spec.rb b/spec/unit/provider/nameservice/directoryservice_spec.rb index 962d5542f..e7fdcbef5 100755 --- a/spec/unit/provider/nameservice/directoryservice_spec.rb +++ b/spec/unit/provider/nameservice/directoryservice_spec.rb @@ -1,189 +1,189 @@ #! /usr/bin/env ruby require 'spec_helper' # We use this as a reasonable way to obtain all the support infrastructure. -[:user, :group].each do |type_for_this_round| +[:group].each do |type_for_this_round| provider_class = Puppet::Type.type(type_for_this_round).provider(:directoryservice) describe provider_class do before do @resource = stub("resource") @provider = provider_class.new(@resource) end it "[#6009] should handle nested arrays of members" do current = ["foo", "bar", "baz"] desired = ["foo", ["quux"], "qorp"] group = 'example' @resource.stubs(:[]).with(:name).returns(group) @resource.stubs(:[]).with(:auth_membership).returns(true) @provider.instance_variable_set(:@property_value_cache_hash, { :members => current }) %w{bar baz}.each do |del| @provider.expects(:execute).once. with([:dseditgroup, '-o', 'edit', '-n', '.', '-d', del, group]) end %w{quux qorp}.each do |add| @provider.expects(:execute).once. with([:dseditgroup, '-o', 'edit', '-n', '.', '-a', add, group]) end expect { @provider.set(:members, desired) }.to_not raise_error end end end describe 'DirectoryService.single_report' do it 'should fail on OS X < 10.5' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.4") expect { Puppet::Provider::NameService::DirectoryService.single_report('resource_name') }.to raise_error(RuntimeError, "Puppet does not support OS X versions < 10.5") end it 'should use plist data on >= 10.5' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.5") Puppet::Provider::NameService::DirectoryService.stubs(:get_ds_path).returns('Users') Puppet::Provider::NameService::DirectoryService.stubs(:list_all_present).returns( ['root', 'user1', 'user2', 'resource_name'] ) Puppet::Provider::NameService::DirectoryService.stubs(:generate_attribute_hash) Puppet::Provider::NameService::DirectoryService.stubs(:execute) Puppet::Provider::NameService::DirectoryService.expects(:parse_dscl_plist_data) Puppet::Provider::NameService::DirectoryService.single_report('resource_name') end end describe 'DirectoryService.get_exec_preamble' do it 'should fail on OS X < 10.5' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.4") expect { Puppet::Provider::NameService::DirectoryService.get_exec_preamble('-list') }.to raise_error(RuntimeError, "Puppet does not support OS X versions < 10.5") end it 'should use plist data on >= 10.5' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.5") Puppet::Provider::NameService::DirectoryService.stubs(:get_ds_path).returns('Users') Puppet::Provider::NameService::DirectoryService.get_exec_preamble('-list').should include("-plist") end end describe 'DirectoryService password behavior' do # The below is a binary plist containing a ShadowHashData key which CONTAINS # another binary plist. The nested binary plist contains a 'SALTED-SHA512' # key that contains a base64 encoded salted-SHA512 password hash... let (:binary_plist) { "bplist00\324\001\002\003\004\005\006\a\bXCRAM-MD5RNT]SALTED-SHA512[RECOVERABLEO\020 \231k2\3360\200GI\201\355J\216\202\215y\243\001\206J\300\363\032\031\022\006\2359\024\257\217<\361O\020\020F\353\at\377\277\226\276c\306\254\031\037J(\235O\020D\335\006{\3744g@\377z\204\322\r\332t\021\330\n\003\246K\223\356\034!P\261\305t\035\346\352p\206\003n\247MMA\310\301Z<\366\246\023\0161W3\340\357\000\317T\t\301\311+\204\246L7\276\370\320*\245O\021\002\000k\024\221\270x\353\001\237\346D}\377?\265]\356+\243\v[\350\316a\340h\376<\322\266\327\016\306n\272r\t\212A\253L\216\214\205\016\241 [\360/\335\002#\\A\372\241a\261\346\346\\\251\330\312\365\016\n\341\017\016\225&;\322\\\004*\ru\316\372\a \362?8\031\247\231\030\030\267\315\023\v\343{@\227\301s\372h\212\000a\244&\231\366\nt\277\2036,\027bZ+\223W\212g\333`\264\331N\306\307\362\257(^~ b\262\247&\231\261t\341\231%\244\247\203eOt\365\271\201\273\330\350\363C^A\327F\214!\217hgf\e\320k\260n\315u~\336\371M\t\235k\230S\375\311\303\240\351\037d\273\321y\335=K\016`_\317\230\2612_\023K\036\350\v\232\323Y\310\317_\035\227%\237\v\340\023\016\243\233\025\306:\227\351\370\364x\234\231\266\367\016w\275\333-\351\210}\375x\034\262\272kRuHa\362T/F!\347B\231O`K\304\037'k$$\245h)e\363\365mT\b\317\\2\361\026\351\254\375Jl1~\r\371\267\352\2322I\341\272\376\243^Un\266E7\230[VocUJ\220N\2116D/\025f=\213\314\325\vG}\311\360\377DT\307m\261&\263\340\272\243_\020\271rG^BW\210\030l\344\0324\335\233\300\023\272\225Im\330\n\227*Yv[\006\315\330y'\a\321\373\273A\240\305F{S\246I#/\355\2425\031\031GGF\270y\n\331\004\023G@\331\000\361\343\350\264$\032\355_\210y\000\205\342\375\212q\024\004\026W:\205 \363v?\035\270L-\270=\022\323\2003\v\336\277\t\237\356\374\n\267n\003\367\342\330;\371S\326\016`B6@Njm>\240\021%\336\345\002(P\204Yn\3279l\0228\264\254\304\2528t\372h\217\347sA\314\345\245\337)]\000\b\000\021\000\032\000\035\000+\0007\000Z\000m\000\264\000\000\000\000\000\000\002\001\000\000\000\000\000\000\000\t\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\270" } # The below is a base64 encoded salted-SHA512 password hash. let (:pw_string) { "\335\006{\3744g@\377z\204\322\r\332t\021\330\n\003\246K\223\356\034!P\261\305t\035\346\352p\206\003n\247MMA\310\301Z<\366\246\023\0161W3\340\357\000\317T\t\301\311+\204\246L7\276\370\320*\245" } # The below is a salted-SHA512 password hash in hex. let (:sha512_hash) { 'dd067bfc346740ff7a84d20dda7411d80a03a64b93ee1c2150b1c5741de6ea7086036ea74d4d41c8c15a3cf6a6130e315733e0ef00cf5409c1c92b84a64c37bef8d02aa5' } let :plist_path do '/var/db/dslocal/nodes/Default/users/jeff.plist' end let :ds_provider do Puppet::Provider::NameService::DirectoryService end let :shadow_hash_data do {'ShadowHashData' => [StringIO.new(binary_plist)]} end subject do Puppet::Provider::NameService::DirectoryService end before :each do subject.expects(:get_macosx_version_major).returns("10.7") end it 'should execute convert_binary_to_xml once when getting the password on >= 10.7' do subject.expects(:convert_binary_to_xml).returns({'SALTED-SHA512' => StringIO.new(pw_string)}) File.expects(:exists?).with(plist_path).once.returns(true) Plist.expects(:parse_xml).returns(shadow_hash_data) # On Mac OS X 10.7 we first need to convert to xml when reading the password subject.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', plist_path) subject.get_password('uid', 'jeff') end it 'should fail if a salted-SHA512 password hash is not passed in >= 10.7' do expect { subject.set_password('jeff', 'uid', 'badpassword') }.to raise_error(RuntimeError, /OS X 10.7 requires a Salted SHA512 hash password of 136 characters./) end it 'should convert xml-to-binary and binary-to-xml when setting the pw on >= 10.7' do subject.expects(:convert_binary_to_xml).returns({'SALTED-SHA512' => StringIO.new(pw_string)}) subject.expects(:convert_xml_to_binary).returns(binary_plist) File.expects(:exists?).with(plist_path).once.returns(true) Plist.expects(:parse_xml).returns(shadow_hash_data) # On Mac OS X 10.7 we first need to convert to xml subject.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', plist_path) # And again back to a binary plist or DirectoryService will complain subject.expects(:plutil).with('-convert', 'binary1', plist_path) Plist::Emit.expects(:save_plist).with(shadow_hash_data, plist_path) subject.set_password('jeff', 'uid', sha512_hash) end it '[#13686] should handle an empty ShadowHashData field in the users plist' do subject.expects(:convert_xml_to_binary).returns(binary_plist) File.expects(:exists?).with(plist_path).once.returns(true) Plist.expects(:parse_xml).returns({'ShadowHashData' => nil}) subject.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', plist_path) subject.expects(:plutil).with('-convert', 'binary1', plist_path) Plist::Emit.expects(:save_plist) subject.set_password('jeff', 'uid', sha512_hash) end end describe '(#4855) directoryservice group resource failure' do let :provider_class do Puppet::Type.type(:group).provider(:directoryservice) end let :group_members do ['root','jeff'] end let :user_account do ['root'] end let :stub_resource do stub('resource') end subject do provider_class.new(stub_resource) end before :each do @resource = stub("resource") @provider = provider_class.new(@resource) end it 'should delete a group member if the user does not exist' do stub_resource.stubs(:[]).with(:name).returns('fake_group') stub_resource.stubs(:name).returns('fake_group') subject.expects(:execute).with([:dseditgroup, '-o', 'edit', '-n', '.', '-d', 'jeff', 'fake_group']).raises(Puppet::ExecutionFailure, 'it broke') subject.expects(:execute).with([:dscl, '.', '-delete', '/Groups/fake_group', 'GroupMembership', 'jeff']) subject.remove_unwanted_members(group_members, user_account) end end diff --git a/spec/unit/provider/user/directoryservice_spec.rb b/spec/unit/provider/user/directoryservice_spec.rb new file mode 100755 index 000000000..eeafd44cd --- /dev/null +++ b/spec/unit/provider/user/directoryservice_spec.rb @@ -0,0 +1,943 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'facter/util/plist' + +describe Puppet::Type.type(:user).provider(:directoryservice) do + let(:username) { 'nonexistant_user' } + let(:user_path) { "/Users/#{username}" } + let(:resource) do + Puppet::Type.type(:user).new( + :name => username, + :provider => :directoryservice + ) + end + let(:provider) { resource.provider } + let(:users_plist_dir) { '/var/db/dslocal/nodes/Default/users' } + + # This is the output of doing `dscl -plist . read /Users/` which + # will return a hash of keys whose values are all arrays. + let(:user_plist_xml) do + ' + + + + dsAttrTypeStandard:NFSHomeDirectory + + /Users/nonexistant_user + + dsAttrTypeStandard:RealName + + nonexistant_user + + dsAttrTypeStandard:PrimaryGroupID + + 22 + + dsAttrTypeStandard:UniqueID + + 1000 + + dsAttrTypeStandard:RecordName + + nonexistant_user + + + ' + end + + # This is the same as above, however in a native Ruby hash instead + # of XML + let(:user_plist_hash) do + { + "dsAttrTypeStandard:RealName" => [username], + "dsAttrTypeStandard:NFSHomeDirectory" => [user_path], + "dsAttrTypeStandard:PrimaryGroupID" => ["22"], + "dsAttrTypeStandard:UniqueID" => ["1000"], + "dsAttrTypeStandard:RecordName" => [username] + } + end + + # The below value is the result of executing + # `dscl -plist . read /Users/ ShadowHashData` on a 10.7 + # system and converting it to a native Ruby Hash with Plist.parse_xml + let(:sha512_shadowhashdata_hash) do + { + 'dsAttrTypeNative:ShadowHashData' => ['62706c69 73743030 d101025d 53414c54 45442d53 48413531 324f1044 7ea7d592 131f57b2 c8f8bdbc ec8d9df1 2128a386 393a4f00 c7619bac 2622a44d 451419d1 1da512d5 915ab98e 39718ac9 4083fe2e fd6bf710 a54d477f 8ff735b1 2587192d 080b1900 00000000 00010100 00000000 00000300 00000000 00000000 00000000 000060'] + } + end + + # The below is a binary plist that is stored in the ShadowHashData key + # on a 10.7 system. + let(:sha512_embedded_bplist) do + "bplist00\321\001\002]SALTED-SHA512O\020D~\247\325\222\023\037W\262\310\370\275\274\354\215\235\361!(\243\2069:O\000\307a\233\254&\"\244ME\024\031\321\035\245\022\325\221Z\271\2169q\212\311@\203\376.\375k\367\020\245MG\177\217\3675\261%\207\031-\b\v\031\000\000\000\000\000\000\001\001\000\000\000\000\000\000\000\003\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000`" + end + + # The below is a Base64 encoded string representing a salted-SHA512 password + # hash. + let(:sha512_pw_string) do + "~\247\325\222\023\037W\262\310\370\275\274\354\215\235\361!(\243\2069:O\000\307a\233\254&\"\244ME\024\031\321\035\245\022\325\221Z\271\2169q\212\311@\203\376.\375k\367\020\245MG\177\217\3675\261%\207\031-" + end + + # The below is the result of converting sha512_embedded_bplist to XML and + # parsing it with Plist.parse_xml. It is a Ruby Hash whose value is a + # StringIO object holding a Base64 encoded salted-SHA512 password hash. + let(:sha512_embedded_bplist_hash) do + { 'SALTED-SHA512' => StringIO.new(sha512_pw_string) } + end + + # The value below is the result of converting sha512_pw_string to Hex. + let(:sha512_password_hash) do + '7ea7d592131f57b2c8f8bdbcec8d9df12128a386393a4f00c7619bac2622a44d451419d11da512d5915ab98e39718ac94083fe2efd6bf710a54d477f8ff735b12587192d' + end + + # The below value is the result of executing + # `dscl -plist . read /Users/ ShadowHashData` on a 10.8 + # system and converting it to a native Ruby Hash with Plist.parse_xml + let(:pbkdf2_shadowhashdata_hash) do + { + "dsAttrTypeNative:ShadowHashData"=>["62706c69 73743030 d101025f 10145341 4c544544 2d534841 3531322d 50424b44 4632d303 04050607 0857656e 74726f70 79547361 6c745a69 74657261 74696f6e 734f1080 0590ade1 9e6953c1 35ae872a e7761823 5df7d46c 63de7f9a 0fcdf2cd 9e7d85e4 b7ca8681 01235b61 58e05a30 9805ee48 14b027a4 be9c23ec 2926bc81 72269aff ba5c9a59 85e81091 fa689807 6d297f1f aa75fa61 7551ef16 71d75200 55c4a0d9 7b9b9c58 05aa322b aedbcd8e e9c52381 1653ac2e a9e9c8d8 f1ac519a 0f2b595e 4f102093 77c46908 a1c8ac2c 3e45c0d4 4da8ad0f cd85ec5c 14d9a59f fc40c9da 31f0ec11 60b0080b 22293136 41c4e700 00000000 00010100 00000000 00000900 00000000 00000000 00000000 0000ea"] + } + end + + # The below value is the result of converting pbkdf2_embedded_bplist to XML and + # parsing it with Plist.parse_xml. + let(:pbkdf2_embedded_bplist_hash) do + { + 'SALTED-SHA512-PBKDF2' => { + 'entropy' => StringIO.new(pbkdf2_pw_string), + 'salt' => StringIO.new(pbkdf2_salt_string), + 'iterations' => pbkdf2_iterations_value + } + } + end + + # The value below is the result of converting pbkdf2_pw_string to Hex. + let(:pbkdf2_password_hash) do + '0590ade19e6953c135ae872ae77618235df7d46c63de7f9a0fcdf2cd9e7d85e4b7ca868101235b6158e05a309805ee4814b027a4be9c23ec2926bc8172269affba5c9a5985e81091fa6898076d297f1faa75fa617551ef1671d7520055c4a0d97b9b9c5805aa322baedbcd8ee9c523811653ac2ea9e9c8d8f1ac519a0f2b595e' + end + + # The below is a binary plist that is stored in the ShadowHashData key + # of a 10.8 system. + let(:pbkdf2_embedded_plist) do + "bplist00\321\001\002_\020\024SALTED-SHA512-PBKDF2\323\003\004\005\006\a\bWentropyTsaltZiterationsO\020\200\005\220\255\341\236iS\3015\256\207*\347v\030#]\367\324lc\336\177\232\017\315\362\315\236}\205\344\267\312\206\201\001#[aX\340Z0\230\005\356H\024\260'\244\276\234#\354)&\274\201r&\232\377\272\\\232Y\205\350\020\221\372h\230\am)\177\037\252u\372auQ\357\026q\327R\000U\304\240\331{\233\234X\005\2522+\256\333\315\216\351\305#\201\026S\254.\251\351\310\330\361\254Q\232\017+Y^O\020 \223w\304i\b\241\310\254,>E\300\324M\250\255\017\315\205\354\\\024\331\245\237\374@\311\3321\360\354\021`\260\b\v\")16A\304\347\000\000\000\000\000\000\001\001\000\000\000\000\000\000\000\t\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\352" + end + + # The below value is a Base64 encoded string representing a PBKDF2 password + # hash. + let(:pbkdf2_pw_string) do + "\005\220\255\341\236iS\3015\256\207*\347v\030#]\367\324lc\336\177\232\017\315\362\315\236}\205\344\267\312\206\201\001#[aX\340Z0\230\005\356H\024\260'\244\276\234#\354)&\274\201r&\232\377\272\\\232Y\205\350\020\221\372h\230\am)\177\037\252u\372auQ\357\026q\327R\000U\304\240\331{\233\234X\005\2522+\256\333\315\216\351\305#\201\026S\254.\251\351\310\330\361\254Q\232\017+Y^" + end + + # The below value is a Base64 encoded string representing a PBKDF2 salt + # string. + let(:pbkdf2_salt_string) do + "\223w\304i\b\241\310\254,>E\300\324M\250\255\017\315\205\354\\\024\331\245\237\374@\311\3321\360\354" + end + + # The below value represents the Hex value of a PBKDF2 salt string + let(:pbkdf2_salt_value) do + "9377c46908a1c8ac2c3e45c0d44da8ad0fcd85ec5c14d9a59ffc40c9da31f0ec" + end + + # The below value is a Fixnum iterations value used in the PBKDF2 + # key stretching algorithm + let(:pbkdf2_iterations_value) do + 24752 + end + + # The below represents output of 'dscl -plist . readall /Users' if + # only one user were installed on the system. This lets us check + # the behavior of all the methods necessary to return a user's + # groups property by controlling the data provided by dscl + let(:testuser_plist) do + ' + + + + + dsAttrTypeNative:KerberosKeys + + 30820157 a1030201 02a08201 4e308201 4a3074a1 2b3029a0 03020112 a1220420 54af3992 1c198bf8 94585a6b 2fba445b c8482228 0dcad666 ea62e038 99e59c45 a2453043 a0030201 03a13c04 3a4c4b44 433a5348 41312e34 33383345 31353244 39443339 34414133 32443133 41453938 46364636 45314645 38443030 46383174 65737475 73657230 64a11b30 19a00302 0111a112 04106375 7d97b2ce ca8343a6 3b0f73d5 1001a245 3043a003 020103a1 3c043a4c 4b44433a 53484131 2e343338 33453135 32443944 33393441 41333244 31334145 39384636 46364531 46453844 30304638 31746573 74757365 72306ca1 233021a0 03020110 a11a0418 67b09be3 5131b670 f8e9265e 62459b4c 19435419 fe918519 a2453043 a0030201 03a13c04 3a4c4b44 433a5348 41312e34 33383345 31353244 39443339 34414133 32443133 41453938 46364636 45314645 38443030 46383174 65737475 736572 + + dsAttrTypeNative:ShadowHashData + + 62706c69 73743030 d101025d 53414c54 45442d53 48413531 324f1044 7ea7d592 131f57b2 c8f8bdbc ec8d9df1 2128a386 393a4f00 c7619bac 2622a44d 451419d1 1da512d5 915ab98e 39718ac9 4083fe2e fd6bf710 a54d477f 8ff735b1 2587192d 080b1900 00000000 00010100 00000000 00000300 00000000 00000000 00000000 000060 + + dsAttrTypeStandard:AppleMetaNodeLocation + + /Local/Default + + dsAttrTypeStandard:AuthenticationAuthority + + ;Kerberosv5;;testuser@LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81;LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81 + ;ShadowHash;HASHLIST:<SALTED-SHA512> + + dsAttrTypeStandard:AuthenticationHint + + + + dsAttrTypeStandard:GeneratedUID + + 0A7D5B63-3AD4-4CA7-B03E-85876F1D1FB3 + + dsAttrTypeStandard:NFSHomeDirectory + + /Users/nonexistant_user + + dsAttrTypeStandard:Password + + ******** + + dsAttrTypeStandard:PasswordPolicyOptions + + <?xml version="1.0" encoding="UTF-8"?> + <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> + <plist version="1.0"> + <dict> + <key>failedLoginCount</key> + <integer>0</integer> + <key>failedLoginTimestamp</key> + <date>2001-01-01T00:00:00Z</date> + <key>lastLoginTimestamp</key> + <date>2001-01-01T00:00:00Z</date> + <key>passwordTimestamp</key> + <date>2012-08-10T23:53:50Z</date> + </dict> + </plist> + + + dsAttrTypeStandard:PrimaryGroupID + + 22 + + dsAttrTypeStandard:RealName + + nonexistant_user + + dsAttrTypeStandard:RecordName + + nonexistant_user + + dsAttrTypeStandard:RecordType + + dsRecTypeStandard:Users + + dsAttrTypeStandard:UniqueID + + 1000 + + dsAttrTypeStandard:UserShell + + /bin/bash + + + + ' + end + + + + # The below represents the result of running Plist.parse_xml on XML + # data returned from the `dscl -plist . readall /Groups` command. + # (AKA: What the get_list_of_groups method returns) + let(:group_plist_hash_guid) do + [{ + 'dsAttrTypeStandard:RecordName' => ['testgroup'], + 'dsAttrTypeStandard:GroupMembership' => [ + username, + 'jeff', + 'zack' + ], + 'dsAttrTypeStandard:GroupMembers' => [ + "guid#{username}", + 'guidtestuser', + 'guidjeff', + 'guidzack' + ], + }, + { + 'dsAttrTypeStandard:RecordName' => ['second'], + 'dsAttrTypeStandard:GroupMembership' => [ + 'jeff', + 'zack' + ], + 'dsAttrTypeStandard:GroupMembers' => [ + "guid#{username}", + 'guidjeff', + 'guidzack' + ], + }, + { + 'dsAttrTypeStandard:RecordName' => ['third'], + 'dsAttrTypeStandard:GroupMembership' => [ + username, + 'jeff', + 'zack' + ], + 'dsAttrTypeStandard:GroupMembers' => [ + "guid#{username}", + 'guidtestuser', + 'guidjeff', + 'guidzack' + ], + }] + end + + + describe 'Creating a user that does not exist' do + # These are the defaults that the provider will use if a user does + # not provide a value + let(:defaults) do + { + 'UniqueID' => '1000', + 'RealName' => resource[:name], + 'PrimaryGroupID' => '20', + 'UserShell' => '/bin/bash', + 'NFSHomeDirectory' => "/Users/#{resource[:name]}" + } + end + + before :each do + # Stub out all calls to dscl with default values from above + defaults.each do |key, val| + provider.expects(:merge_attribute_with_dscl).with('Users', username, key, val) + end + + # Mock the rest of the dscl calls. We can't assume that our Linux + # build system will have the dscl binary + provider.expects(:create_new_user).with(username) + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'GeneratedUID').returns({'dsAttrTypeStandard:GeneratedUID' => ['GUID']}) + provider.expects(:next_system_id).returns('1000') + end + + it 'should not raise any errors when creating a user with default values' do + provider.create + end + + %w{password iterations salt}.each do |value| + it "should call ##{value}= if a #{value} attribute is specified" do + resource[value.intern] = 'somevalue' + setter = (value << '=').intern + provider.expects(setter).with('somevalue') + provider.create + end + end + + it 'should merge the GroupMembership and GroupMembers dscl values if a groups attribute is specified' do + resource[:groups] = 'somegroup' + provider.expects(:merge_attribute_with_dscl).with('Groups', 'somegroup', 'GroupMembership', username) + provider.expects(:merge_attribute_with_dscl).with('Groups', 'somegroup', 'GroupMembers', 'GUID') + provider.create + end + end + + describe 'self#instances' do + it 'should create an array of provider instances' do + provider.class.expects(:get_all_users).returns(['foo', 'bar']) + ['foo', 'bar'].each do |user| + provider.class.expects(:generate_attribute_hash).with(user).returns({}) + end + provider.class.instances.size.should == 2 + end + end + + describe 'self#get_all_users' do + let(:empty_plist) do + ' + + + + + ' + end + + it 'should return a hash of user attributes' do + provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Users').returns(user_plist_xml) + provider.class.get_all_users.should == user_plist_hash + end + + it 'should return a hash when passed an empty plist' do + provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Users').returns(empty_plist) + provider.class.get_all_users.should == {} + end + end + + describe 'self#generate_attribute_hash' do + let(:user_plist_resource) do + { + :ensure => :present, + :provider => :directoryservice, + :groups => 'testgroup,third', + :comment => username, + :password => sha512_password_hash, + :shadowhashdata => sha512_shadowhashdata_hash, + :name => username, + :uid => 1000, + :gid => 22, + :home => user_path + } + end + + before :each do + Facter.expects(:value).with(:macosx_productversion_major).twice.returns('10.7') + provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Users').returns(testuser_plist) + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns(sha512_shadowhashdata_hash).twice + provider.class.expects(:get_list_of_groups).returns(group_plist_hash_guid).twice + provider.class.expects(:convert_binary_to_xml).with(sha512_embedded_bplist).twice.returns(sha512_embedded_bplist_hash) + provider.class.prefetch({}) + end + + it 'should return :uid values as a Fixnum' do + provider.class.generate_attribute_hash(user_plist_hash)[:uid].class.should == Fixnum + end + + it 'should return :gid values as a Fixnum' do + provider.class.generate_attribute_hash(user_plist_hash)[:gid].class.should == Fixnum + end + + it 'should return a hash of resource attributes' do + provider.class.generate_attribute_hash(user_plist_hash).should == user_plist_resource + end + end + + describe '#exists?' do + # This test expects an error to be raised + # I'm PROBABLY doing this wrong... + it 'should return false if the dscl command errors out' do + provider.expects(:dscl).with('.', 'read', user_path).raises(Puppet::ExecutionFailure, 'Dscl Fails') + provider.exists?.should == false + end + + it 'should return true if the dscl command does not error' do + provider.expects(:dscl).with('.', 'read', user_path).returns(user_plist_xml) + provider.exists?.should == true + end + end + + describe '#delete' do + it 'should call dscl when destroying/deleting a resource' do + provider.expects(:dscl).with('.', '-delete', user_path) + provider.delete + end + end + + describe 'the groups property' do + # The below represents the result of running Plist.parse_xml on XML + # data returned from the `dscl -plist . readall /Groups` command. + # (AKA: What the get_list_of_groups method returns) + let(:group_plist_hash) do + [{ + 'dsAttrTypeStandard:RecordName' => ['testgroup'], + 'dsAttrTypeStandard:GroupMembership' => [ + 'testuser', + username, + 'jeff', + 'zack' + ], + 'dsAttrTypeStandard:GroupMembers' => [ + 'guidtestuser', + 'guidjeff', + 'guidzack' + ], + }, + { + 'dsAttrTypeStandard:RecordName' => ['second'], + 'dsAttrTypeStandard:GroupMembership' => [ + username, + 'testuser', + 'jeff', + ], + 'dsAttrTypeStandard:GroupMembers' => [ + 'guidtestuser', + 'guidjeff', + ], + }, + { + 'dsAttrTypeStandard:RecordName' => ['third'], + 'dsAttrTypeStandard:GroupMembership' => [ + 'jeff', + 'zack' + ], + 'dsAttrTypeStandard:GroupMembers' => [ + 'guidjeff', + 'guidzack' + ], + }] + end + + + before :each do + provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Users').returns(testuser_plist) + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns([]) + Facter.expects(:value).with(:macosx_productversion_major).returns('10.7') + end + + it "should return a list of groups if the user's name matches GroupMembership" do + provider.class.expects(:get_list_of_groups).returns(group_plist_hash) + provider.class.prefetch({}).first.groups.should == 'second,testgroup' + end + + it "should return a list of groups if the user's GUID matches GroupMembers" do + provider.class.expects(:get_list_of_groups).returns(group_plist_hash_guid) + provider.class.prefetch({}).first.groups.should == 'testgroup,third' + end + end + + describe '#groups=' do + let(:group_plist_one_two_three) do + [{ + 'dsAttrTypeStandard:RecordName' => ['one'], + 'dsAttrTypeStandard:GroupMembership' => [ + 'jeff', + 'zack' + ], + 'dsAttrTypeStandard:GroupMembers' => [ + 'guidjeff', + 'guidzack' + ], + }, + { + 'dsAttrTypeStandard:RecordName' => ['two'], + 'dsAttrTypeStandard:GroupMembership' => [ + 'jeff', + 'zack', + username + ], + 'dsAttrTypeStandard:GroupMembers' => [ + 'guidjeff', + 'guidzack' + ], + }, + { + 'dsAttrTypeStandard:RecordName' => ['three'], + 'dsAttrTypeStandard:GroupMembership' => [ + 'jeff', + 'zack', + username + ], + 'dsAttrTypeStandard:GroupMembers' => [ + 'guidjeff', + 'guidzack' + ], + }] + end + + before :each do + provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Users').returns(testuser_plist) + provider.class.expects(:get_list_of_groups).returns(group_plist_one_two_three) + end + + it 'should call dscl to add necessary groups' do + Facter.expects(:value).with(:macosx_productversion_major).returns('10.7') + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns([]) + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'GeneratedUID').returns({'dsAttrTypeStandard:GeneratedUID' => ['guidnonexistant_user']}) + provider.expects(:groups).returns('two,three') + provider.expects(:dscl).with('.', '-merge', '/Groups/one', 'GroupMembership', 'nonexistant_user') + provider.expects(:dscl).with('.', '-merge', '/Groups/one', 'GroupMembers', 'guidnonexistant_user') + provider.class.prefetch({}) + provider.groups= 'one,two,three' + end + + #describe how passwords are fetched in 10.5 and 10.6 + ['10.5', '10.6'].each do |os_ver| + it "should call the get_sha1 method on #{os_ver}" do + Facter.expects(:value).with(:macosx_productversion_major).returns(os_ver) + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns([]) + provider.class.expects(:get_sha1).with('0A7D5B63-3AD4-4CA7-B03E-85876F1D1FB3').returns('password') + provider.class.prefetch({}).first.password.should == 'password' + end + end + + it 'should call the get_salted_sha512 method on 10.7 and return the correct hash' do + Facter.expects(:value).with(:macosx_productversion_major).returns('10.7') + provider.class.expects(:convert_binary_to_xml).with(sha512_embedded_bplist).returns(sha512_embedded_bplist_hash) + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'ShadowHashData').returns(sha512_shadowhashdata_hash) + provider.class.prefetch({}).first.password.should == sha512_password_hash + end + + it 'should call the get_salted_sha512_pbkdf2 method on 10.8 and return the correct hash' do + Facter.expects(:value).with(:macosx_productversion_major).returns('10.8') + provider.class.expects(:get_attribute_from_dscl).with('Users', username,'ShadowHashData').returns(pbkdf2_shadowhashdata_hash) + provider.class.expects(:convert_binary_to_xml).with(pbkdf2_embedded_plist).returns(pbkdf2_embedded_bplist_hash) + provider.class.prefetch({}).first.password.should == pbkdf2_password_hash + end + + end + + describe '#password=' do + ['10.5', '10.6'].each do |os_ver| + it "should call write_sha1_hash when setting the password on #{os_ver}" do + Facter.expects(:value).with(:macosx_productversion_major).returns(os_ver) + provider.expects(:write_sha1_hash).with('password') + provider.password = 'password' + end + end + + it 'should call write_password_to_users_plist when setting the password on 10.7' do + Facter.expects(:value).with(:macosx_productversion_major).twice.returns('10.7') + provider.expects(:write_password_to_users_plist).with(sha512_password_hash) + provider.expects(:flush_dscl_cache).twice + provider.password = sha512_password_hash + end + + it 'should call write_password_to_users_plist when setting the password on 10.8' do + Facter.expects(:value).with(:macosx_productversion_major).twice.returns('10.8') + provider.expects(:write_password_to_users_plist).with(pbkdf2_password_hash) + provider.expects(:flush_dscl_cache).twice + provider.password = pbkdf2_password_hash + end + + it "should raise an error on 10.7 if a password hash that doesn't contain 136 characters is passed" do + Facter.expects(:value).with(:macosx_productversion_major).twice.returns('10.7') + expect { provider.password = 'password' }.to raise_error Puppet::Error, /OS X 10\.7 requires a Salted SHA512 hash password of 136 characters\. Please check your password and try again/ + end + + it "should raise an error on 10.8 if a password hash that doesn't contain 256 characters is passed" do + Facter.expects(:value).with(:macosx_productversion_major).twice.returns('10.8') + expect { provider.password = 'password' }.to raise_error Puppet::Error, /OS X versions > 10\.7 require a Salted SHA512 PBKDF2 password hash of 256 characters\. Please check your password and try again\./ + end + end + + describe '#get_list_of_groups' do + # The below value is the result of running `dscl -plist . readall /Groups` + # on an OS X system. + let(:groups_xml) do + ' + + + + + dsAttrTypeStandard:AppleMetaNodeLocation + + /Local/Default + + dsAttrTypeStandard:GeneratedUID + + ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000053 + + dsAttrTypeStandard:Password + + * + + dsAttrTypeStandard:PrimaryGroupID + + 83 + + dsAttrTypeStandard:RealName + + SPAM Assassin Group 2 + + dsAttrTypeStandard:RecordName + + _amavisd + amavisd + + dsAttrTypeStandard:RecordType + + dsRecTypeStandard:Groups + + + + ' + end + + # The below value is the result of executing Plist.parse_xml on + # groups_xml + let(:groups_hash) do + [{ 'dsAttrTypeStandard:AppleMetaNodeLocation' => ['/Local/Default'], + 'dsAttrTypeStandard:GeneratedUID' => ['ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000053'], + 'dsAttrTypeStandard:Password' => ['*'], + 'dsAttrTypeStandard:PrimaryGroupID' => ['83'], + 'dsAttrTypeStandard:RealName' => ['SPAM Assassin Group 2'], + 'dsAttrTypeStandard:RecordName' => ['_amavisd', 'amavisd'], + 'dsAttrTypeStandard:RecordType' => ['dsRecTypeStandard:Groups'] + }] + end + + it 'should return a array of hashes containing group data' do + provider.class.expects(:dscl).with('-plist', '.', 'readall', '/Groups').returns(groups_xml) + provider.class.get_list_of_groups.should == groups_hash + end + end + + describe '#get_attribute_from_dscl' do + # The below value is the result of executing + # `dscl -plist . read /Users/ + + + + dsAttrTypeStandard:GeneratedUID + + DCC660C6-F5A9-446D-B9FF-3C0258AB5BA0 + + + ' + end + + # The below value is the result of parsing user_guid_xml with + # Plist.parse_xml + let(:user_guid_hash) do + { 'dsAttrTypeStandard:GeneratedUID' => ['DCC660C6-F5A9-446D-B9FF-3C0258AB5BA0'] } + end + + it 'should return a hash containing a user\'s dscl attribute data' do + provider.class.expects(:dscl).with('-plist', '.', 'read', user_path, 'GeneratedUID').returns(user_guid_xml) + provider.class.get_attribute_from_dscl('Users', username, 'GeneratedUID').should == user_guid_hash + end + end + + describe '#convert_xml_to_binary' do + # Because this method relies on a binary that only exists on OS X, a stub + # object is needed to expect the calls. This makes testing somewhat...uneventful + let(:stub_io_object) { stub('connection') } + + it 'should use plutil to successfully convert an xml plist to a binary plist' do + IO.expects(:popen).with('plutil -convert binary1 -o - -', 'r+').yields stub_io_object + Plist::Emit.expects(:dump).with('ruby_hash').returns('xml_plist_data') + stub_io_object.expects(:write).with('xml_plist_data') + stub_io_object.expects(:close_write) + stub_io_object.expects(:read).returns('binary_plist_data') + provider.class.convert_xml_to_binary('ruby_hash').should == 'binary_plist_data' + end + end + + describe '#convert_binary_to_xml' do + let(:stub_io_object) { stub('connection') } + + it 'should accept a binary plist and return a ruby hash containing the plist data' do + IO.expects(:popen).with('plutil -convert xml1 -o - -', 'r+').yields stub_io_object + stub_io_object.expects(:write).with('binary_plist_data') + stub_io_object.expects(:close_write) + stub_io_object.expects(:read).returns(user_plist_xml) + provider.class.convert_binary_to_xml('binary_plist_data').should == user_plist_hash + end + end + + describe '#next_system_id' do + it 'should return the next available UID number that is not in the list obtained from dscl and is greater than the passed integer value' do + provider.expects(:dscl).with('.', '-list', '/Users', 'uid').returns("kathee 312\ngary 11\ntanny 33\njohn 9\nzach 5") + provider.next_system_id(30).should == 34 + end + end + + describe '#get_salted_sha512' do + it "should accept a hash whose 'SALTED-SHA512' key contains a StringIO object with a base64 encoded salted-SHA512 password hash and return the hex value of that password hash" do + provider.class.get_salted_sha512(sha512_embedded_bplist_hash).should == sha512_password_hash + end + end + + describe '#get_salted_sha512_pbkdf2' do + it "should accept a hash containing a PBKDF2 password hash, salt, and iterations value and return the correct password hash" do + provider.class.get_salted_sha512_pbkdf2('entropy', pbkdf2_embedded_bplist_hash).should == pbkdf2_password_hash + end + it "should accept a hash containing a PBKDF2 password hash, salt, and iterations value and return the correct salt value" do + provider.class.get_salted_sha512_pbkdf2('salt', pbkdf2_embedded_bplist_hash).should == pbkdf2_salt_value + end + it "should accept a hash containing a PBKDF2 password hash, salt, and iterations value and return the correct iterations value" do + provider.class.get_salted_sha512_pbkdf2('iterations', pbkdf2_embedded_bplist_hash).should == pbkdf2_iterations_value + end + it "should return a Fixnum value when looking up the PBKDF2 iterations value" do + provider.class.get_salted_sha512_pbkdf2('iterations', pbkdf2_embedded_bplist_hash).class.should == Fixnum + end + it "should raise an error if a field other than 'entropy', 'salt', or 'iterations' is passed" do + expect { provider.class.get_salted_sha512_pbkdf2('othervalue', pbkdf2_embedded_bplist_hash) }.to raise_error Puppet::Error, /Puppet has tried to read an incorrect value from the SALTED-SHA512-PBKDF2 hash. Acceptable fields are 'salt', 'entropy', or 'iterations'/ + end + end + + describe '#get_sha1' do + let(:password_hash_file) { '/var/db/shadow/hash/user_guid' } + let(:stub_password_file) { stub('connection') } + + it 'should return a a sha1 hash read from disk' do + File.expects(:exists?).with(password_hash_file).returns(true) + File.expects(:file?).with(password_hash_file).returns(true) + File.expects(:readable?).with(password_hash_file).returns(true) + File.expects(:new).with(password_hash_file).returns(stub_password_file) + stub_password_file.expects(:read).returns('sha1_password_hash') + stub_password_file.expects(:close) + provider.class.get_sha1('user_guid').should == 'sha1_password_hash' + end + + it 'should return nil if the password_hash_file does not exist' do + File.expects(:exists?).with(password_hash_file).returns(false) + provider.class.get_sha1('user_guid').should == nil + end + + it 'should return nil if the password_hash_file is not a file' do + File.expects(:exists?).with(password_hash_file).returns(true) + File.expects(:file?).with(password_hash_file).returns(false) + provider.class.get_sha1('user_guid').should == nil + end + + it 'should raise an error if the password_hash_file is not readable' do + File.expects(:exists?).with(password_hash_file).returns(true) + File.expects(:file?).with(password_hash_file).returns(true) + File.expects(:readable?).with(password_hash_file).returns(false) + expect { provider.class.get_sha1('user_guid').should == nil }.to raise_error Puppet::Error, /Could not read password hash file at #{password_hash_file}/ + end + end + + describe '#write_password_to_users_plist' do + let(:sha512_plist_xml) do + "\n\n\n\n\tKerberosKeys\n\t\n\t\t\n\t\tMIIBS6EDAgEBoIIBQjCCAT4wcKErMCmgAwIBEqEiBCCS/0Im7BAps/YhX/ED\n\t\tKOpDeSMFkUsu3UzEa6gqDu35BKJBMD+gAwIBA6E4BDZMS0RDOlNIQTEuNDM4\n\t\tM0UxNTJEOUQzOTRBQTMyRDEzQUU5OEY2RjZFMUZFOEQwMEY4MWplZmYwYKEb\n\t\tMBmgAwIBEaESBBAk8a3rrFk5mHAdEU5nRgFwokEwP6ADAgEDoTgENkxLREM6\n\t\tU0hBMS40MzgzRTE1MkQ5RDM5NEFBMzJEMTNBRTk4RjZGNkUxRkU4RDAwRjgx\n\t\tamVmZjBooSMwIaADAgEQoRoEGFg71irsV+9ddRNPSn9houo3Q6jZuj55XaJB\n\t\tMD+gAwIBA6E4BDZMS0RDOlNIQTEuNDM4M0UxNTJEOUQzOTRBQTMyRDEzQUU5\n\t\tOEY2RjZFMUZFOEQwMEY4MWplZmY=\n\t\t\n\t\n\tShadowHashData\n\t\n\t\t\n\t\tYnBsaXN0MDDRAQJdU0FMVEVELVNIQTUxMk8QRFNL0iuruijP6becUWe43GTX\n\t\t5WTgOTi2emx41DMnwnB4vbKieVOE4eNHiyocX5c0GX1LWJ6VlZqZ9EnDLsuA\n\t\tNC5Ga9qlCAsZAAAAAAAAAQEAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAGA=\n\t\t\n\t\n\tauthentication_authority\n\t\n\t\t;Kerberosv5;;jeff@LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81;LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81\n\t\t;ShadowHash;HASHLIST:<SALTED-SHA512>\n\t\n\tdsAttrTypeStandard:ShadowHashData\n\t\n\t\t\n\t\tYnBsaXN0MDDRAQJdU0FMVEVELVNIQTUxMk8QRH6n1ZITH1eyyPi9vOyNnfEh\n\t\tKKOGOTpPAMdhm6wmIqRNRRQZ0R2lEtWRWrmOOXGKyUCD/i79a/cQpU1Hf4/3\n\t\tNbElhxktCAsZAAAAAAAAAQEAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAGA=\n\t\t\n\t\n\tgenerateduid\n\t\n\t\t3AC74939-C14F-45DD-B6A9-D1A82373F0B0\n\t\n\tname\n\t\n\t\tjeff\n\t\n\tpasswd\n\t\n\t\t********\n\t\n\tpasswordpolicyoptions\n\t\n\t\t\n\t\tPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NU\n\t\tWVBFIHBsaXN0IFBVQkxJQyAiLS8vQXBwbGUvL0RURCBQTElTVCAxLjAvL0VO\n\t\tIiAiaHR0cDovL3d3dy5hcHBsZS5jb20vRFREcy9Qcm9wZXJ0eUxpc3QtMS4w\n\t\tLmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo8ZGljdD4KCTxrZXk+ZmFp\n\t\tbGVkTG9naW5Db3VudDwva2V5PgoJPGludGVnZXI+MDwvaW50ZWdlcj4KCTxr\n\t\tZXk+ZmFpbGVkTG9naW5UaW1lc3RhbXA8L2tleT4KCTxkYXRlPjIwMDEtMDEt\n\t\tMDFUMDA6MDA6MDBaPC9kYXRlPgoJPGtleT5sYXN0TG9naW5UaW1lc3RhbXA8\n\t\tL2tleT4KCTxkYXRlPjIwMDEtMDEtMDFUMDA6MDA6MDBaPC9kYXRlPgoJPGtl\n\t\teT5wYXNzd29yZFRpbWVzdGFtcDwva2V5PgoJPGRhdGU+MjAxMi0wOC0xMVQw\n\t\tMDozNTo1MFo8L2RhdGU+CjwvZGljdD4KPC9wbGlzdD4K\n\t\t\n\t\n\tuid\n\t\n\t\t28\n\t\n\n" + end + + let(:pbkdf2_plist_xml) do + "\n\n\n\n\tKerberosKeys\n\t\n\t\t\n\t\tMIIBS6EDAgEBoIIBQjCCAT4wcKErMCmgAwIBEqEiBCDrboPy0gxu7oTZR/Pc\n\t\tYdCBC9ivXo1k05gt036/aNe5VqJBMD+gAwIBA6E4BDZMS0RDOlNIQTEuNDEz\n\t\tQTMwRjU5MEVFREM3ODdENTMyOTgxODUwQTk3NTI0NUIwQTcyM2plZmYwYKEb\n\t\tMBmgAwIBEaESBBCm02SYYdsxo2fiDP4KuPtmokEwP6ADAgEDoTgENkxLREM6\n\t\tU0hBMS40MTNBMzBGNTkwRUVEQzc4N0Q1MzI5ODE4NTBBOTc1MjQ1QjBBNzIz\n\t\tamVmZjBooSMwIaADAgEQoRoEGHPBc7Dg7zjaE8g+YXObwupiBLMIlCrN5aJB\n\t\tMD+gAwIBA6E4BDZMS0RDOlNIQTEuNDEzQTMwRjU5MEVFREM3ODdENTMyOTgx\n\t\tODUwQTk3NTI0NUIwQTcyM2plZmY=\n\t\t\n\t\n\tShadowHashData\n\t\n\t\t\n\t\tYnBsaXN0MDDRAQJfEBRTQUxURUQtU0hBNTEyLVBCS0RGMtMDBAUGBwhXZW50\n\t\tcm9weVRzYWx0Wml0ZXJhdGlvbnNPEIAFkK3hnmlTwTWuhyrndhgjXffUbGPe\n\t\tf5oPzfLNnn2F5LfKhoEBI1thWOBaMJgF7kgUsCekvpwj7CkmvIFyJpr/ulya\n\t\tWYXoEJH6aJgHbSl/H6p1+mF1Ue8WcddSAFXEoNl7m5xYBaoyK67bzY7pxSOB\n\t\tFlOsLqnpyNjxrFGaDytZXk8QIJN3xGkIocisLD5FwNRNqK0PzYXsXBTZpZ/8\n\t\tQMnaMfDsEWCwCAsiKTE2QcTnAAAAAAAAAQEAAAAAAAAACQAAAAAAAAAAAAAA\n\t\tAAAAAOo=\n\t\t\n\t\n\tauthentication_authority\n\t\n\t\t;Kerberosv5;;jeff@LKDC:SHA1.413A30F590EEDC787D532981850A975245B0A723;LKDC:SHA1.413A30F590EEDC787D532981850A975245B0A723\n\t\t;ShadowHash;HASHLIST:<SALTED-SHA512-PBKDF2>\n\t\n\tgenerateduid\n\t\n\t\t1CB825D1-2DF7-43CC-B874-DB6BBB76C402\n\t\n\tgid\n\t\n\t\t21\n\t\n\tname\n\t\n\t\tjeff\n\t\n\tpasswd\n\t\n\t\t********\n\t\n\tpasswordpolicyoptions\n\t\n\t\t\n\t\tPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NU\n\t\tWVBFIHBsaXN0IFBVQkxJQyAiLS8vQXBwbGUvL0RURCBQTElTVCAxLjAvL0VO\n\t\tIiAiaHR0cDovL3d3dy5hcHBsZS5jb20vRFREcy9Qcm9wZXJ0eUxpc3QtMS4w\n\t\tLmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo8ZGljdD4KCTxrZXk+ZmFp\n\t\tbGVkTG9naW5Db3VudDwva2V5PgoJPGludGVnZXI+MDwvaW50ZWdlcj4KCTxr\n\t\tZXk+ZmFpbGVkTG9naW5UaW1lc3RhbXA8L2tleT4KCTxkYXRlPjIwMDEtMDEt\n\t\tMDFUMDA6MDA6MDBaPC9kYXRlPgoJPGtleT5sYXN0TG9naW5UaW1lc3RhbXA8\n\t\tL2tleT4KCTxkYXRlPjIwMDEtMDEtMDFUMDA6MDA6MDBaPC9kYXRlPgoJPGtl\n\t\teT5wYXNzd29yZExhc3RTZXRUaW1lPC9rZXk+Cgk8ZGF0ZT4yMDEyLTA3LTI1\n\t\tVDE4OjQ3OjU5WjwvZGF0ZT4KPC9kaWN0Pgo8L3BsaXN0Pgo=\n\t\t\n\t\n\tuid\n\t\n\t\t28\n\t\n\n" + end + + let(:sha512_shadowhashdata) do + { + 'SALTED-SHA512' => StringIO.new('blankvalue') + } + end + + let(:pbkdf2_shadowhashdata) do + { + 'SALTED-SHA512-PBKDF2' => { + 'entropy' => StringIO.new('blank_entropy'), + 'salt' => StringIO.new('blank_salt'), + 'iterations' => 100 + } + } + end + + let(:stub_shadowhashdata) { stub('connection') } + + it 'should call set_salted_sha512 on 10.7 when given a a salted-SHA512 password hash' do + provider.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', "#{users_plist_dir}/nonexistant_user.plist").returns(sha512_plist_xml) + Facter.expects(:value).with(:macosx_productversion_major).returns('10.7') + # The below line is not as tight as I would like. It would be + # nice to set the expectation using .with and passing the hash + # we're expecting, but there are several StringIO objects that + # report with a hex identifier. Even though the string data + # matches, frequently the hex identifiers vary slightly. I + # feel like the work I'd need to do to keep the StringIO objects + # in sync would result in a test with staged data. + provider.expects(:set_salted_sha512) + provider.class.expects(:convert_binary_to_xml).returns(sha512_embedded_bplist_hash) + provider.write_password_to_users_plist(sha512_password_hash) + end + + it 'should call set_salted_pbkdf2 on 10.8 when given a PBKDF2 password hash' do + provider.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', "#{users_plist_dir}/nonexistant_user.plist").returns(pbkdf2_plist_xml) + Facter.expects(:value).with(:macosx_productversion_major).returns('10.8') + # See comment in previous test... + provider.expects(:set_salted_pbkdf2) + provider.class.expects(:convert_binary_to_xml).returns(pbkdf2_embedded_bplist_hash) + provider.write_password_to_users_plist(pbkdf2_password_hash) + end + + it "should delete the SALTED-SHA512 key in the shadow_hash_data hash if it exists on a 10.8 system and write_password_to_users_plist has been called to set the user's password" do + provider.expects(:plutil).with('-convert', 'xml1', '-o', '/dev/stdout', "#{users_plist_dir}/nonexistant_user.plist").returns('xml_data') + Plist.expects(:parse_xml).with('xml_data').returns('ruby_hash') + Facter.expects(:value).with(:macosx_productversion_major).returns('10.8') + provider.expects(:get_shadow_hash_data).with('ruby_hash').returns(stub_shadowhashdata) + stub_shadowhashdata.expects(:[]).with('SALTED-SHA512').returns(true) + stub_shadowhashdata.expects(:delete).with('SALTED-SHA512') + provider.expects(:set_salted_pbkdf2).with('ruby_hash', stub_shadowhashdata, 'entropy', pbkdf2_password_hash) + provider.write_password_to_users_plist(pbkdf2_password_hash) + end + end + + describe '#set_salted_sha512' do + let(:users_plist) { {'ShadowHashData' => [StringIO.new('string_data')] } } + let(:converted_string) { "fqfVkhMfV7LI+L287I2d8SEoo4Y5Ok8Ax2GbrCYipE1FFBnRHaUS1ZFauY45\ncYrJQIP+Lv1r9xClTUd/j/c1sSWHGS0=" } + + it 'should set the SALTED-SHA512 password hash for a user in 10.7 and call the write_users_plist_to_disk method to write the plist to disk' do + Hash.expects(:new).never + Base64.expects(:decode64).with(converted_string).returns(sha512_pw_string) + provider.class.expects(:convert_xml_to_binary).with(sha512_embedded_bplist_hash).returns(sha512_embedded_bplist) + # Again, here's another test that's loose because of StringIO objects... + provider.expects(:write_users_plist_to_disk) + provider.set_salted_sha512(users_plist, sha512_embedded_bplist_hash, sha512_password_hash) + end + + it 'should set the salted-SHA512 password, even if a blank shadow_hash_data hash is passed' do + # The only thing that sets this aside from the previous test is the + # Hash.new call that's expected if a shadow_hash_data argument is + # passed that doesn't have a 'SALTED-SHA512' key. + Hash.expects(:new).returns({}) + Base64.expects(:decode64).with(converted_string).returns(sha512_pw_string) + provider.class.expects(:convert_xml_to_binary).returns(sha512_embedded_bplist) + provider.expects(:write_users_plist_to_disk) + provider.set_salted_sha512(users_plist, false, sha512_password_hash) + end + end + + describe '#set_salted_pbkdf2' do + let(:users_plist) { {'ShadowHashData' => [StringIO.new('string_data')] } } + + # The below are the result of running "[[value].pack("H*")].pack("m").strip" + # where value is a hex string passed by pbkdf2_password_hash and + # pbkdf2_salt_value + let(:converted_pw_string) { "BZCt4Z5pU8E1rocq53YYI1331Gxj3n+aD83yzZ59heS3yoaBASNbYVjgWjCY\nBe5IFLAnpL6cI+wpJryBciaa/7pcmlmF6BCR+miYB20pfx+qdfphdVHvFnHX\nUgBVxKDZe5ucWAWqMiuu282O6cUjgRZTrC6p6cjY8axRmg8rWV4=" } + let(:converted_salt_string) { "k3fEaQihyKwsPkXA1E2orQ/NhexcFNmln/xAydox8Ow=" } + + it "should set the PBKDF2 password hash when the 'entropy' field is passed with a valid password hash" do + Base64.expects(:decode64).with(converted_pw_string).returns(pbkdf2_pw_string) + provider.class.expects(:convert_xml_to_binary).returns(pbkdf2_embedded_plist) + provider.expects(:write_users_plist_to_disk) + users_plist.expects(:[]=).with('passwd', '********') + provider.set_salted_pbkdf2(users_plist, pbkdf2_embedded_bplist_hash, 'entropy', pbkdf2_password_hash) + end + + it "should set the PBKDF2 password hash when the 'salt' field is passed with a valid password hash" do + Base64.expects(:decode64).with(converted_salt_string).returns(pbkdf2_salt_string) + provider.class.expects(:convert_xml_to_binary).returns(pbkdf2_embedded_plist) + provider.expects(:write_users_plist_to_disk) + users_plist.expects(:[]=).with('passwd', '********') + provider.set_salted_pbkdf2(users_plist, pbkdf2_embedded_bplist_hash, 'salt', pbkdf2_salt_value) + end + + it "should set the PBKDF2 password hash when the 'iterations' field is passed with a valid password hash" do + provider.class.expects(:convert_xml_to_binary).returns(pbkdf2_embedded_plist) + provider.expects(:write_users_plist_to_disk) + users_plist.expects(:[]=).with('passwd', '********') + provider.set_salted_pbkdf2(users_plist, pbkdf2_embedded_bplist_hash, 'iterations', pbkdf2_iterations_value) + end + end + + describe '#write_users_plist_to_disk' do + it 'should save the passed plist to disk and convert it to a binary plist' do + Plist::Emit.expects(:save_plist).with(user_plist_xml, "#{users_plist_dir}/nonexistant_user.plist") + provider.expects(:plutil).with('-convert', 'binary1', "#{users_plist_dir}/nonexistant_user.plist") + provider.write_users_plist_to_disk(user_plist_xml) + end + end + + describe '#write_sha1_hash' do + let(:password_hash_dir) { '/var/db/shadow/hash' } + + it "should write the sha1 hash to a file on disk named after the user's GUID and also ensure that ':ShadowHash;' is included in the user's AuthenticationAuthority" do + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'GeneratedUID').returns({'dsAttrTypeStandard:GeneratedUID' => ['GUID']}) + provider.expects(:write_to_file).with("#{password_hash_dir}/GUID", 'sha1_password') + provider.expects(:dscl).with('.', '-merge', user_path, 'AuthenticationAuthority', ';ShadowHash;').returns(true) + provider.write_sha1_hash('sha1_password') + end + + it "should raise an error if Puppet cannot write to the file in /var/db/shadow/hash named after the user's GUID" do + File.expects(:open).with('filename', 'w').raises(Errno::EACCES, 'boom') + expect { provider.write_to_file('filename', 'sha1_password') }.to raise_error Puppet::Error, /Could not write to file filename: Permission denied - boom/ + end + + it "should raise an error if dscl cannot merge ';ShadowHash;' into the user's AuthenticationAuthority" do + provider.class.expects(:get_attribute_from_dscl).with('Users', username, 'GeneratedUID').returns({'dsAttrTypeStandard:GeneratedUID' => ['GUID']}) + provider.expects(:write_to_file).with("#{password_hash_dir}/GUID", 'sha1_password') + provider.expects(:dscl).with('.', '-merge', user_path, 'AuthenticationAuthority', ';ShadowHash;').raises(Puppet::ExecutionFailure, 'boom') + expect { provider.write_sha1_hash('sha1_password') }.to raise_error Puppet::Error, /Could not set the dscl AuthenticationAuthority key with value: ;ShadowHash;/ + end + end + + describe '#merge_attribute_with_dscl' do + it 'should raise an error if a dscl command raises an error' do + provider.expects(:dscl).with('.', '-merge', user_path, 'GeneratedUID', 'GUID').raises(Puppet::ExecutionFailure, 'boom') + expect { provider.merge_attribute_with_dscl('Users', username, 'GeneratedUID', 'GUID') }.to raise_error Puppet::Error, /Could not set the dscl GeneratedUID key with value: GUID/ + end + end +end + +