RsaSha1Signature::method()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Invoiced\OAuth1\Client\Server;
4
5
use GuzzleHttp\Psr7;
6
use GuzzleHttp\Psr7\Uri;
7
use League\OAuth1\Client\Signature\Signature;
8
use League\OAuth1\Client\Signature\SignatureInterface;
9
10
class RsaSha1Signature extends Signature implements SignatureInterface
11
{
12
    /**
13
     * {@inheritdoc}
14
     */
15
    public function method()
16
    {
17
        return 'RSA-SHA1';
18
    }
19
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function sign($uri, array $parameters = array(), $method = 'POST')
24
    {
25
        $url = $this->createUrl($uri);
26
        $baseString = $this->baseString($url, $method, $parameters);
0 ignored issues
show
Compatibility introduced by
$url of type object<Psr\Http\Message\UriInterface> is not a sub-type of object<GuzzleHttp\Psr7\Uri>. It seems like you assume a concrete implementation of the interface Psr\Http\Message\UriInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
27
28
        $privateKey = $this->clientCredentials->getRsaPrivateKey();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface League\OAuth1\Client\Cre...entCredentialsInterface as the method getRsaPrivateKey() does only exist in the following implementations of said interface: Invoiced\OAuth1\Client\Server\RsaClientCredentials.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
29
30
        openssl_sign($baseString, $signature, $privateKey);
31
32
        return base64_encode($signature);
33
    }
34
35
    /**
36
     * Create a Guzzle url for the given URI.
37
     *
38
     * @param string $uri
39
     *
40
     * @return Url
41
     */
42
    protected function createUrl($uri)
43
    {
44
        return Psr7\uri_for($uri);
45
    }
46
47
    /**
48
     * Generate a base string for a RSA-SHA1 signature
49
     * based on the given a url, method, and any parameters.
50
     *
51
     * @param Url    $url
52
     * @param string $method
53
     * @param array  $parameters
54
     *
55
     * @return string
56
     */
57
    protected function baseString(Uri $url, $method = 'POST', array $parameters = array())
58
    {
59
        $baseString = rawurlencode($method).'&';
60
61
        $schemeHostPath = Uri::fromParts(array(
62
           'scheme' => $url->getScheme(),
63
           'host' => $url->getHost(),
64
           'path' => $url->getPath(),
65
        ));
66
67
        $baseString .= rawurlencode($schemeHostPath).'&';
68
69
        $data = array();
0 ignored issues
show
Unused Code introduced by
$data is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
70
        parse_str($url->getQuery(), $query);
71
        $data = array_merge($query, $parameters);
72
73
        // normalize data key/values
74
        array_walk_recursive($data, function (&$key, &$value) {
75
            $key = rawurlencode(rawurldecode($key));
76
            $value = rawurlencode(rawurldecode($value));
77
        });
78
        ksort($data);
79
80
        $baseString .= $this->queryStringFromData($data);
81
82
        return $baseString;
83
    }
84
85
    /**
86
     * Creates an array of rawurlencoded strings out of each array key/value pair
87
     * Handles multi-demensional arrays recursively.
88
     *
89
     * @param array  $data        Array of parameters to convert.
90
     * @param array  $queryParams Array to extend. False by default.
91
     * @param string $prevKey     Optional Array key to append
92
     *
93
     * @return string rawurlencoded string version of data
94
     */
95
    protected function queryStringFromData($data, $queryParams = false, $prevKey = '')
96
    {
97
        if ($initial = (false === $queryParams)) {
98
            $queryParams = array();
99
        }
100
101
        foreach ($data as $key => $value) {
102
            if ($prevKey) {
103
                $key = $prevKey.'['.$key.']'; // Handle multi-dimensional array
104
            }
105
            if (is_array($value)) {
106
                $queryParams = $this->queryStringFromData($value, $queryParams, $key);
107
            } else {
108
                $queryParams[] = rawurlencode($key.'='.$value); // join with equals sign
109
            }
110
        }
111
112
        if ($initial) {
113
            return implode('%26', $queryParams); // join with ampersand
114
        }
115
116
        return $queryParams;
117
    }
118
}
119