aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/OAuth1.php
blob: 3d67199b54c3c21e54a4e6f0d4f570e643c8215d (plain)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
<?php
namespace Studip;

use Psr\Http\Message\ServerRequestInterface as Request;
use RuntimeException;

/**
 * Basic oauth1 request handling for Stud.IP using PSR-7 http messages.
 *
 * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
 * @license GPL2 or any later version
 * @since Stud.IP 6.0
 */
final class OAuth1
{
    /**
     * Signs a given request.
     *
     * @throws RuntimeException if a request for any other oauth version then
     *                          1.0 shall be signed
     */
    public static function signRequest(
        Request $request,
        string  $consumerSecret,
        string  $tokenSecret,
        string  $method
    ): string {
        if (
            isset($request->getQueryParams()['oauth_version'])
            && $request->getQueryParams()['oauth_version'] !== '1.0'
        ) {
            throw new RuntimeException(self::class . ' only supports OAuth 1.0 requests');
        }

        $allowed_replacements_methods = [
            'sha1'   => 'hmac-sha1',
            'sha256' => 'hmac-sha256',
            'sha512' => 'hmac-sha512',
        ];

        return self::hash(
            $allowed_replacements_methods[$method] ?? $method,
            self::getSignatureBaseString($request),
            rawurlencode($consumerSecret) . '&' . rawurlencode($tokenSecret)
        );
    }

    /**
     * Verifies an oauth request.
     *
     * @throws RuntimeException if any necessary oauth parameter is missing
     */
    public static function verifyRequest(
        Request $request,
        string  $consumerSecret,
        string  $tokenSecret
    ): bool {
        $parameters = self::extractParameters($request);

        if ($parameters['oauth_timestamp'] < time() - 5 * 60) {
            return false;
        }

        return self::verifySignature($request, $consumerSecret, $tokenSecret);
    }

    /**
     * Verifies an oauth request.
     *
     * @throws RuntimeException if any necessary oauth parameter is missing
     */
    public static function verifySignature(
        Request $request,
        string  $consumerSecret,
        string  $tokenSecret
    ): bool {
        $parameters = self::extractParameters($request);

        $signatureToVerify = $parameters['oauth_signature'];
        unset($parameters['oauth_signature']);

        $signature = self::signRequest(
            $request->withQueryParams($parameters),
            $consumerSecret,
            $tokenSecret,
            $parameters['oauth_signature_method']
        );

        return $signature === $signatureToVerify;
    }

    /**
     * Extracts the oauth parameters either from the Authorization header or
     * from the query string.
     *
     * @throws RuntimeException if any necessary oauth parameter is missing
     */
    public static function extractParameters(
        Request $request,
        array $required = [
            'oauth_consumer_key',
            'oauth_nonce',
            'oauth_signature',
            'oauth_signature_method',
            'oauth_timestamp',
        ]
    ): array {
        $parameters = $request->getQueryParams();

        $header = $request->getHeaderLine('Authorization');
        if ($header && str_starts_with($header, 'OAuth ')) {
            $temp = substr($header, 6);
            $chunks = explode(',', $temp);

            foreach ($chunks as $chunk) {
                [$key, $value] = explode('=', $chunk, 2);
                $value = trim($value, '"');
                $parameters[$key] = rawurldecode($value);
            }
        }

        $missing = array_diff($required, array_keys($parameters));
        if (count($missing) > 0) {
            throw new RuntimeException('Missing oauth parameters ' . implode(', ', $missing));
        }

        return $parameters;
    }

    /**
     * Creates the base string for the signature. It consists of:
     *
     * - The uppercase request method
     * - The request URL
     * - the sorted and urlencoded parameters of the request
     *
     * The urlencoded parts are concatenated together into a single string
     * separated by the '&' character.
     *
     *
     */
    public static function getSignatureBaseString(Request $request): string
    {
        $parameters = $request->getQueryParams();
        ksort($parameters);

        return implode('&', array_map(
            rawurlencode(...),
            [
                strtoupper($request->getMethod()),
                (string) $request->getUri()->withQuery(''),
                http_build_query($parameters, '', '&', PHP_QUERY_RFC3986),
            ]
        ));
    }

    /**
     * Hashes a given text with a given key by the given method.
     *
     * @throws RuntimeException if the given hash method is not supported
     */
    public static function hash(string $method, string $text, string $key): string
    {
        $method = strtolower($method);
        return match ($method) {
            'hmac-sha1'   => base64_encode(hash_hmac('sha1', $text, $key, true)),
            'hmac-sha256' => base64_encode(hash_hmac('sha256', $text, $key, true)),
            'hmac-sha512' => base64_encode(hash_hmac('sha512', $text, $key, true)),

            'plaintext' => $key,

            default => throw new RuntimeException('Unsupported sigature method "' . $method . '"'),
        };
    }
}