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

UrlTrait   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 197
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 28
eloc 88
c 3
b 0
f 0
dl 0
loc 197
rs 10

5 Methods

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