Passed
Pull Request — master (#2)
by Tim
02:02
created

MetaEditor::main()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 45
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 27
c 1
b 0
f 0
nc 9
nop 1
dl 0
loc 45
rs 8.8657
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\metaedit\Controller;
6
7
use Exception;
8
use SAML2\Constants;
9
use SimpleSAML\Auth;
10
use SimpleSAML\Configuration;
11
use SimpleSAML\Error;
12
use SimpleSAML\Metadata;
13
use SimpleSAML\Module\metaedit\MetaEditor as Editor;
14
use SimpleSAML\Session;
15
use SimpleSAML\Utils;
16
use SimpleSAML\XHTML\Template;
17
use Symfony\Component\HttpFoundation\Request;
18
19
use function array_key_exists;
20
use function array_pop;
21
22
/**
23
 * Controller class for the metaedit module.
24
 *
25
 * This class serves the different views available in the module.
26
 *
27
 * @package simplesamlphp/simplesamlphp-module-metaedit
28
 */
29
class MetaEditor
30
{
31
    /** @var \SimpleSAML\Configuration */
32
    protected Configuration $config;
33
34
    /** @var \SimpleSAML\Session */
35
    protected Session $session;
36
37
38
    /**
39
     * Controller constructor.
40
     *
41
     * It initializes the global configuration and session for the controllers implemented here.
42
     *
43
     * @param \SimpleSAML\Configuration $config The configuration to use by the controllers.
44
     * @param \SimpleSAML\Session $session The session to use by the controllers.
45
     *
46
     * @throws \Exception
47
     */
48
    public function __construct(
49
        Configuration $config,
50
        Session $session
51
    ) {
52
        $this->config = $config;
53
        $this->session = $session;
54
    }
55
56
57
    /**
58
     * Main index
59
     *
60
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
61
     *
62
     * @return \SimpleSAML\XHTML\Template
63
     */
64
    public function main(Request $request): Template
65
    {
66
        /* Load simpleSAMLphp, configuration and metadata */
67
        $moduleConfig = Configuration::getConfig('module_metaedit.php');
68
69
        $authsource = $moduleConfig->getValue('auth', 'login-admin');
70
        $useridattr = $moduleConfig->getValue('useridattr', 'eduPersonPrincipalName');
71
72
        $as = new Auth\Simple($authsource);
73
        $as->requireAuth();
74
        $attributes = $as->getAttributes();
75
76
        // Check if userid exists
77
        if (!isset($attributes[$useridattr])) {
78
            throw new Error\Exception('User ID is missing');
79
        }
80
        $userid = $attributes[$useridattr][0];
81
82
        $mdh = new Metadata\MetaDataStorageHandlerSerialize($moduleConfig->getArray('metahandlerConfig', []));
83
84
        $delete = $request->get('delete');
85
        if ($delete !== null) {
86
            $premetadata = $mdh->getMetadata($delete, 'saml20-sp-remote');
87
            $this->requireOwnership($premetadata, $userid);
0 ignored issues
show
Bug introduced by
It seems like $premetadata can also be of type null; however, parameter $metadata of SimpleSAML\Module\metaed...tor::requireOwnership() 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

87
            $this->requireOwnership(/** @scrutinizer ignore-type */ $premetadata, $userid);
Loading history...
88
            $mdh->deleteMetadata($delete, 'saml20-sp-remote');
89
        }
90
91
        $list = $mdh->getMetadataSet('saml20-sp-remote');
92
93
        $slist = ['mine' => [], 'others' => []];
94
        foreach ($list as $listitem) {
95
            if (array_key_exists('owner', $listitem)) {
96
                if ($listitem['owner'] === $userid) {
97
                    $slist['mine'][] = $listitem;
98
                    continue;
99
                }
100
            }
101
            $slist['others'][] = $listitem;
102
        }
103
104
        $t = new Template($this->config, 'metaedit:metalist.twig');
105
        $t->data['metadata'] = $slist;
106
        $t->data['userid'] = $userid;
107
108
        return $t;
109
    }
110
111
112
    /**
113
     * Editor
114
     *
115
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
116
     *
117
     * @return \SimpleSAML\XHTML\Template
118
     */
119
    public function edit(Request $request): Template
120
    {
121
        /* Load configuration and metadata */
122
        $moduleConfig = Configuration::getConfig('module_metaedit.php');
123
124
        $authsource = $moduleConfig->getValue('auth', 'login-admin');
125
        $useridattr = $moduleConfig->getValue('useridattr', 'eduPersonPrincipalName');
126
127
        $as = new Auth\Simple($authsource);
128
        $as->requireAuth();
129
130
        $attributes = $as->getAttributes();
131
        // Check if userid exists
132
        if (!isset($attributes[$useridattr])) {
133
            throw new Error\Exception('User ID is missing');
134
        }
135
        $userid = $attributes[$useridattr][0];
136
137
        $entityId = $request->get('entityid');
138
        $xmlMetadata = $request->get('xmlmetadata');
139
140
        $mdh = new Metadata\MetaDataStorageHandlerSerialize($moduleConfig->getArray('metahandlerConfig', []));
141
142
        if ($entityId !== null) {
143
            $metadata = $mdh->getMetadata($entityId, 'saml20-sp-remote');
144
            $this->requireOwnership($metadata, $userid);
0 ignored issues
show
Bug introduced by
It seems like $metadata can also be of type null; however, parameter $metadata of SimpleSAML\Module\metaed...tor::requireOwnership() 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

144
            $this->requireOwnership(/** @scrutinizer ignore-type */ $metadata, $userid);
Loading history...
145
        } elseif ($xmlMetadata !== null) {
146
            $xmlUtils = new Utils\XML();
147
            $xmlUtils->checkSAMLMessage($xmlMetadata, 'saml-meta');
148
            $entities = Metadata\SAMLParser::parseDescriptorsString($xmlMetadata);
149
            $entity = array_pop($entities);
150
            $metadata =  $entity->getMetadata20SP();
151
152
            /* Trim metadata endpoint arrays. */
153
            $metadata['AssertionConsumerService'] = [
154
                Utils\Config\Metadata::getDefaultEndpoint(
155
                    $metadata['AssertionConsumerService'],
156
                    [Constants::BINDING_HTTP_POST]
157
                )
158
            ];
159
            $metadata['SingleLogoutService'] = [
160
                Utils\Config\Metadata::getDefaultEndpoint(
161
                    $metadata['SingleLogoutService'],
162
                    [Constants::BINDING_HTTP_REDIRECT]
163
                )
164
            ];
165
        } else {
166
            $metadata = [
167
                'owner' => $userid,
168
            ];
169
        }
170
171
        $editor = new Editor();
172
173
        if ($request->get('submit')) {
174
            $editor->checkForm($request->request->all());
175
            $metadata = $editor->formToMeta($request->request->all(), [], ['owner' => $userid]);
176
            $wasEntityId = $request->get('was-entityid');
177
            if (($wasEntityId !== null) && ($wasEntityId !== $metadata['entityid'])) {
178
                $premetadata = $mdh->getMetadata($wasEntityId, 'saml20-sp-remote');
179
                $this->requireOwnership($premetadata, $userid);
180
                $mdh->deleteMetadata($wasEntityId, 'saml20-sp-remote');
181
            }
182
183
            try {
184
                $testmetadata = $mdh->getMetadata($metadata['entityid'], 'saml20-sp-remote');
185
            } catch (Exception $e) {
186
                // catch
187
                $testmetadata = null;
188
            }
189
190
            if ($testmetadata) {
191
                $this->requireOwnership($testmetadata, $userid);
192
            }
193
194
            $result = $mdh->saveMetadata($metadata['entityid'], 'saml20-sp-remote', $metadata);
195
            if ($result === false) {
196
                throw new Error\Exception("Could not save metadata. See log for details");
197
            }
198
199
            return new Template($this->config, 'metaedit:saved.twig');
200
        }
201
202
        $form = $editor->metaToForm($metadata);
203
204
        $t = new Template($this->config, 'metaedit:formedit.twig');
205
        $t->data['form'] = $form;
206
207
        return $t;
208
    }
209
210
211
    /**
212
     * Importer
213
     *
214
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
215
     *
216
     * @return \SimpleSAML\XHTML\Template
217
     */
218
    public function import(Request $request): Template
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

218
    public function import(/** @scrutinizer ignore-unused */ Request $request): Template

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
219
    {
220
        /* Load simpleSAMLphp, configuration and metadata */
221
        return new Template($this->config, 'metaedit:xmlimport.twig');
222
    }
223
224
225
    /**
226
     * @param array $metadata
227
     * @param string $userid
228
     * @return void
229
     */
230
    private function requireOwnership(array $metadata, string $userid): void
231
    {
232
        if (!isset($metadata['owner'])) {
233
            throw new Exception('Metadata has no owner. Which means no one is granted access, not even you.');
234
        }
235
236
        if ($metadata['owner'] !== $userid) {
237
            throw new Exception(
238
                'Metadata has an owner that is not equal to your userid, hence you are not granted access.'
239
            );
240
        }
241
    }
242
}
243