Using Pester to save yourself from leaked API keys

I’m here at PowerShell Conference Asia and enjoying some superb content and insightful discussion. One thing that just came up was the idea that Pester doesn’t have to be solely for testing code  you can also test things related your code – metadata for instance.

The example I just mentioned on the hashtag is that I have a Pester test which scans the entire repository for things that look like API keys – in my case for Octopus Deploy and AWS.

The code isn’t too tricky, to be honest. Just recurse over your files, open them up and test them against a regex. Here’s the code in question

Describe "Overview Tests" {
    Context "Checking Repo integrity" {   
         It "The repo does not include anything that looks like an Octopus API key" {
            # Octopus API keys are 31 chars and start with API-

            $ok = $true
            $badfiles = @()

            $regex = "\bAPI-\w{27}\b" 
            gci -recurse -File | % {
                $filecontent = gc $_.FullName -raw
                if($filecontent -match $regex)
                {
                    $ok = $false
                    Write-Host $_.FullName "has an Octopus API key warning"
                }
            }
            $ok | Should Be $true
        }

        It "Doesn't contain anything that looks like an AWS Key or secret" {
            $ok = $true
            $badfiles = @()

            $regex = "\b(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])\b" 
            $secretregex = "\b(?<![A-Za-z0-9/+=])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])\b"

            gci -recurse -File | % {
                $filecontent = gc $_.FullName -raw
                if($filecontent -match $regex -or $filecontent -match $secretregex)
                {
                    $ok = $false
                    Write-Host $_.FullName "has an AWS API key warning"
                }
            }
            $ok | Should Be $true
        }
    }
}

This does come with caveats – AWS make no guarantee that their API key format won’t change. This certainly works right now, but might not work next week. Same with Octopus, as far as I’m aware. But it’ll protect the keys you have now from being exposed on github, potentially costing you thousands.

Leave a Reply

Your email address will not be published. Required fields are marked *