Private/Hide-SecretValue.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
Function Hide-SecretValue {
    <#
    .SYNOPSIS
    Hide a secret value by converting it to "******"
 
    .DESCRIPTION
    Matches a pattern in a JSON formatted string which is expected to contain a secret value.
    Replaces all secret values with "******", and returns a sanitised string.
    Enables a request body to be included in debug/verbose streams without exposing secret values.
 
    .PARAMETER InputValue
    JSON body of API request
 
    .PARAMETER SecretsToRemove
    Any additional JSON properties which should be sanitised.
 
    .PARAMETER Secrets
    psPAS default JSON properties known to contain secrets
 
    .EXAMPLE
    Remove Secret Values from $String
 
    $String = [pscustomobject]@{
        "Property"="Value"
        "Password"="SecretValue"
        "Secret"="DontShareThis"
        "NewCredentials"="S3cr3t"
        "NewPassword"="Password123!"
        "BindPassword"="ABCDE123!"
        "InitialPassword"="123456"
        "InnocentProperty"="SomeValue"
    } | ConvertTo-Json
 
    Hide-SecretValue -InputValue $String
 
    {
        "Property": "Value",
        "Password": "******",
        "Secret": "******",
        "NewCredentials": "******",
        "NewPassword": "******",
        "BindPassword": "******",
        "InitialPassword": "******",
        "InnocentProperty": "SomeValue"
    }
 
    #>

    [CmdletBinding()]
    [OutputType('System.String')]
    param(
        [parameter(
            Position = 0,
            Mandatory = $true,
            ValueFromPipeline = $true)]
        [String]$InputValue,

        [parameter(
            Mandatory = $false)]
        [array]$SecretsToRemove = @(),

        [parameter(
            Mandatory = $false)]
        [array]$Secrets = @(
            "Secret",
            "Password",
            "NewCredentials",
            "NewPassword",
            "BindPassword",
            "InitialPassword"
        )
    )

    BEGIN {



    }#begin

    PROCESS {

        $OutputValue = $InputValue

        #Combine base parameters and any additional parameters to remove
        ($SecretsToRemove + $Secrets) |

        ForEach-Object {

            $OutputValue = $OutputValue -replace "(`"$_`":).+", "`$1 `"******`","

        }

    }#process

    END {

        #Return Output
        $OutputValue

    }#end

}