Passed
Pull Request — master (#45)
by
unknown
12:36
created

UrlTrait::parseQueryParameters()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 10
c 3
b 0
f 0
dl 0
loc 19
rs 9.2222
cc 6
nc 12
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\casserver\Controller\Traits;
6
7
use SimpleSAML\Configuration;
8
use SimpleSAML\Logger;
9
use SimpleSAML\Module\casserver\Cas\ServiceValidator;
10
use SimpleSAML\Module\casserver\Cas\TicketValidator;
11
use SimpleSAML\Module\casserver\Http\XmlResponse;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\HttpFoundation\Response;
14
15
trait UrlTrait
16
{
17
    /**
18
     * @deprecated
19
     * @see ServiceValidator
20
     * @param string $service
21
     * @param array $legal_service_urls
22
     * @return bool
23
     */
24
    public function checkServiceURL(string $service, array $legal_service_urls): bool
25
    {
26
        //delegate to ServiceValidator until all references to this can be cleaned up
27
        $config = Configuration::loadFromArray(['legal_service_urls' => $legal_service_urls]);
28
        $serviceValidator = new ServiceValidator($config);
29
        return $serviceValidator->checkServiceURL($service) !== null;
30
    }
31
32
    /**
33
     * @param string $parameter
34
     * @return string
35
     */
36
    public function sanitize(string $parameter): string
37
    {
38
        return TicketValidator::sanitize($parameter);
39
    }
40
41
    /**
42
     * Parse the query Parameters from $_GET global and return them in an array.
43
     *
44
     * @param   Request     $request
45
     * @param   array|null  $sessionTicket
46
     *
47
     * @return array
48
     */
49
    public function parseQueryParameters(Request $request, ?array $sessionTicket): array
50
    {
51
        $forceAuthn = $this->getRequestParam($request, 'renew');
52
        $sessionRenewId = $sessionTicket ? $sessionTicket['renewId'] : null;
53
54
        $queryParameters = $request->query->all();
55
        $requestParameters = $request->request->all();
56
57
        $query = array_merge($requestParameters, $queryParameters);
58
59
        if ($sessionRenewId && $forceAuthn) {
60
            $query['renewId'] = $sessionRenewId;
61
        }
62
63
        if (isset($query['language'])) {
64
            $query['language'] = is_string($query['language']) ? $query['language'] : null;
65
        }
66
67
        return $query;
68
    }
69
70
    /**
71
     * @param   Request  $request
72
     * @param   string   $paramName
73
     *
74
     * @return string|int|array|null
75
     */
76
    public function getRequestParam(Request $request, string $paramName): string|int|array|null
77
    {
78
        return $request->query->get($paramName) ?? $request->request->get($paramName) ?? null;
79
    }
80
81
    /**
82
     * @param   Request      $request
83
     * @param   string       $method
84
     * @param   bool         $renew
85
     * @param   string|null  $target
86
     * @param   string|null  $ticket
87
     * @param   string|null  $service
88
     * @param   string|null  $pgtUrl
89
     *
90
     * @return XmlResponse
91
     */
92
    public function validate(
93
        Request $request,
94
        string $method,
95
        bool $renew = false,
96
        ?string $target = null,
97
        ?string $ticket = null,
98
        ?string $service = null,
99
        ?string $pgtUrl = null,
100
    ): XmlResponse {
101
        $forceAuthn = $renew;
102
        $serviceUrl = $service ?? $target ?? null;
103
104
        // Check if any of the required query parameters are missing
105
        if ($serviceUrl === null || $ticket === null) {
106
            $messagePostfix = $serviceUrl === null ? 'service' : 'ticket';
107
            $message        = "casserver: Missing service parameter: [{$messagePostfix}]";
108
            Logger::debug($message);
109
110
            return new XmlResponse(
111
                (string)$this->cas20Protocol->getValidateFailureResponse(C::ERR_INVALID_SERVICE, $message),
0 ignored issues
show
Bug introduced by
The type SimpleSAML\Module\casserver\Controller\Traits\C was not found. Did you mean C? If so, make sure to prefix the type with \.
Loading history...
112
                Response::HTTP_BAD_REQUEST,
113
            );
114
        }
115
116
        try {
117
            // Get the service ticket
118
            // `getTicket` uses the unserializable method and Objects may throw Throwables in their
119
            // unserialization handlers.
120
            $serviceTicket = $this->ticketStore->getTicket($ticket);
121
            // Delete the ticket
122
            $this->ticketStore->deleteTicket($ticket);
123
        } catch (\Exception $e) {
124
            $message = 'casserver:serviceValidate: internal server error. ' . var_export($e->getMessage(), true);
125
            Logger::error($message);
126
127
            return new XmlResponse(
128
                (string)$this->cas20Protocol->getValidateFailureResponse(C::ERR_INVALID_SERVICE, $message),
129
                Response::HTTP_INTERNAL_SERVER_ERROR,
130
            );
131
        }
132
133
        $failed  = false;
134
        $message = '';
135
        if (empty($serviceTicket)) {
136
            // No ticket
137
            $message = 'ticket: ' . var_export($ticket, true) . ' not recognized';
138
            $failed  = true;
139
        } elseif ($method === 'serviceValidate' && $this->ticketFactory->isProxyTicket($serviceTicket)) {
140
            $message = 'Ticket ' . var_export($_GET['ticket'], true) .
141
                ' is a proxy ticket. Use proxyValidate instead.';
142
            $failed  = true;
143
        } elseif (!$this->ticketFactory->isServiceTicket($serviceTicket)) {
144
            // This is not a service ticket
145
            $message = 'ticket: ' . var_export($ticket, true) . ' is not a service ticket';
146
            $failed  = true;
147
        } elseif ($this->ticketFactory->isExpired($serviceTicket)) {
148
            // the ticket has expired
149
            $message = 'Ticket has ' . var_export($ticket, true) . ' expired';
150
            $failed  = true;
151
        } elseif ($this->sanitize($serviceTicket['service']) !== $this->sanitize($serviceUrl)) {
152
            // The service url we passed to the query parameters does not match the one in the ticket.
153
            $message = 'Mismatching service parameters: expected ' .
154
                var_export($serviceTicket['service'], true) .
155
                ' but was: ' . var_export($serviceUrl, true);
156
            $failed  = true;
157
        } elseif ($forceAuthn && !$serviceTicket['forceAuthn']) {
158
            // If `forceAuthn` is required but not set in the ticket
159
            $message = 'Ticket was issued from single sign on session';
160
            $failed  = true;
161
        }
162
163
        if ($failed) {
164
            $finalMessage = 'casserver:validate: ' . $message;
165
            Logger::error($finalMessage);
166
167
            return new XmlResponse(
168
                (string)$this->cas20Protocol->getValidateFailureResponse(C::ERR_INVALID_SERVICE, $message),
169
                Response::HTTP_BAD_REQUEST,
170
            );
171
        }
172
173
        $attributes = $serviceTicket['attributes'];
174
        $this->cas20Protocol->setAttributes($attributes);
175
176
        if (isset($pgtUrl)) {
177
            $sessionTicket = $this->ticketStore->getTicket($serviceTicket['sessionId']);
178
            if (
179
                $sessionTicket !== null
180
                && $this->ticketFactory->isSessionTicket($sessionTicket)
181
                && !$this->ticketFactory->isExpired($sessionTicket)
182
            ) {
183
                $proxyGrantingTicket = $this->ticketFactory->createProxyGrantingTicket(
184
                    [
185
                        'userName' => $serviceTicket['userName'],
186
                        'attributes' => $attributes,
187
                        'forceAuthn' => false,
188
                        'proxies' => array_merge(
189
                            [$serviceUrl],
190
                            $serviceTicket['proxies'],
191
                        ),
192
                        'sessionId' => $serviceTicket['sessionId'],
193
                    ],
194
                );
195
                try {
196
                    $this->httpUtils->fetch(
197
                        $pgtUrl . '?pgtIou=' . $proxyGrantingTicket['iou'] . '&pgtId=' . $proxyGrantingTicket['id'],
198
                    );
199
200
                    $this->cas20Protocol->setProxyGrantingTicketIOU($proxyGrantingTicket['iou']);
201
202
                    $this->ticketStore->addTicket($proxyGrantingTicket);
203
                } catch (\Exception $e) {
204
                    // Fall through
205
                }
206
            }
207
        }
208
209
        return new XmlResponse(
210
            (string)$this->cas20Protocol->getValidateSuccessResponse($serviceTicket['userName']),
211
            Response::HTTP_OK,
212
        );
213
    }
214
}
215