ruby-pwsh 2.1.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fdd18168a3a6fe49791f6f3452ac2d0a57095e2cc0282ebe87705e57826025a3
4
- data.tar.gz: 55a6ca4cc69c47bac20ae5fce610a8a231163a6d9b433f88ee3478a0ebb2d99b
3
+ metadata.gz: 95f7c58255412ed752ac450fb56bd057a0444b17c92d7092db2cf63baf74f186
4
+ data.tar.gz: 5357910655c947428a6022cc393923882b37ba8f4c0f3059a5d48457e78ec480
5
5
  SHA512:
6
- metadata.gz: 96a53d1e796ae8095549e8208d70889d4955c86fe8da348a37036d3ab9096593a8bebffd75541eacab33d8d0d6e43a07e38be116f544b8c1069066e682c2ec9f
7
- data.tar.gz: 2ea225d33feada65d2075e1a565d57b6d8055fd4742581c7d719bfaacf373b94048eb4fe091442c7ed62ed744e4519f9744a7a72226cb9af58b2d15ad7697332
6
+ metadata.gz: ec67605cc01284688b7addd5418f86d792bd7c605d31db864f13dacad6d6bb2a36c8bba65f79abe683c31a4efd5a2967215efb0fec59185a991ce3c20abd4f8c
7
+ data.tar.gz: e8b9c74b212bafa736a1bac68fa4b42009f5bc492422b86ea2c2b72e9fbb4644aae056a88134d4d04c04d302a3820a1e004e1af82c355102334c94ade6f330a6
@@ -60,7 +60,10 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
60
60
  # If the resource is meant to be absent, skip canonicalization and rely on the manifest
61
61
  # value; there's no reason to compare system state to desired state for casing if the
62
62
  # resource is being removed.
63
- if r[:dsc_ensure] == 'absent'
63
+ # In resource validation mode, DSC Test decides whether the resource is in the desired state,
64
+ # so the casing from the system is not needed either: get() runs Test first and only calls
65
+ # the Get method when Test fails.
66
+ if r[:dsc_ensure] == 'absent' || r[:validation_mode] == 'resource'
64
67
  canonicalized = r.dup
65
68
  @cached_canonicalized_resource << r.dup
66
69
  else
@@ -139,38 +142,15 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
139
142
  # passed to the invocable_resource method.
140
143
  context.debug('Collecting data from the DSC Resource')
141
144
 
142
- # If the resource has already been queried, do not bother querying for it again
143
- cached_results = fetch_cached_hashes(@cached_query_results, names)
144
- return cached_results unless cached_results.empty?
145
-
146
- # Use the raw system state from canonicalize's Get call if available.
147
- # @cached_canonicalize_results has the unmodified DSC Get response (before
148
- # canonicalize normalized casing). This gives the Resource API real "is" data
149
- # with all property values, enabling per-property "Changed from" reporting.
150
- unless @cached_canonicalize_results.empty?
151
- canon_results = fetch_cached_hashes(@cached_canonicalize_results, names)
152
- unless canon_results.empty?
153
- # Cache these as query results too so subsequent get() calls find them
154
- canon_results.each do |r|
155
- @cached_query_results << r.dup if fetch_cached_hashes(@cached_query_results, [r]).empty?
156
- end
157
- return canon_results
158
- end
159
- end
160
-
161
- if @cached_canonicalized_resource.empty?
162
- mandatory_properties = {}
163
- else
164
- canonicalized_resource = @cached_canonicalized_resource[0].dup
165
- mandatory_properties = canonicalized_resource.select do |attribute, _value|
166
- (mandatory_get_attributes(context) - namevar_attributes(context)).include?(attribute)
167
- end
168
- # If dsc_psdscrunascredential was specified, re-add it here.
169
- mandatory_properties[:dsc_psdscrunascredential] = canonicalized_resource[:dsc_psdscrunascredential] if canonicalized_resource.key?(:dsc_psdscrunascredential)
170
- end
171
- names.collect do |name|
145
+ names.flat_map do |name|
172
146
  name = { name: name } if name.is_a? String
173
- invoke_get_method(context, name.merge(mandatory_properties))
147
+ cached_results = cached_get_results(name)
148
+ next cached_results unless cached_results.empty?
149
+
150
+ state_from_test = resource_mode_state_from_test(context, name)
151
+ next [state_from_test] unless state_from_test.nil?
152
+
153
+ [invoke_get_method(context, name.merge(mandatory_get_properties(context, name)))]
174
154
  end
175
155
  end
176
156
 
@@ -491,23 +471,97 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
491
471
  # @param is_value [Object] the current value from a fresh DSC Get
492
472
  # @param should_value [Object] the desired value from the Puppet manifest
493
473
  # @return [Boolean] true if the values are equivalent
494
- def values_equal?(is_value, should_value)
474
+ def values_equal?(is_value, should_value, embedded: false)
495
475
  return true if is_value == should_value
496
476
 
497
- # Handle nil/empty equivalence
498
- is_empty = is_value.nil? || (is_value.respond_to?(:empty?) && is_value.empty?)
499
- should_empty = should_value.nil? || (should_value.respond_to?(:empty?) && should_value.empty?)
500
- return true if is_empty && should_empty
477
+ # Handle nil/empty equivalence. Treating nil and '' as equal is intentional:
478
+ # PowerShell returns $null for empty strings (see invoke_dsc_resource_functions.ps1),
479
+ # so a fresh DSC Get cannot tell them apart. Without this, a manifest value of ''
480
+ # reports a corrective change on every run.
481
+ return true if blank_value?(is_value) && blank_value?(should_value)
482
+
483
+ # DSC Get returns optional fields omitted from the manifest for embedded
484
+ # CIM instances. Treat desired hashes as partial hashes in this case.
485
+ return embedded_value_equal?(is_value, should_value) if embedded
501
486
 
502
487
  # Normalize and compare: sort for order-insensitive array/hash comparison,
503
488
  # downcase for case-insensitive string comparison, handles nested structures.
504
489
  same?(recursively_downcase(is_value), recursively_downcase(should_value))
505
490
  end
506
491
 
492
+ # Recursively compare an embedded CIM value. Additional keys returned by DSC
493
+ # are ignored because they were not explicitly managed by the manifest.
494
+ # Empty values follow the same rule as top-level properties at every level:
495
+ # PowerShell also returns $null for empty strings inside CIM instances, and a
496
+ # missing key is treated as nil. A nil desired field is not managed, since DSC
497
+ # cannot tell it apart from an omitted field.
498
+ def embedded_value_equal?(actual, desired)
499
+ return true if blank_value?(actual) && blank_value?(desired)
500
+
501
+ case desired
502
+ when Hash
503
+ return false unless actual.is_a?(Hash)
504
+
505
+ actual = with_default_ensure(actual)
506
+ with_default_ensure(desired).all? do |desired_key, desired_value|
507
+ # A nil (undef) field is not managed, like a field omitted from the manifest.
508
+ next true if desired_value.nil?
509
+
510
+ actual_key = actual.keys.find do |key|
511
+ key.to_s.casecmp?(desired_key.to_s)
512
+ end
513
+
514
+ embedded_value_equal?(actual_key.nil? ? nil : actual[actual_key], desired_value)
515
+ end
516
+ when Array
517
+ return false unless actual.is_a?(Array)
518
+ return false unless actual.length == desired.length
519
+
520
+ embedded_arrays_equal?(actual, desired)
521
+ else
522
+ same?(
523
+ recursively_downcase(actual),
524
+ recursively_downcase(desired)
525
+ )
526
+ end
527
+ end
528
+
529
+ # Match each desired entry to its own actual entry, without depending on
530
+ # their order. Uses Kuhn's matching: an actual entry already taken can be
531
+ # freed if the desired entry holding it can move to another entry it also
532
+ # matches. This avoids trying every ordering of the entries.
533
+ def embedded_arrays_equal?(actual, desired)
534
+ candidates = desired.map do |desired_value|
535
+ actual.each_index.select { |index| embedded_value_equal?(actual[index], desired_value) }
536
+ end
537
+ owners = {}
538
+
539
+ desired.each_index.all? do |desired_index|
540
+ assign_embedded_entry(desired_index, candidates, owners, {})
541
+ end
542
+ end
543
+
544
+ # Try to give the desired entry an actual entry, moving other desired
545
+ # entries to another of their candidates when needed.
546
+ def assign_embedded_entry(desired_index, candidates, owners, visited)
547
+ candidates[desired_index].any? do |actual_index|
548
+ next false if visited[actual_index]
549
+
550
+ visited[actual_index] = true
551
+ next false unless owners[actual_index].nil? ||
552
+ assign_embedded_entry(owners[actual_index], candidates, owners, visited)
553
+
554
+ owners[actual_index] = desired_index
555
+ true
556
+ end
557
+ end
558
+
507
559
  # Determine if the DSC Resource is in the desired state, using fresh DSC Get
508
560
  # results to provide accurate property comparison and real change messages.
509
561
  #
510
- # For validation_mode: resource, delegates entirely to DSC Test (unchanged).
562
+ # For validation_mode: resource, DSC Test decides. When Test fails, the fresh
563
+ # Get comparison below reports which properties differ; if it shows none, one
564
+ # managed property is still reported as changed so that Set runs.
511
565
  #
512
566
  # For validation_mode: property (default), performs a fresh DSC Get (one per
513
567
  # resource, cached) that bypasses the get()/canonicalize pipeline, then compares
@@ -541,6 +595,63 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
541
595
 
542
596
  private
543
597
 
598
+ # Returns the properties that Get needs besides the namevars (and the credential, if any), taken
599
+ # from the canonicalized resource matching the name hash, so that each resource gets its own
600
+ # values. Falls back on the first canonicalized resource, as before, when none matches.
601
+ #
602
+ # @param context [Object] the Puppet runtime context to operate in and send feedback to
603
+ # @param name [Hash] the name hash for the resource
604
+ # @return [Hash] the mandatory Get properties to merge into the name hash
605
+ def mandatory_get_properties(context, name)
606
+ return {} if @cached_canonicalized_resource.empty?
607
+
608
+ canonicalized_resource = @cached_canonicalized_resource.find { |resource| (name.to_a - resource.to_a).empty? } ||
609
+ @cached_canonicalized_resource[0]
610
+ mandatory_properties = canonicalized_resource.select do |attribute, _value|
611
+ (mandatory_get_attributes(context) - namevar_attributes(context)).include?(attribute)
612
+ end
613
+ # If dsc_psdscrunascredential was specified, re-add it here.
614
+ mandatory_properties[:dsc_psdscrunascredential] = canonicalized_resource[:dsc_psdscrunascredential] if canonicalized_resource.key?(:dsc_psdscrunascredential)
615
+ mandatory_properties
616
+ end
617
+
618
+ # Returns the cached state of one resource, if any: the result of an earlier query, else the raw
619
+ # system state from canonicalize's Get call (the unmodified DSC Get response, before canonicalize
620
+ # normalized casing), which gives the Resource API real "is" data for per-property change reports.
621
+ #
622
+ # @param name [Hash] the name hash for the resource
623
+ # @return [Array] the cached hashes matching the name hash, empty if none
624
+ def cached_get_results(name)
625
+ cached_results = fetch_cached_hashes(@cached_query_results, [name])
626
+ return cached_results unless cached_results.empty? && !@cached_canonicalize_results.empty?
627
+
628
+ canon_results = fetch_cached_hashes(@cached_canonicalize_results, [name])
629
+ canon_results.each do |r|
630
+ @cached_query_results << r.dup if fetch_cached_hashes(@cached_query_results, [r]).empty?
631
+ end
632
+ canon_results
633
+ end
634
+
635
+ # Resource validation mode: DSC Test decides whether the resource is in the desired state, so when it
636
+ # passes, the desired values are the current state and no Get call is needed (one DSC call instead of
637
+ # two for an in-sync resource). When Test fails, the caller falls back on the Get method, to report
638
+ # the differences and to choose between create, update and delete.
639
+ #
640
+ # @param context [Object] the Puppet runtime context to operate in and send feedback to
641
+ # @param name [Hash] the name hash for the resource
642
+ # @return [Hash, nil] the desired state when DSC Test passes, nil otherwise
643
+ def resource_mode_state_from_test(context, name)
644
+ should = @cached_canonicalized_resource.find do |resource|
645
+ resource[:validation_mode] == 'resource' && resource[:dsc_ensure] != 'absent' && (name.to_a - resource.to_a).empty?
646
+ end
647
+ return nil if should.nil?
648
+ return nil unless invoke_test_method(context, name, should) == true
649
+
650
+ current = should.reject { |key, _value| Puppet::Type.metaparam?(key) }
651
+ @cached_query_results << current.dup
652
+ current
653
+ end
654
+
544
655
  # Resource validation mode: DSC Test is the authority on overall sync state.
545
656
  def insync_resource_mode(context, name, property_name, should_hash)
546
657
  should_value = should_hash.is_a?(Hash) ? should_hash[property_name] : nil
@@ -550,12 +661,32 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
550
661
 
551
662
  return true if in_sync
552
663
 
553
- # DSC Test says out of sync. Suppress non-dsc_ and nil/empty properties.
664
+ # DSC Test says out of sync. Suppress non-dsc_ and unset properties.
554
665
  return true unless property_name.to_s.start_with?('dsc_')
555
- return true if should_value.nil? || (should_value.respond_to?(:empty?) && should_value.empty?)
666
+ return true if skip_empty_should_value?(should_value)
556
667
 
557
668
  # Fresh Get comparison for dsc_ properties with values
558
- compare_fresh_value(context, name, property_name, should_hash, report_on_failure: true)
669
+ result = compare_fresh_value(context, name, property_name, should_hash, report_on_failure: true)
670
+ return result unless result == true && in_sync == false && carries_failed_test?(context, name, property_name, should_hash)
671
+
672
+ @insync_property_cache["#{name.is_a?(Hash) ? name[:name] : name}_#{property_name}"] = true
673
+ [false, 'DSC Test reported the resource out of sync; the difference may be in array order, string case or a property Get does not return']
674
+ end
675
+
676
+ # DSC Test failed, but the fresh Get comparison can show no difference: it ignores array
677
+ # order and string case, and Get may not return every property that Test checks. Puppet
678
+ # only calls Set when a property is out of sync, so when no managed property differs,
679
+ # the first one is reported as changed.
680
+ def carries_failed_test?(context, name, property_name, should_hash)
681
+ fresh_state = get_cached_fresh_state(context, name, should_hash)
682
+ attributes = context.type.attributes
683
+ managed = should_hash.select do |key, value|
684
+ key.to_s.start_with?('dsc_') && !skip_empty_should_value?(value) &&
685
+ attributes.key?(key) && attributes[key][:behaviour].nil?
686
+ end
687
+ return false if managed.any? { |key, value| !fresh_value_equal?(context, key, fresh_state[key], value) }
688
+
689
+ managed.keys.first == property_name
559
690
  end
560
691
 
561
692
  # Property validation mode: only intervene for dsc_ properties with a desired value.
@@ -563,11 +694,37 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
563
694
  return nil unless property_name.to_s.start_with?('dsc_')
564
695
 
565
696
  should_value = should_hash.is_a?(Hash) ? should_hash[property_name] : nil
566
- return nil if should_value.nil? || (should_value.respond_to?(:empty?) && should_value.empty?)
697
+ return nil if skip_empty_should_value?(should_value)
567
698
 
568
699
  compare_fresh_value(context, name, property_name, should_hash, report_on_failure: false)
569
700
  end
570
701
 
702
+ # Whether a desired value should be left out of the fresh Get comparison:
703
+ # nil and empty collections mean the property is not managed. An empty String
704
+ # is an explicit, valid DSC value (e.g. ManagedRuntimeVersion = '' for
705
+ # "No Managed Code") and must be compared.
706
+ def skip_empty_should_value?(value)
707
+ return true if value.nil?
708
+
709
+ !value.is_a?(String) && value.respond_to?(:empty?) && value.empty?
710
+ end
711
+
712
+ # Whether a value is nil or empty ('', [], {}).
713
+ def blank_value?(value)
714
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
715
+ end
716
+
717
+ # DSC defaults a nested Ensure to Present, and some resources don't return it
718
+ # (or return it as nil). Fill it in on both sides so an entry reported as
719
+ # Absent is not ignored when the manifest omits Ensure. Hashes without an
720
+ # Ensure field get the same value on both sides, so they are not affected.
721
+ def with_default_ensure(hash)
722
+ ensure_key = hash.keys.find { |key| key.to_s.casecmp?('ensure') } || 'ensure'
723
+ return hash unless blank_value?(hash[ensure_key])
724
+
725
+ hash.merge(ensure_key => 'Present')
726
+ end
727
+
571
728
  # Shared fresh Get comparison for both validation modes.
572
729
  def compare_fresh_value(context, name, property_name, should_hash, report_on_failure:)
573
730
  should_value = should_hash.is_a?(Hash) ? should_hash[property_name] : nil
@@ -584,12 +741,19 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
584
741
  end
585
742
 
586
743
  fresh_value = fresh_state[property_name]
587
- return true if values_equal?(fresh_value, should_value)
744
+ return true if fresh_value_equal?(context, property_name, fresh_value, should_value)
588
745
 
589
746
  @insync_property_cache[property_key] = true
590
747
  [false, "#{property_name} changed '#{fresh_value}' to '#{should_value}'"]
591
748
  end
592
749
 
750
+ # Compare a value from the fresh Get with the desired value, as a partial hash
751
+ # for embedded CIM instances.
752
+ def fresh_value_equal?(context, property_name, fresh_value, should_value)
753
+ attribute = context.type.attributes[property_name] || {}
754
+ values_equal?(fresh_value, should_value, embedded: attribute[:mof_is_embedded] == true)
755
+ end
756
+
593
757
  public
594
758
 
595
759
  # Invokes the `Get` method, passing the name_hash as the properties to use with `Invoke-DscResource`
@@ -746,7 +910,9 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
746
910
  context.debug("Invoking Test Method for '#{name}' with #{should.inspect}")
747
911
 
748
912
  test_props = should.select { |k, _v| k.to_s =~ /^dsc_/ }
749
- data = invoke_dsc_resource(context, name, test_props, 'test')
913
+ # invoke_dsc_resource reads the timeout and the credential from the name hash
914
+ name_hash = name.merge(should.slice(:dsc_timeout, :dsc_psdscrunascredential).compact)
915
+ data = invoke_dsc_resource(context, name_hash, test_props, 'test')
750
916
  # Something went wrong with Invoke-DscResource; fall back on property state comparisons
751
917
  return nil if data.nil?
752
918
 
@@ -779,10 +945,11 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
779
945
  next if k == :dsc_psdscrunascredential && v.nil?
780
946
 
781
947
  resource[:parameters][k] = {}
782
- resource[:parameters][k][:value] = v
783
948
  %i[mof_type mof_is_embedded].each do |ky|
784
949
  resource[:parameters][k][ky] = context.type.definition[:attributes][k][ky]
785
950
  end
951
+ embedded_cim = resource[:parameters][k][:mof_is_embedded] && resource[:parameters][k][:mof_type] != 'PSCredential'
952
+ resource[:parameters][k][:value] = embedded_cim ? remove_nil_fields(v) : v
786
953
  end
787
954
  resource[:dsc_invoke_method] = dsc_invoke_method
788
955
 
@@ -952,6 +1119,22 @@ class Puppet::Provider::DscBaseProvider # rubocop:disable Metrics/ClassLength
952
1119
  recursively_sort(value2) == recursively_sort(value1)
953
1120
  end
954
1121
 
1122
+ # Remove nil (undef) fields from an embedded CIM instance value. DSC treats them
1123
+ # like omitted fields, and they cannot be formatted to PowerShell.
1124
+ #
1125
+ # @param value [Object] the embedded CIM instance value (hash, array of hashes, or scalar)
1126
+ # @return [Object] the value without nil hash fields, at any nesting level
1127
+ def remove_nil_fields(value)
1128
+ case value
1129
+ when Hash
1130
+ value.compact.transform_values { |field| remove_nil_fields(field) }
1131
+ when Array
1132
+ value.map { |item| remove_nil_fields(item) }
1133
+ else
1134
+ value
1135
+ end
1136
+ end
1137
+
955
1138
  # Parses the DSC resource type definition to retrieve the names of any attributes which are specified as mandatory for get operations
956
1139
  #
957
1140
  # @param context [Object] the Puppet runtime context to operate in and send feedback to
data/lib/pwsh/version.rb CHANGED
@@ -2,5 +2,5 @@
2
2
 
3
3
  module Pwsh
4
4
  # The version of the ruby-pwsh gem
5
- VERSION = '2.1.0'
5
+ VERSION = '2.1.2'
6
6
  end
data/lib/pwsh.rb CHANGED
@@ -531,11 +531,14 @@ module Pwsh
531
531
  def drain_pipe_until_signaled(pipe, signal)
532
532
  output = []
533
533
 
534
- read_from_pipe(pipe) { |s| output << s } while signal.locked?
534
+ # These pipes usually stay empty: poll them every 0.01 s so the end of the call is seen at once,
535
+ # instead of up to 0.1 s later with the default read_from_pipe timeout
536
+ read_from_pipe(pipe, 0.01) { |s| output << s } while signal.locked?
535
537
 
536
538
  # There's ultimately a bit of a race here
537
- # Read one more time after signal is received
538
- read_from_pipe(pipe, 0) { |s| output << s } while self.class.readable?(pipe)
539
+ # Read one more time after signal is received, without waiting for more data:
540
+ # the default 0.5 s timeout would delay every call, since these pipes usually stay empty
541
+ read_from_pipe(pipe, 0) { |s| output << s } while self.class.readable?(pipe, 0)
539
542
 
540
543
  # String has been binary up to this point, so force UTF-8 now
541
544
  output == [] ? [] : [output.join.force_encoding(Encoding::UTF_8)]
@@ -41,15 +41,23 @@ function Reset-ProcessEnvironmentVariables {
41
41
  # remote PowerShell session.
42
42
  # The least descructive way to avoid this is to filter out SystemRoot when pulling our current list
43
43
  # of environment variables. Then we can continue safely with the removal.
44
- $CurrentEnvironmentVariables = Get-ChildItem -Path Env:\* |
45
- Where-Object {$_.Name -ne "SystemRoot"}
44
+ # Only touch the variables that differ from the cache: same final state as deleting every variable
45
+ # and re-adding the cached ones, without hundreds of Remove-Item / Set-Item calls on each invocation.
46
+ # Environment variable names are case-insensitive on Windows only, so the cache compares them the same way.
47
+ if ([Environment]::OSVersion.Platform -eq 'Win32NT') {
48
+ $Comparer = [StringComparer]::OrdinalIgnoreCase
49
+ } else {
50
+ $Comparer = [StringComparer]::Ordinal
51
+ }
52
+ $Cached = New-Object -TypeName System.Collections.Hashtable -ArgumentList $Comparer
53
+ $CachedEnvironmentVariables | ForEach-Object -Process { $Cached[$_.Name] = $_.Value }
46
54
 
47
- # Delete existing environment variables
48
- $CurrentEnvironmentVariables |
55
+ @(Get-ChildItem -Path Env:\*) |
56
+ Where-Object { $_.Name -ne "SystemRoot" -and -not $Cached.ContainsKey($_.Name) } |
49
57
  ForEach-Object -Process { Remove-Item -Path "ENV:\$($_.Name)" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Recurse }
50
58
 
51
- # Re-add the cached environment variables
52
59
  $CachedEnvironmentVariables |
60
+ Where-Object { [Environment]::GetEnvironmentVariable($_.Name, 'Process') -cne $_.Value } |
53
61
  ForEach-Object -Process { Set-Item -Path "Env:\$($_.Name)" -Value $_.Value }
54
62
  }
55
63
 
@@ -116,6 +116,16 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
116
116
  end
117
117
  end
118
118
 
119
+ context 'when a manifest resource uses the resource validation mode' do
120
+ let(:manifest_resource) { base_resource.merge({ dsc_property: 'FooBar', validation_mode: 'resource' }) }
121
+ let(:cached_canonicalized_resource) { [] }
122
+
123
+ it 'keeps the manifest values without calling the Get method' do
124
+ expect(provider).not_to receive(:invoke_get_method_for_canonicalize)
125
+ expect(canonicalized_resource).to eq([manifest_resource])
126
+ end
127
+ end
128
+
119
129
  context 'when a manifest resource is in the canonicalized resource cache' do
120
130
  let(:manifest_resource) { base_resource.merge({ dsc_property: 'FooBar' }) }
121
131
  let(:expected_resource) { base_resource.merge({ dsc_property: 'foobar' }) }
@@ -148,6 +158,17 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
148
158
  allow(provider).to receive(:enum_attributes).and_return([])
149
159
  end
150
160
 
161
+ context 'when the manifest resource has meta parameters with mixed casing' do
162
+ let(:manifest_resource) do
163
+ base_resource.merge({ dsc_property: 'bar', require: 'Service[MyService]', tag: ['MyTag'], alias: 'MyAlias' })
164
+ end
165
+ let(:actual_resource) { base_resource.merge({ dsc_property: 'Bar' }) }
166
+
167
+ it 'preserves the casing of the meta parameters' do
168
+ expect(canonicalized_resource.first).to include(require: 'Service[MyService]', tag: ['MyTag'], alias: 'MyAlias')
169
+ end
170
+ end
171
+
151
172
  context 'when canonicalizing property values' do
152
173
  let(:manifest_resource) { base_resource.merge({ dsc_property: 'bar' }) }
153
174
 
@@ -278,6 +299,56 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
278
299
  expect(provider).to receive(:invoke_get_method).with(context, { name: 'foo', dsc_some_parameter: 'baz' }).and_return({ name: 'foo', property: 'bar' })
279
300
  expect(provider.get(context, [{ name: 'foo' }])).to eq([{ name: 'foo', property: 'bar' }])
280
301
  end
302
+
303
+ it 'takes the mandatory properties from the canonicalized resource with the same name' do
304
+ provider.instance_variable_set(:@cached_canonicalized_resource, [{ name: 'foo', dsc_path: 'C:\\foo' }, { name: 'bar', dsc_path: 'C:\\bar' }])
305
+ allow(context).to receive(:debug)
306
+ allow(provider).to receive_messages(fetch_cached_hashes: [], namevar_attributes: [:name], mandatory_get_attributes: [:dsc_path])
307
+ expect(provider).to receive(:invoke_get_method).with(context, { name: 'bar', dsc_path: 'C:\\bar' }).and_return({ name: 'bar' })
308
+ provider.get(context, [{ name: 'bar' }])
309
+ end
310
+
311
+ it 'calls the Get method for the names missing from the canonicalize cache' do
312
+ provider.instance_variable_set(:@cached_canonicalize_results, [{ name: 'foo', dsc_setting: 'Foo' }])
313
+ allow(context).to receive(:debug)
314
+ expect(provider).to receive(:invoke_get_method).with(context, { name: 'bar' }).and_return({ name: 'bar', dsc_setting: 'Bar' })
315
+ expect(provider.get(context, [{ name: 'foo' }, { name: 'bar' }])).to eq([{ name: 'foo', dsc_setting: 'Foo' }, { name: 'bar', dsc_setting: 'Bar' }])
316
+ end
317
+ end
318
+
319
+ describe '.get in the resource validation mode' do
320
+ let(:should_hash) { { name: 'foo', dsc_name: 'foo', dsc_setting: 'Foo', validation_mode: 'resource', noop: true } }
321
+
322
+ before do
323
+ allow(context).to receive(:debug)
324
+ allow(provider).to receive(:mandatory_get_attributes).and_return([])
325
+ allow(provider).to receive(:namevar_attributes).and_return(%i[name dsc_name])
326
+ provider.instance_variable_set(:@cached_canonicalized_resource, [should_hash])
327
+ end
328
+
329
+ after do
330
+ provider.instance_variable_set(:@cached_canonicalized_resource, [])
331
+ provider.instance_variable_set(:@cached_query_results, [])
332
+ end
333
+
334
+ it 'returns the desired state without calling the Get method when DSC Test passes' do
335
+ expect(provider).to receive(:invoke_test_method).with(context, { name: 'foo' }, should_hash).and_return(true)
336
+ expect(provider).not_to receive(:invoke_get_method)
337
+ expect(provider.get(context, [{ name: 'foo' }])).to eq([should_hash.reject { |key, _value| key == :noop }])
338
+ end
339
+
340
+ it 'calls the Get method when DSC Test fails' do
341
+ expect(provider).to receive(:invoke_test_method).and_return([false, 'not in the desired state'])
342
+ expect(provider).to receive(:invoke_get_method).with(context, { name: 'foo' }).and_return({ name: 'foo', dsc_setting: 'Bar' })
343
+ expect(provider.get(context, [{ name: 'foo' }])).to eq([{ name: 'foo', dsc_setting: 'Bar' }])
344
+ end
345
+
346
+ it 'calls the Get method when the resource is meant to be absent' do
347
+ provider.instance_variable_set(:@cached_canonicalized_resource, [should_hash.merge(dsc_ensure: 'absent')])
348
+ expect(provider).not_to receive(:invoke_test_method)
349
+ expect(provider).to receive(:invoke_get_method).and_return({ name: 'foo', dsc_ensure: 'absent' })
350
+ provider.get(context, [{ name: 'foo' }])
351
+ end
281
352
  end
282
353
 
283
354
  describe '.set' do
@@ -414,6 +485,10 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
414
485
 
415
486
  before do
416
487
  allow(context).to receive(:debug)
488
+ allow(context).to receive(:type).and_return(type)
489
+ allow(type).to receive(:attributes).and_return(
490
+ dsc_setting: { mof_is_embedded: false }
491
+ )
417
492
  end
418
493
 
419
494
  context 'when the corrective check is detected' do
@@ -468,6 +543,81 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
468
543
  result = provider.send(:insync?, context, name, :dsc_setting, is_hash, should_hash_nil)
469
544
  expect(result).to be true
470
545
  end
546
+
547
+ # '' is a valid DSC value (e.g. dsc_managedruntimeversion => '' for
548
+ # "No Managed Code"), so it must be compared instead of suppressed.
549
+ it 'reports a change when should_value is an empty string and the system has a value' do
550
+ should_hash_empty = should_hash.merge(dsc_setting: '')
551
+ allow(provider).to receive(:get_cached_fresh_state).and_return(name: 'foo', dsc_setting: 'v4.0')
552
+ result = provider.send(:insync?, context, name, :dsc_setting, is_hash, should_hash_empty)
553
+ expect(result).to eq([false, "dsc_setting changed 'v4.0' to ''"])
554
+ end
555
+
556
+ # The fresh Get comparison ignores array order and string case, so it can find no
557
+ # difference although Test failed. One property must still be reported, or Set never runs.
558
+ context 'when the fresh Get shows no difference on any managed property' do
559
+ let(:should_hash) do
560
+ { name: 'foo', dsc_interfacealias: 'Ethernet', dsc_address: ['10.0.0.1', '10.0.0.2'], dsc_validate: false,
561
+ dsc_psdscrunascredential: nil, validation_mode: 'resource' }
562
+ end
563
+ let(:fresh_state) { { name: 'foo', dsc_interfacealias: 'Ethernet', dsc_address: ['10.0.0.2', '10.0.0.1'], dsc_validate: false } }
564
+ let(:message) do
565
+ 'DSC Test reported the resource out of sync; the difference may be in array order, string case or a property Get does not return'
566
+ end
567
+
568
+ before do
569
+ allow(type).to receive(:attributes).and_return(
570
+ dsc_interfacealias: { behaviour: :namevar },
571
+ dsc_address: {},
572
+ dsc_validate: {},
573
+ dsc_psdscrunascredential: { behaviour: :parameter }
574
+ )
575
+ allow(provider).to receive(:get_cached_fresh_state).and_return(fresh_state)
576
+ end
577
+
578
+ it 'reports the first managed property as changed' do
579
+ expect(provider.send(:insync?, context, name, :dsc_address, is_hash, should_hash)).to eq([false, message])
580
+ expect(provider.instance_variable_get(:@insync_property_cache)).to have_key('foo_dsc_address')
581
+ end
582
+
583
+ it 'returns true for the other managed properties' do
584
+ expect(provider.send(:insync?, context, name, :dsc_validate, is_hash, should_hash)).to be true
585
+ end
586
+
587
+ it 'returns nil on the corrective change check that follows' do
588
+ provider.send(:insync?, context, name, :dsc_address, is_hash, should_hash)
589
+ expect(provider.send(:insync?, context, name, :dsc_address, is_hash, should_hash)).to be_nil
590
+ end
591
+
592
+ it 'never reports a namevar or a parameter' do
593
+ expect(provider.send(:insync?, context, name, :dsc_interfacealias, is_hash, should_hash)).to be true
594
+ expect(provider.send(:carries_failed_test?, context, name, :dsc_psdscrunascredential, should_hash)).to be false
595
+ end
596
+ end
597
+
598
+ context 'when the fresh Get shows a difference on another managed property' do
599
+ let(:should_hash) { { name: 'foo', dsc_address: ['10.0.0.1', '10.0.0.2'], dsc_validate: true, validation_mode: 'resource' } }
600
+
601
+ before do
602
+ allow(type).to receive(:attributes).and_return(dsc_address: {}, dsc_validate: {})
603
+ allow(provider).to receive(:get_cached_fresh_state)
604
+ .and_return(name: 'foo', dsc_address: ['10.0.0.2', '10.0.0.1'], dsc_validate: false)
605
+ end
606
+
607
+ it 'reports only the property that differs' do
608
+ expect(provider.send(:insync?, context, name, :dsc_address, is_hash, should_hash)).to be true
609
+ expect(provider.send(:insync?, context, name, :dsc_validate, is_hash, should_hash)).to eq([false, "dsc_validate changed 'false' to 'true'"])
610
+ end
611
+ end
612
+ end
613
+
614
+ context 'when DSC Test returns an error' do
615
+ it 'keeps the fresh Get comparison without forcing a change' do
616
+ allow(provider).to receive(:fetch_cached_hashes).and_return([])
617
+ allow(provider).to receive(:invoke_test_method).and_return(nil)
618
+ allow(provider).to receive(:get_cached_fresh_state).and_return(name: 'foo', dsc_setting: 'foo')
619
+ expect(provider.send(:insync?, context, name, :dsc_setting, is_hash, should_hash)).to be true
620
+ end
471
621
  end
472
622
  end
473
623
 
@@ -492,9 +642,36 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
492
642
  end
493
643
  end
494
644
 
645
+ # '' is a valid DSC value (e.g. dsc_managedruntimeversion => '' for
646
+ # "No Managed Code"), so it must be compared instead of skipped.
495
647
  context 'when should_value is empty string' do
648
+ let(:should_hash_empty) { should_hash.merge(dsc_setting: '') }
649
+
650
+ it 'returns true when the system value is also empty' do
651
+ # PowerShell returns $null for an empty string, so the fresh Get gives nil.
652
+ allow(provider).to receive(:get_cached_fresh_state).and_return(name: 'foo', dsc_setting: nil)
653
+ result = provider.send(:insync?, context, name, :dsc_setting, is_hash, should_hash_empty)
654
+ expect(result).to be(true)
655
+ end
656
+
657
+ it 'reports a change when the system has a value' do
658
+ allow(provider).to receive(:get_cached_fresh_state).and_return(name: 'foo', dsc_setting: 'v4.0')
659
+ result = provider.send(:insync?, context, name, :dsc_setting, is_hash, should_hash_empty)
660
+ expect(result).to eq([false, "dsc_setting changed 'v4.0' to ''"])
661
+ end
662
+ end
663
+
664
+ context 'when should_value is empty array' do
496
665
  it 'returns nil' do
497
- should_hash_empty = should_hash.merge(dsc_setting: '')
666
+ should_hash_empty = should_hash.merge(dsc_setting: [])
667
+ result = provider.send(:insync?, context, name, :dsc_setting, is_hash, should_hash_empty)
668
+ expect(result).to be_nil
669
+ end
670
+ end
671
+
672
+ context 'when should_value is empty hash' do
673
+ it 'returns nil' do
674
+ should_hash_empty = should_hash.merge(dsc_setting: {})
498
675
  result = provider.send(:insync?, context, name, :dsc_setting, is_hash, should_hash_empty)
499
676
  expect(result).to be_nil
500
677
  end
@@ -531,6 +708,334 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
531
708
  end
532
709
  end
533
710
 
711
+ context 'when the property is an embedded CIM instance array' do
712
+ let(:property_name) { :dsc_bindinginfo }
713
+ let(:should_hash) do
714
+ {
715
+ name: 'foo',
716
+ validation_mode: 'property',
717
+ dsc_bindinginfo: [
718
+ {
719
+ 'hostname' => 'contoso.com',
720
+ 'protocol' => 'http',
721
+ 'port' => 80
722
+ }
723
+ ]
724
+ }
725
+ end
726
+
727
+ before do
728
+ allow(type).to receive(:attributes).and_return(
729
+ dsc_bindinginfo: {
730
+ mof_type: 'DSC_WebBindingInformation[]',
731
+ mof_is_embedded: true
732
+ }
733
+ )
734
+ end
735
+
736
+ it 'ignores optional CIM fields omitted from the manifest' do
737
+ actual = should_hash[:dsc_bindinginfo].first.merge(
738
+ 'bindinginformation' => '*:80:contoso.com',
739
+ 'certificatestorename' => nil,
740
+ 'sslflags' => '0'
741
+ )
742
+ allow(provider).to receive(:get_cached_fresh_state)
743
+ .and_return(name: 'foo', dsc_bindinginfo: [actual])
744
+
745
+ result = provider.send(:insync?, context, name, property_name, {}, should_hash)
746
+ expect(result).to be true
747
+ end
748
+
749
+ it 'returns true when DSC adds optional fields to an embedded hash' do
750
+ actual_binding = {
751
+ 'bindinginformation' => '*:80:contoso.com',
752
+ 'certificatestorename' => nil,
753
+ 'certificatesubject' => nil,
754
+ 'certificatethumbprint' => nil,
755
+ 'hostname' => 'contoso.com',
756
+ 'ipaddress' => '*',
757
+ 'port' => 80,
758
+ 'protocol' => 'http',
759
+ 'sslflags' => '0'
760
+ }
761
+
762
+ allow(provider).to receive(:get_cached_fresh_state).and_return(
763
+ name: 'foo',
764
+ dsc_bindinginfo: [actual_binding]
765
+ )
766
+
767
+ result = provider.send(
768
+ :insync?, context, name, property_name, {}, should_hash
769
+ )
770
+
771
+ expect(result).to be true
772
+ end
773
+
774
+ context 'when comparing against the fresh DSC state' do
775
+ let(:http_binding) { { 'hostname' => 'contoso.com', 'protocol' => 'http', 'port' => 80 } }
776
+ let(:https_binding) { { 'hostname' => 'contoso.com', 'protocol' => 'https', 'port' => 443 } }
777
+
778
+ def insync_with(actual_bindings, desired_bindings = should_hash[:dsc_bindinginfo])
779
+ allow(provider).to receive(:get_cached_fresh_state)
780
+ .and_return(name: 'foo', dsc_bindinginfo: actual_bindings)
781
+ provider.send(
782
+ :insync?, context, name, property_name, {},
783
+ should_hash.merge(dsc_bindinginfo: desired_bindings)
784
+ )
785
+ end
786
+
787
+ it 'returns [false, change_message] when a managed field differs' do
788
+ result = insync_with([http_binding.merge('port' => 8080, 'sslflags' => '0')])
789
+ expect(result).to be_an(Array)
790
+ expect(result[0]).to be false
791
+ expect(result[1]).to include('dsc_bindinginfo changed')
792
+ end
793
+
794
+ it 'returns false when a managed field is missing from the fresh state' do
795
+ result = insync_with([{ 'hostname' => 'contoso.com', 'protocol' => 'http' }])
796
+ expect(result[0]).to be false
797
+ end
798
+
799
+ it 'returns false when the fresh state has more entries than desired' do
800
+ result = insync_with([http_binding, https_binding])
801
+ expect(result[0]).to be false
802
+ end
803
+
804
+ it 'returns false when the fresh state has fewer entries than desired' do
805
+ result = insync_with([http_binding], [http_binding, https_binding])
806
+ expect(result[0]).to be false
807
+ end
808
+
809
+ it 'returns false when the fresh state is not an array' do
810
+ result = insync_with(http_binding)
811
+ expect(result[0]).to be false
812
+ end
813
+
814
+ it 'returns true regardless of entry order' do
815
+ actual = [https_binding.merge('sslflags' => '1'), http_binding.merge('sslflags' => '0')]
816
+ expect(insync_with(actual, [http_binding, https_binding])).to be true
817
+ end
818
+
819
+ it 'matches keys and string values case-insensitively' do
820
+ actual = [{ 'HostName' => 'CONTOSO.com', 'Protocol' => 'HTTP', 'Port' => 80 }]
821
+ expect(insync_with(actual)).to be true
822
+ end
823
+
824
+ it 'matches duplicate desired entries one-to-one' do
825
+ actual = [http_binding, https_binding]
826
+ result = insync_with(actual, [http_binding, http_binding])
827
+ expect(result[0]).to be false
828
+ end
829
+
830
+ it 'returns true when duplicate desired entries each have a match' do
831
+ actual = [http_binding.merge('sslflags' => '0'), http_binding.merge('sslflags' => '1')]
832
+ expect(insync_with(actual, [http_binding, http_binding])).to be true
833
+ end
834
+
835
+ it 'compares nested embedded hashes partially' do
836
+ desired = [{ 'name' => 'a', 'options' => { 'mode' => 'x' } }]
837
+ actual = [{ 'name' => 'a', 'extra' => 1, 'options' => { 'mode' => 'X', 'level' => 2 } }]
838
+ expect(insync_with(actual, desired)).to be true
839
+ end
840
+
841
+ it 'detects differences in nested embedded hashes' do
842
+ desired = [{ 'name' => 'a', 'options' => { 'mode' => 'x' } }]
843
+ actual = [{ 'name' => 'a', 'options' => { 'mode' => 'y' } }]
844
+ expect(insync_with(actual, desired)[0]).to be false
845
+ end
846
+
847
+ it 'moves an earlier match when a later entry has only one possible match' do
848
+ # The first desired entry matches both actual entries, the second only
849
+ # the first one, so the first desired entry must move to the second.
850
+ desired = [{ 'protocol' => 'http' }, { 'protocol' => 'http', 'port' => 80 }]
851
+ actual = [http_binding, http_binding.merge('port' => 8080)]
852
+ expect(insync_with(actual, desired)).to be true
853
+ end
854
+
855
+ it 'does not try every ordering when many entries look alike' do
856
+ desired = Array.new(10) { { 'protocol' => 'http' } }
857
+ actual = Array.new(9) { |i| { 'protocol' => 'http', 'port' => 80 + i } } + [https_binding]
858
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
859
+ expect(insync_with(actual, desired)[0]).to be false
860
+ expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 1
861
+ end
862
+
863
+ # PowerShell returns $null for empty strings, also inside CIM instances.
864
+ context 'when a managed field is an empty string' do
865
+ let(:desired) { [http_binding.merge('certificatestorename' => '')] }
866
+
867
+ it 'returns true when DSC returns nil' do
868
+ expect(insync_with([http_binding.merge('certificatestorename' => nil)], desired)).to be true
869
+ end
870
+
871
+ it 'returns true when DSC omits the key' do
872
+ expect(insync_with([http_binding], desired)).to be true
873
+ end
874
+
875
+ it 'reports a change when DSC returns a value' do
876
+ result = insync_with([http_binding.merge('certificatestorename' => 'My')], desired)
877
+ expect(result[0]).to be false
878
+ end
879
+
880
+ it 'returns true when the empty string is in a nested hash and DSC returns nil' do
881
+ nested_desired = [{ 'name' => 'a', 'options' => { 'mode' => '' } }]
882
+ nested_actual = [{ 'name' => 'a', 'options' => { 'mode' => nil } }]
883
+ expect(insync_with(nested_actual, nested_desired)).to be true
884
+ end
885
+ end
886
+
887
+ # DSC defaults a nested Ensure to Present (e.g. SqlDatabaseObjectPermission,
888
+ # LogCustomFields), and Get may report the real state through it.
889
+ context 'when entries have an Ensure field' do
890
+ let(:grant) { { 'state' => 'Grant', 'permission' => 'Select' } }
891
+
892
+ it 'reports a change when the manifest omits Ensure and DSC returns Absent' do
893
+ expect(insync_with([grant.merge('ensure' => 'Absent')], [grant])[0]).to be false
894
+ end
895
+
896
+ it 'returns true when the manifest omits Ensure and DSC returns Present' do
897
+ expect(insync_with([grant.merge('ensure' => 'Present')], [grant])).to be true
898
+ end
899
+
900
+ it 'returns true when the manifest sets Present and DSC does not return Ensure' do
901
+ expect(insync_with([grant], [grant.merge('Ensure' => 'Present')])).to be true
902
+ end
903
+
904
+ it 'returns true when the manifest sets Present and DSC returns a nil Ensure' do
905
+ expect(insync_with([grant.merge('ensure' => nil)], [grant.merge('ensure' => 'present')])).to be true
906
+ end
907
+
908
+ it 'reports a change when the manifest sets Absent and DSC returns Present' do
909
+ expect(insync_with([grant.merge('ensure' => 'Present')], [grant.merge('ensure' => 'Absent')])[0]).to be false
910
+ end
911
+ end
912
+
913
+ # undef in the manifest (e.g. an optional class parameter) is not managed.
914
+ context 'when a managed field is nil in the manifest' do
915
+ let(:desired) { [http_binding.merge('sslflags' => nil)] }
916
+
917
+ it 'returns true when DSC returns a value' do
918
+ expect(insync_with([http_binding.merge('sslflags' => '1')], desired)).to be true
919
+ end
920
+
921
+ it 'returns true when DSC omits the key' do
922
+ expect(insync_with([http_binding], desired)).to be true
923
+ end
924
+
925
+ it 'returns true when the nil field is in a nested hash' do
926
+ nested_desired = [{ 'name' => 'a', 'options' => { 'mode' => nil } }]
927
+ nested_actual = [{ 'name' => 'a', 'options' => { 'mode' => 'x' } }]
928
+ expect(insync_with(nested_actual, nested_desired)).to be true
929
+ end
930
+
931
+ it 'still compares Ensure as Present when it is nil in the manifest' do
932
+ grant = { 'state' => 'Grant', 'permission' => 'Select' }
933
+ result = insync_with([grant.merge('ensure' => 'Absent')], [grant.merge('ensure' => nil)])
934
+ expect(result[0]).to be false
935
+ end
936
+ end
937
+
938
+ context 'when a nested field is an empty array' do
939
+ let(:desired) { [{ 'name' => 'a', 'members' => [] }] }
940
+
941
+ it 'returns true when DSC returns nil' do
942
+ expect(insync_with([{ 'name' => 'a', 'members' => nil }], desired)).to be true
943
+ end
944
+
945
+ it 'reports a change when DSC returns entries' do
946
+ expect(insync_with([{ 'name' => 'a', 'members' => ['bob'] }], desired)[0]).to be false
947
+ end
948
+ end
949
+
950
+ it 'returns true when a nested array of values is in a different order' do
951
+ desired = [{ 'name' => 'a', 'members' => %w[alice bob] }]
952
+ actual = [{ 'name' => 'a', 'members' => %w[bob alice] }]
953
+ expect(insync_with(actual, desired)).to be true
954
+ end
955
+
956
+ it 'moves entries along a chain of matches' do
957
+ desired = [{ 'protocol' => 'http' }, { 'protocol' => 'http', 'port' => 80 },
958
+ { 'protocol' => 'http', 'port' => 80, 'hostname' => 'contoso.com' }]
959
+ actual = [http_binding, http_binding.merge('hostname' => 'fabrikam.com'),
960
+ http_binding.merge('port' => 8080, 'hostname' => 'fabrikam.com')]
961
+ expect(insync_with(actual, desired)).to be true
962
+ end
963
+
964
+ it 'returns false when two desired entries can only match the same actual entry' do
965
+ desired = [{ 'protocol' => 'http', 'port' => 80 }, { 'protocol' => 'http', 'hostname' => 'contoso.com' }]
966
+ actual = [http_binding, https_binding]
967
+ expect(insync_with(actual, desired)[0]).to be false
968
+ end
969
+
970
+ context 'when the validation_mode is "resource"' do
971
+ let(:should_hash) { super().merge(validation_mode: 'resource') }
972
+
973
+ before do
974
+ allow(provider).to receive(:fetch_cached_hashes).and_return([])
975
+ allow(provider).to receive(:invoke_test_method).and_return([false, 'not in desired state'])
976
+ end
977
+
978
+ it 'ignores optional CIM fields omitted from the manifest, and still reports the failed Test' do
979
+ result = insync_with([http_binding.merge('sslflags' => '0')])
980
+ expect(result[0]).to be false
981
+ expect(result[1]).to start_with('DSC Test reported the resource out of sync')
982
+ end
983
+
984
+ it 'reports a change when a managed field differs' do
985
+ result = insync_with([http_binding.merge('port' => 8080)])
986
+ expect(result[0]).to be false
987
+ expect(result[1]).to include('dsc_bindinginfo changed')
988
+ end
989
+ end
990
+ end
991
+ end
992
+
993
+ context 'when the property is a single embedded CIM instance' do
994
+ let(:property_name) { :dsc_authenticationinfo }
995
+ let(:should_hash) do
996
+ { name: 'foo', validation_mode: 'property', dsc_authenticationinfo: { 'anonymous' => true } }
997
+ end
998
+
999
+ before do
1000
+ allow(type).to receive(:attributes).and_return(
1001
+ dsc_authenticationinfo: { mof_type: 'DSC_WebAuthenticationInformation', mof_is_embedded: true }
1002
+ )
1003
+ end
1004
+
1005
+ def insync_with(actual)
1006
+ allow(provider).to receive(:get_cached_fresh_state).and_return(name: 'foo', dsc_authenticationinfo: actual)
1007
+ provider.send(:insync?, context, name, property_name, {}, should_hash)
1008
+ end
1009
+
1010
+ it 'ignores optional CIM fields omitted from the manifest' do
1011
+ expect(insync_with('anonymous' => true, 'basic' => false, 'windows' => true)).to be true
1012
+ end
1013
+
1014
+ it 'reports a change when a managed field differs' do
1015
+ expect(insync_with('anonymous' => false, 'basic' => false)[0]).to be false
1016
+ end
1017
+ end
1018
+
1019
+ context 'when a hash property is not an embedded CIM instance' do
1020
+ let(:should_hash) { { name: 'foo', validation_mode: 'property', dsc_setting: { 'a' => 1 } } }
1021
+
1022
+ before do
1023
+ allow(provider).to receive(:get_cached_fresh_state).and_return(name: 'foo', dsc_setting: { 'a' => 1, 'b' => 2 })
1024
+ end
1025
+
1026
+ it 'reports a change when DSC returns extra fields' do
1027
+ allow(type).to receive(:attributes).and_return(dsc_setting: { mof_is_embedded: false })
1028
+ result = provider.send(:insync?, context, name, :dsc_setting, {}, should_hash)
1029
+ expect(result[0]).to be false
1030
+ end
1031
+
1032
+ it 'compares strictly when the property is missing from the type definition' do
1033
+ allow(type).to receive(:attributes).and_return({})
1034
+ result = provider.send(:insync?, context, name, :dsc_setting, {}, should_hash)
1035
+ expect(result[0]).to be false
1036
+ end
1037
+ end
1038
+
534
1039
  context 'when values differ' do
535
1040
  it 'returns [false, change_message] and sets insync_property_cache' do
536
1041
  differing_fresh = { name: 'foo', dsc_setting: 'Bar' }
@@ -554,6 +1059,7 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
554
1059
  expect(provider.values_equal?(nil, nil)).to be true
555
1060
  end
556
1061
 
1062
+ # Required because PowerShell returns $null for empty strings.
557
1063
  it 'returns true for nil and empty string' do
558
1064
  expect(provider.values_equal?(nil, '')).to be true
559
1065
  expect(provider.values_equal?('', nil)).to be true
@@ -1292,6 +1798,47 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
1292
1798
  end
1293
1799
  end
1294
1800
  end
1801
+
1802
+ # undef in an embedded CIM instance is not managed, and nil cannot be formatted to PowerShell
1803
+ context 'when an embedded CIM instance has nil fields' do
1804
+ let(:definition) do
1805
+ super().tap do |d|
1806
+ d[:attributes][:dsc_bindinginfo] = { type: 'Optional[Array[Struct[{}]]]', mof_type: 'DSC_WebBindingInformation[]', mof_is_embedded: true }
1807
+ d[:attributes][:dsc_setting] = { type: 'Optional[Hash]', mof_type: 'String', mof_is_embedded: false }
1808
+ end
1809
+ end
1810
+
1811
+ it 'removes nil fields and keeps the others' do
1812
+ should_hash[:dsc_bindinginfo] = [{ 'protocol' => 'https', 'port' => 8443, 'sslflags' => nil }]
1813
+ expect(result[:parameters][:dsc_bindinginfo][:value]).to eq([{ 'protocol' => 'https', 'port' => 8443 }])
1814
+ end
1815
+
1816
+ it 'keeps empty strings' do
1817
+ should_hash[:dsc_bindinginfo] = [{ 'protocol' => 'https', 'certificatethumbprint' => '' }]
1818
+ expect(result[:parameters][:dsc_bindinginfo][:value]).to eq([{ 'protocol' => 'https', 'certificatethumbprint' => '' }])
1819
+ end
1820
+
1821
+ it 'removes nil fields in nested hashes' do
1822
+ should_hash[:dsc_bindinginfo] = [{ 'name' => 'a', 'options' => { 'mode' => nil, 'level' => 1 } }]
1823
+ expect(result[:parameters][:dsc_bindinginfo][:value]).to eq([{ 'name' => 'a', 'options' => { 'level' => 1 } }])
1824
+ end
1825
+
1826
+ it 'does not change properties that are not embedded CIM instances' do
1827
+ should_hash[:dsc_setting] = { 'a' => nil }
1828
+ expect(result[:parameters][:dsc_setting][:value]).to eq({ 'a' => nil })
1829
+ end
1830
+
1831
+ it 'does not change the should hash' do
1832
+ should_hash[:dsc_bindinginfo] = [{ 'protocol' => 'https', 'sslflags' => nil }]
1833
+ result
1834
+ expect(should_hash[:dsc_bindinginfo]).to eq([{ 'protocol' => 'https', 'sslflags' => nil }])
1835
+ end
1836
+
1837
+ it 'can be formatted to PowerShell' do
1838
+ should_hash[:dsc_bindinginfo] = [{ 'protocol' => 'https', 'sslflags' => nil }]
1839
+ expect { provider.format(result[:parameters][:dsc_bindinginfo][:value]) }.not_to raise_error
1840
+ end
1841
+ end
1295
1842
  end
1296
1843
 
1297
1844
  describe '.vendored_modules_path' do
@@ -1380,6 +1927,19 @@ RSpec.describe Puppet::Provider::DscBaseProvider do
1380
1927
  provider.instance_variable_set(:@cached_test_results, [])
1381
1928
  end
1382
1929
 
1930
+ context 'when the resource sets a timeout and a credential' do
1931
+ let(:credential) { { 'user' => 'DOM\\svc', 'password' => 'secret' } }
1932
+ let(:should_hash) { name.merge(dsc_ensure: 'present', dsc_timeout: 600, dsc_psdscrunascredential: credential) }
1933
+
1934
+ it 'passes them in the name hash and caches the result under the name' do
1935
+ expect(provider).to receive(:invoke_dsc_resource)
1936
+ .with(context, name.merge(dsc_timeout: 600, dsc_psdscrunascredential: credential), test_properties, 'test')
1937
+ .and_return({ 'indesiredstate' => true, 'errormessage' => '' })
1938
+ expect(result).to be(true)
1939
+ expect(provider.cached_test_results).to eq([name.merge(in_desired_state: true)])
1940
+ end
1941
+ end
1942
+
1383
1943
  context 'when something went wrong calling Invoke-DscResource' do
1384
1944
  it 'falls back on property-by-property state comparison and does not cache anything' do
1385
1945
  expect(context).not_to receive(:err)
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'ruby-pwsh'
5
+
6
+ RSpec.describe Pwsh::Manager do
7
+ describe '#drain_pipe_until_signaled' do
8
+ let(:manager) { described_class.allocate }
9
+ let(:pipes) { IO.pipe }
10
+ let(:reader) { pipes[0] }
11
+ let(:writer) { pipes[1] }
12
+ let(:signal) { Mutex.new }
13
+
14
+ after do
15
+ reader.close
16
+ writer.close
17
+ end
18
+
19
+ it 'returns everything written before the signal without waiting on the open, empty pipe' do
20
+ signal.lock
21
+ drain = Thread.new do
22
+ output = manager.send(:drain_pipe_until_signaled, reader, signal)
23
+ [output, Process.clock_gettime(Process::CLOCK_MONOTONIC)]
24
+ end
25
+
26
+ writer.write('hello')
27
+ sleep 0.2
28
+ writer.write(' world')
29
+ released_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
30
+ signal.unlock
31
+ output, finished_at = drain.value
32
+
33
+ expect(output).to eq(['hello world'])
34
+ expect(finished_at - released_at).to be < 0.3
35
+ end
36
+
37
+ it 'returns an empty array when nothing was written' do
38
+ expect(manager.send(:drain_pipe_until_signaled, reader, signal)).to eq([])
39
+ end
40
+ end
41
+ end
@@ -516,6 +516,15 @@ RSpec.shared_examples 'a PowerShellCodeManager' do |ps_command, ps_args|
516
516
  expect(result[:stdout]).to eq("False#{line_end}")
517
517
  end
518
518
 
519
+ it 'removes env variables named like a cached one with another case between runs' do
520
+ path = manager.execute('[Environment]::GetEnvironmentVariable("PATH", "process")')[:stdout]
521
+ manager.execute('[Environment]::SetEnvironmentVariable("path", "leak", "process")')
522
+ result = manager.execute('[Environment]::GetEnvironmentVariable("path", "process")')
523
+
524
+ expect(result[:stdout]).not_to eq("leak#{line_end}")
525
+ expect(manager.execute('[Environment]::GetEnvironmentVariable("PATH", "process")')[:stdout]).to eq(path)
526
+ end
527
+
519
528
  it 'sets custom environment variables' do
520
529
  result = manager.execute('Write-Output $ENV:foo', nil, nil, ['foo=bar'])
521
530
 
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ruby-pwsh
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.1.0
4
+ version: 2.1.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Puppet, Inc.
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-09-07 00:00:00.000000000 Z
11
+ date: 2026-11-30 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rexml
@@ -54,6 +54,7 @@ files:
54
54
  - spec/exit-27.ps1
55
55
  - spec/spec_helper.rb
56
56
  - spec/unit/puppet/provider/dsc_base_provider/dsc_base_provider_spec.rb
57
+ - spec/unit/pwsh/manager_drain_spec.rb
57
58
  - spec/unit/pwsh/util_spec.rb
58
59
  - spec/unit/pwsh/version_spec.rb
59
60
  - spec/unit/pwsh/windows_powershell_spec.rb