Debian Codegraph @

lib/ansible/executor/powershell/module_wrapper.ps1

raw
1 # (c) 2025 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 using namespace System.Collections
5 using namespace System.IO
6 using namespace System.Management.Automation
7 using namespace System.Management.Automation.Language
8 using namespace System.Management.Automation.Security
9 using namespace System.Text
10
11 [CmdletBinding()]
12 param(
13 [Parameter(Mandatory)]
14 [string]
15 $Script,
16
17 [Parameter()]
18 [PSObject]
19 $Environment,
20
21 [Parameter()]
22 [AllowEmptyCollection()]
23 [string[]]
24 $CSharpModules,
25
26 [Parameter()]
27 [AllowEmptyCollection()]
28 [string[]]
29 $PowerShellModules,
30
31 [Parameter()]
32 [LineBreakpoint[]]
33 $Breakpoints,
34
35 [Parameter()]
36 [string]
37 $ArgumentJSON,
38
39 [Parameter()]
40 [SecureString[]]
41 $Secrets,
42
43 [Parameter()]
44 [switch]
45 $ForModule
46 )
47
48 Function Convert-JsonObject {
49 param (
50 [Parameter(Mandatory, ValueFromPipeline)]
51 [AllowNull()]
52 [object]
53 $InputObject
54 )
55
56 process {
57 # Using the full type name is important as [PSCustomObject] is an
58 # alias for [PSObject] which all piped objects are.
59 if ($InputObject -is [System.Management.Automation.PSCustomObject]) {
60 $value = @{}
61 foreach ($prop in $InputObject.PSObject.Properties) {
62 $value[$prop.Name] = Convert-JsonObject -InputObject $prop.Value
63 }
64 $value
65 }
66 elseif ($InputObject -is [Array]) {
67 , @($InputObject | Convert-JsonObject)
68 }
69 else {
70 $InputObject
71 }
72 }
73 }
74
75 Function Write-AnsibleErrorDetail {
76 [CmdletBinding()]
77 param (
78 [Parameter(Mandatory)]
79 [System.Management.Automation.ErrorRecord]
80 $ErrorRecord,
81
82 [Parameter()]
83 [switch]
84 $ForModule
85 )
86
87 # Be more defensive when trying to find the InnerException in case it isn't
88 # set. This shouldn't ever be the case but if it is then it makes it more
89 # difficult to track down the problem.
90 if ($ErrorRecord.Exception.InnerException.ErrorRecord) {
91 $ErrorRecord = $ErrorRecord.Exception.InnerException.ErrorRecord
92 }
93
94 $exception = @(
95 "$ErrorRecord"
96
97 # stderr from sub processes have this error id, we don't want to format those errors
98 # like a normal powershell error record.
99 if ($ErrorRecord.FullyQualifiedErrorId -notin @('NativeCommandError', 'NativeCommandErrorMessage')) {
100 "$($ErrorRecord.InvocationInfo.PositionMessage)"
101 "+ CategoryInfo : $($ErrorRecord.CategoryInfo)"
102 "+ FullyQualifiedErrorId : $($ErrorRecord.FullyQualifiedErrorId)"
103 ""
104 "ScriptStackTrace:"
105 "$($ErrorRecord.ScriptStackTrace)"
106
107 if ($ErrorRecord.Exception.StackTrace) {
108 "$($ErrorRecord.Exception.StackTrace)"
109 }
110 }
111 ) -join ([Environment]::NewLine)
112
113 if ($ForModule) {
114 @{
115 failed = $true
116 msg = "Unhandled exception while executing module: $ErrorRecord"
117 exception = $exception
118 } | ConvertTo-Json -Compress
119 }
120 else {
121 $host.UI.WriteErrorLine($exception)
122 }
123 }
124
125 # It is important we use CreateDefault2 to ensure that builtin modules are
126 # imported when requested. CreateDefault only imports the builtin modules
127 # as snapins which miss things like ETS type definitions.
128 $ps = [PowerShell]::Create([InitialSessionState]::CreateDefault2())
129
130 if ($ForModule) {
131 $ps.Runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "Stop")
132 }
133 else {
134 # For script files we want to ensure we load it as UTF-8. We don't set this
135 # for modules as they are loaded from memory whereas a script is loaded
136 # from disk as part of the script being run than by us.
137 Set-WinPSDefaultFileEncoding
138 }
139
140 if ($ArgumentJSON) {
141 $jsonParams = @{}
142 if ($IsCoreCLR) {
143 # PowerShell 7 parses an ISO 8601 date string into a DateTime object. As we
144 # want to preserve the original string we tell it using the DateKind param.
145 $jsonParams.DateKind = 'String'
146 }
147 $parsedArgs = $ArgumentJSON | ConvertFrom-Json @jsonParams | Convert-JsonObject
148
149 # FUTURE: Deprecate complex_args and move parsing logic into module_utils.
150 # Deprecation requires exec_wrapper warning system to be implemented. We
151 # can use Set-PSBreakPoint to fire an action on variable reads.
152 $null = $ps.AddCommand("Set-Variable").AddParameters(
153 @{
154 Name = 'complex_args'
155 Value = $parsedArgs
156 Scope = 'Global'
157 }).AddStatement()
158 }
159
160 # env vars are process side so we can just set them here.
161 foreach ($env in $Environment.PSObject.Properties) {
162 [Environment]::SetEnvironmentVariable($env.Name, $env.Value)
163 }
164
165 # Redefine Write-Host to dump to output instead of failing, lots of scripts
166 # still use it.
167 $null = $ps.AddScript('Function Write-Host($msg) { Write-Output -InputObject $msg }').AddStatement()
168
169 # ParseInput doesn't throw on an invalid script, we need to check the errors
170 # and throw ourselves. We use ParseInput so we can associate a filename with
171 # the script making StackTraces and error messages much easier to understand.
172 $parseScriptWithName = {
173 [OutputType([ScriptBlock])]
174 [CmdletBinding()]
175 param (
176 [Parameter(Mandatory)]
177 [string]
178 $Name,
179
180 [Parameter(Mandatory)]
181 [string]
182 $Script
183 )
184
185 $err = @()
186 $ast = [System.Management.Automation.Language.Parser]::ParseInput(
187 $Script,
188 $Name,
189 [ref]$null,
190 [ref]$err)
191 if ($err) {
192 $parseErrors = $err -join "`n"
193 throw "Failed to parse script '$Name'`n$parseErrors"
194 }
195
196 $ast.GetScriptBlock()
197 }
198
199 $scriptInfo = Get-AnsibleScript -Name $Script
200 if ($scriptInfo.ShouldConstrain) {
201 # Fail if there are any module utils, in the future we may allow unsigned
202 # PowerShell utils in CLM but for now we don't.
203 if ($PowerShellModules -or $CSharpModules) {
204 throw "Cannot run untrusted PowerShell script '$Script' in ConstrainedLanguage mode with module util imports."
205 }
206
207 # If the module is marked as needing to be constrained then we set the
208 # language mode to ConstrainedLanguage so that when parsed inside the
209 # Runspace it will run in CLM. We need to run it from a filepath as in
210 # CLM we cannot call the methods needed to create the ScriptBlock and we
211 # need to be in CLM to downgrade the language mode.
212 $null = $ps.AddScript('$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"').AddStatement()
213 $scriptPath = New-TempAnsibleFile -FileName $Script -Content $scriptInfo.Script
214 $null = $ps.AddCommand($scriptPath, $false).AddStatement()
215 }
216 else {
217 if ($PowerShellModules) {
218 foreach ($utilName in $PowerShellModules) {
219 $utilInfo = Get-AnsibleScript -Name $utilName
220 if ($utilInfo.ShouldConstrain) {
221 throw "PowerShell module util '$utilName' is not trusted and cannot be loaded."
222 }
223
224 $null = $ps.AddScript($parseScriptWithName).AddParameters(@{
225 Name = $utilName
226 Script = $utilInfo.Script
227 })
228 $null = $ps.AddScript(@'
229 New-Module -Name $args[0] -ScriptBlock @($input)[0] |
230 Import-Module -WarningAction SilentlyContinue -Scope Global
231 '@).AddArgument([Path]::GetFileNameWithoutExtension($utilName)).AddStatement()
232 }
233 }
234
235 if ($CSharpModules) {
236 # C# utils are process wide so just load them here.
237 Import-CSharpUtil -Name $CSharpModules
238 }
239
240 # We invoke it through a command with useLocalScope $false to
241 # ensure the code runs with it's own $script: scope. It also
242 # cleans up the StackTrace on errors by not showing the stub
243 # execution line and starts immediately at the module "cmd".
244 $null = $ps.AddScript($parseScriptWithName).AddParameters(@{
245 Name = $Script
246 Script = $scriptInfo.Script
247 }).AddScript(@'
248 ${function:<AnsibleModule>} = @($input)[0]
249 '@).AddStatement()
250 $null = $ps.AddCommand('<AnsibleModule>', $false).AddStatement()
251 }
252
253 if ($Breakpoints) {
254 $ps.Runspace.Debugger.SetBreakpoints($Breakpoints)
255 }
256
257 if ($Secrets.Count) {
258 # Using SecureString is important to avoid AMSI and other logging tools
259 # from accidentally exposing the raw values.
260 [Ansible.Secrets.SecretMasker]::_RegisterAnsibleSecrets($Secrets)
261 }
262
263 # Temporarily override the stdout stream and create our own in a StringBuilder.
264 # We use this to ensure there's always an Out pipe and that we capture the
265 # output for things like async or psrp.
266 $origOut = [Console]::Out
267 $sb = [StringBuilder]::new()
268 try {
269 $newOut = [StringWriter]::new($sb)
270 [Console]::SetOut($newOut)
271
272 $modOut = @($ps.Invoke())
273 }
274 catch {
275 Write-AnsibleErrorDetail -ErrorRecord $_ -ForModule:$ForModule
276 if ($ForModule) {
277 $host.SetShouldExit(1)
278 return
279 }
280 }
281 finally {
282 if ($newOut) {
283 [Console]::SetOut($origOut)
284 $newOut.Dispose()
285 }
286 }
287
288 $stdout = $sb.ToString()
289 if ($stdout) {
290 $stdout
291 }
292 if ($modOut.Count) {
293 $modOut -join "`r`n"
294 }
295
296 # Attempt to set the return code from the LASTEXITCODE variable. This is set
297 # explicitly in newer style modules when calling ExitJson and FailJson.
298 $rc = $ps.Runspace.SessionStateProxy.GetVariable("LASTEXITCODE")
299 if ($null -ne $rc) {
300 $host.SetShouldExit($rc)
301 }
302
303 foreach ($err in $ps.Streams.Error) {
304 Write-AnsibleErrorDetail -ErrorRecord $err -ForModule:$ForModule
305 if ($ForModule) {
306 if ($null -eq $rc) {
307 $host.SetShouldExit(1)
308 }
309 return
310 }
311 }