Skip to content

Commit

Permalink
Redact API key in RequestOpts debug info
Browse files Browse the repository at this point in the history
  • Loading branch information
ob-stripe committed Oct 18, 2019
1 parent 96c5974 commit 3ad8f5e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/Util/RequestOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ public function __construct($key = null, $headers = [], $base = null)
$this->apiBase = $base;
}

public function __debugInfo()
{
return [
'apiKey' => $this->redactedApiKey(),
'headers' => $this->headers,
'apiBase' => $this->apiBase,
];
}

/**
* Unpacks an options array and merges it into the existing RequestOptions
* object.
Expand Down Expand Up @@ -105,4 +114,15 @@ public static function parse($options)
. 'a global apiKey by "Stripe::setApiKey(<apiKey>)")';
throw new Exception\InvalidArgumentException($message);
}

private function redactedApiKey()
{
$pieces = explode('_', $this->apiKey, 3);
$last = array_pop($pieces);
$redactedLast = strlen($last) > 4
? (str_repeat('*', strlen($last) - 4) . substr($last, -4))
: $last;
array_push($pieces, $redactedLast);
return implode('_', $pieces);
}
}
15 changes: 15 additions & 0 deletions tests/Stripe/Util/RequestOptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,19 @@ public function testDiscardNonPersistentHeaders()
$opts->discardNonPersistentHeaders();
$this->assertSame(['Stripe-Account' => 'foo'], $opts->headers);
}

public function testDebugInfo()
{
$opts = Util\RequestOptions::parse(['api_key' => 'sk_test_1234567890abcdefghijklmn']);
$debugInfo = print_r($opts, true);
$this->assertContains("[apiKey] => sk_test_********************klmn", $debugInfo);

$opts = Util\RequestOptions::parse(['api_key' => 'sk_1234567890abcdefghijklmn']);
$debugInfo = print_r($opts, true);
$this->assertContains("[apiKey] => sk_********************klmn", $debugInfo);

$opts = Util\RequestOptions::parse(['api_key' => '1234567890abcdefghijklmn']);
$debugInfo = print_r($opts, true);
$this->assertContains("[apiKey] => ********************klmn", $debugInfo);
}
}

0 comments on commit 3ad8f5e

Please sign in to comment.