HTTPRedirect::receive()   C
last analyzed

Complexity

Conditions 13
Paths 25

Size

Total Lines 78
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 40
c 1
b 0
f 0
nc 25
nop 1
dl 0
loc 78
rs 6.6166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\SAML2\Binding;
6
7
use Exception;
8
use Nyholm\Psr7\Response;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use SimpleSAML\Assert\Assert;
12
use SimpleSAML\SAML2\Binding;
13
use SimpleSAML\SAML2\Binding\RelayStateTrait;
14
use SimpleSAML\SAML2\Compat\ContainerSingleton;
15
use SimpleSAML\SAML2\Constants as C;
16
use SimpleSAML\SAML2\Exception\ProtocolViolationException;
17
use SimpleSAML\SAML2\Utils;
18
use SimpleSAML\SAML2\XML\samlp\AbstractMessage;
19
use SimpleSAML\SAML2\XML\samlp\AbstractRequest;
20
use SimpleSAML\SAML2\XML\samlp\MessageFactory;
21
use SimpleSAML\XML\DOMDocumentFactory;
22
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
23
use SimpleSAML\XMLSecurity\Exception\SignatureVerificationFailedException;
24
use SimpleSAML\XMLSecurity\TestUtils\PEMCertificatesMock;
25
26
use function array_key_exists;
27
use function base64_decode;
28
use function base64_encode;
29
use function gzdeflate;
30
use function gzinflate;
31
use function sprintf;
32
use function str_contains;
33
use function strlen;
34
use function urlencode;
35
36
/**
37
 * Class which implements the HTTP-Redirect binding.
38
 *
39
 * @package simplesamlphp/saml2
40
 */
41
class HTTPRedirect extends Binding
42
{
43
    use RelayStateTrait;
44
45
    /**
46
     * Create the redirect URL for a message.
47
     *
48
     * @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $message The message.
49
     * @return string The URL the user should be redirected to in order to send a message.
50
     */
51
    public function getRedirectURL(AbstractMessage $message): string
52
    {
53
        if ($this->destination === null) {
54
            $destination = $message->getDestination();
55
            if ($destination === null) {
56
                throw new Exception('Cannot build a redirect URL, no destination set.');
57
            }
58
        } else {
59
            $destination = $this->destination;
60
        }
61
62
        $relayState = $this->getRelayState();
63
        $msgStr = $message->toXML();
64
65
        Utils::getContainer()->debugMessage($msgStr, 'out');
66
        $msgStr = $msgStr->ownerDocument?->saveXML($msgStr);
67
68
        $msgStr = gzdeflate($msgStr);
69
        $msgStr = base64_encode($msgStr);
70
71
        /* Build the query string. */
72
73
        if ($message instanceof AbstractRequest) {
74
            $msg = 'SAMLRequest=';
75
        } else {
76
            $msg = 'SAMLResponse=';
77
        }
78
        $msg .= urlencode($msgStr);
79
80
        if ($relayState !== null) {
81
            $msg .= '&RelayState=' . urlencode($relayState);
82
        }
83
84
        $signature = $message->getSignature();
85
        if ($signature !== null) { // add the signature
86
            $msg .= '&SigAlg=' . urlencode($signature->getSignedInfo()->getSignatureMethod()->getAlgorithm());
87
            $msg .= '&Signature=' . urlencode($signature->getSignatureValue()->getContent());
88
        }
89
90
        if (str_contains($destination, '?')) {
91
            $destination .= '&' . $msg;
92
        } else {
93
            $destination .= '?' . $msg;
94
        }
95
96
        return $destination;
97
    }
98
99
100
    /**
101
     * Send a SAML 2 message using the HTTP-Redirect binding.
102
     *
103
     * @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $message
104
     * @return \Psr\Http\Message\ResponseInterface
105
     */
106
    public function send(AbstractMessage $message): ResponseInterface
107
    {
108
        $destination = $this->getRedirectURL($message);
109
        Utils::getContainer()->getLogger()->debug(
110
            'Redirect to ' . strlen($destination) . ' byte URL: ' . $destination,
111
        );
112
        return new Response(303, ['Location' => $destination]);
113
    }
114
115
116
    /**
117
     * Receive a SAML 2 message sent using the HTTP-Redirect binding.
118
     *
119
     * Throws an exception if it is unable receive the message.
120
     *
121
     * @param \Psr\Http\Message\ServerRequestInterface $request
122
     * @return \SimpleSAML\SAML2\XML\samlp\AbstractMessage The received message.
123
     * @throws \Exception
124
     *
125
     * NPath is currently too high but solving that just moves code around.
126
     */
127
    public function receive(ServerRequestInterface $request): AbstractMessage
128
    {
129
        $query = $request->getQueryParams();
130
131
        /**
132
         * Put the SAMLRequest/SAMLResponse from the actual query string into $message,
133
         * and assert that the result from parseQuery() in $query and the parsing of the SignedQuery in $res agree
134
         */
135
        if (array_key_exists('SAMLRequest', $query)) {
136
            $message = $query['SAMLRequest'];
137
            $signedQuery = 'SAMLRequest=' . urlencode($query['SAMLRequest']);
138
        } elseif (array_key_exists('SAMLResponse', $query)) {
139
            $message = $query['SAMLResponse'];
140
            $signedQuery = 'SAMLResponse=' . urlencode($query['SAMLResponse']);
141
        } else {
142
            throw new Exception('Missing SAMLRequest or SAMLResponse parameter.');
143
        }
144
145
        if (array_key_exists('SAMLRequest', $query) && array_key_exists('SAMLResponse', $query)) {
146
            throw new Exception('Both SAMLRequest and SAMLResponse provided.');
147
        }
148
149
        if (isset($query['SAMLEncoding']) && $query['SAMLEncoding'] !== C::BINDING_HTTP_REDIRECT_DEFLATE) {
150
            throw new Exception(sprintf('Unknown SAMLEncoding: %s', $query['SAMLEncoding']));
151
        }
152
153
        $message = base64_decode($message, true);
154
        if ($message === false) {
155
            throw new Exception('Error while base64 decoding SAML message.');
156
        }
157
158
        $message = gzinflate($message);
159
        if ($message === false) {
160
            throw new Exception('Error while inflating SAML message.');
161
        }
162
163
        $document = DOMDocumentFactory::fromString($message);
164
        Utils::getContainer()->debugMessage($document->documentElement, 'in');
165
        $message = MessageFactory::fromXML($document->documentElement);
166
167
        if (array_key_exists('RelayState', $query)) {
168
            $this->setRelayState($query['RelayState']);
169
            $signedQuery .= '&RelayState=' . urlencode($query['RelayState']);
170
        }
171
172
        if (!array_key_exists('Signature', $query)) {
173
            return $message;
174
        }
175
176
        /**
177
         * 3.4.5.2 - SAML Bindings
178
         *
179
         * If the message is signed, the Destination XML attribute in the root SAML element of the protocol
180
         * message MUST contain the URL to which the sender has instructed the user agent to deliver the
181
         * message.
182
         */
183
        Assert::notNull($message->getDestination(), ProtocolViolationException::class);
184
        // Validation of the Destination must be done upstream
185
186
        if (!array_key_exists('SigAlg', $query)) {
187
            throw new Exception('Missing signature algorithm.');
188
        } else {
189
            $signedQuery .= '&SigAlg=' . urlencode($query['SigAlg']);
190
        }
191
192
        $container = ContainerSingleton::getInstance();
193
        $blacklist = $container->getBlacklistedEncryptionAlgorithms();
194
        $verifier = (new SignatureAlgorithmFactory($blacklist))->getAlgorithm(
0 ignored issues
show
Bug introduced by
It seems like $blacklist can also be of type null; however, parameter $blacklist of SimpleSAML\XMLSecurity\A...mFactory::__construct() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

194
        $verifier = (new SignatureAlgorithmFactory(/** @scrutinizer ignore-type */ $blacklist))->getAlgorithm(
Loading history...
195
            $query['SigAlg'],
196
            // TODO:  Need to use the key from the metadata
197
            PEMCertificatesMock::getPublicKey(PEMCertificatesMock::SELFSIGNED_PUBLIC_KEY),
198
        );
199
200
        if ($verifier->verify($signedQuery, base64_decode($query['Signature'])) === false) {
201
            throw new SignatureVerificationFailedException('Failed to verify signature.');
202
        }
203
204
        return $message;
205
    }
206
}
207