summaryrefslogtreecommitdiffstats
path: root/apps/user_ldap/lib/Migration/Version1130Date20211102154716.php
blob: 5c5ed44c8992c432a2f4d76d500ada410c43d128 (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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
<?php

declare(strict_types=1);

/**
 * @copyright Copyright (c) 2020 Joas Schilling <coding@schilljs.com>
 *
 * @author Côme Chilliet <come.chilliet@nextcloud.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OCA\User_LDAP\Migration;

use Closure;
use Generator;
use OCP\DB\Exception;
use OCP\DB\ISchemaWrapper;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\DB\Types;
use OCP\IDBConnection;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
use Psr\Log\LoggerInterface;

class Version1130Date20211102154716 extends SimpleMigrationStep {

	/** @var IDBConnection */
	private $dbc;
	/** @var LoggerInterface */
	private $logger;
	/** @var string[] */
	private $hashColumnAddedToTables = [];

	public function __construct(IDBConnection $dbc, LoggerInterface $logger) {
		$this->dbc = $dbc;
		$this->logger = $logger;
	}

	public function getName() {
		return 'Adjust LDAP user and group ldap_dn column lengths and add ldap_dn_hash columns';
	}

	public function preSchemaChange(IOutput $output, \Closure $schemaClosure, array $options) {
		foreach (['ldap_user_mapping', 'ldap_group_mapping'] as $tableName) {
			$this->processDuplicateUUIDs($tableName);
		}

		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();
		if ($schema->hasTable('ldap_group_mapping_backup')) {
			// Previous upgrades of a broken release might have left an incomplete
			// ldap_group_mapping_backup table. No need to recreate, but it
			// should be empty.
			// TRUNCATE is not available from Query Builder, but faster than DELETE FROM.
			$sql = $this->dbc->getDatabasePlatform()->getTruncateTableSQL('`*PREFIX*ldap_group_mapping_backup`', false);
			$this->dbc->executeStatement($sql);
		}
	}

	/**
	 * @param IOutput $output
	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
	 * @param array $options
	 * @return null|ISchemaWrapper
	 */
	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();

		$changeSchema = false;
		foreach (['ldap_user_mapping', 'ldap_group_mapping'] as $tableName) {
			$table = $schema->getTable($tableName);
			if (!$table->hasColumn('ldap_dn_hash')) {
				$table->addColumn('ldap_dn_hash', Types::STRING, [
					'notnull' => false,
					'length' => 64,
				]);
				$changeSchema = true;
				$this->hashColumnAddedToTables[] = $tableName;
			}
			$column = $table->getColumn('ldap_dn');
			if ($tableName === 'ldap_user_mapping') {
				if ($column->getLength() < 4000) {
					$column->setLength(4000);
					$changeSchema = true;
				}

				if ($table->hasIndex('ldap_dn_users')) {
					$table->dropIndex('ldap_dn_users');
					$changeSchema = true;
				}
				if (!$table->hasIndex('ldap_user_dn_hashes')) {
					$table->addUniqueIndex(['ldap_dn_hash'], 'ldap_user_dn_hashes');
					$changeSchema = true;
				}
				if (!$table->hasIndex('ldap_user_directory_uuid')) {
					$table->addUniqueIndex(['directory_uuid'], 'ldap_user_directory_uuid');
					$changeSchema = true;
				}
			} elseif (!$schema->hasTable('ldap_group_mapping_backup')) {
				// We need to copy the table twice to be able to change primary key, prepare the backup table
				$table2 = $schema->createTable('ldap_group_mapping_backup');
				$table2->addColumn('ldap_dn', Types::STRING, [
					'notnull' => true,
					'length' => 4000,
					'default' => '',
				]);
				$table2->addColumn('owncloud_name', Types::STRING, [
					'notnull' => true,
					'length' => 64,
					'default' => '',
				]);
				$table2->addColumn('directory_uuid', Types::STRING, [
					'notnull' => true,
					'length' => 255,
					'default' => '',
				]);
				$table2->addColumn('ldap_dn_hash', Types::STRING, [
					'notnull' => false,
					'length' => 64,
				]);
				$table2->setPrimaryKey(['owncloud_name'], 'lgm_backup_primary');
				$changeSchema = true;
			}
		}

		return $changeSchema ? $schema : null;
	}

	/**
	 * @param IOutput $output
	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
	 * @param array $options
	 */
	public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options) {
		$this->handleDNHashes('ldap_group_mapping');
		$this->handleDNHashes('ldap_user_mapping');
	}

	protected function handleDNHashes(string $table): void {
		$select = $this->getSelectQuery($table);
		$update = $this->getUpdateQuery($table);

		$result = $select->executeQuery();
		while ($row = $result->fetch()) {
			$dnHash = hash('sha256', $row['ldap_dn'], false);
			$update->setParameter('name', $row['owncloud_name']);
			$update->setParameter('dn_hash', $dnHash);
			try {
				$update->executeStatement();
			} catch (Exception $e) {
				$this->logger->error('Failed to add hash "{dnHash}" ("{name}" of {table})',
					[
						'app' => 'user_ldap',
						'name' => $row['owncloud_name'],
						'dnHash' => $dnHash,
						'table' => $table,
						'exception' => $e,
					]
				);
			}
		}
		$result->closeCursor();
	}

	protected function getSelectQuery(string $table): IQueryBuilder {
		$qb = $this->dbc->getQueryBuilder();
		$qb->select('owncloud_name', 'ldap_dn')
			->from($table);

		// when added we may run into risk that it's read from a DB node
		// where the column is not present. Then the where clause is also
		// not necessary since all rows qualify.
		if (!in_array($table, $this->hashColumnAddedToTables, true)) {
			$qb->where($qb->expr()->isNull('ldap_dn_hash'));
		}

		return $qb;
	}

	protected function getUpdateQuery(string $table): IQueryBuilder {
		$qb = $this->dbc->getQueryBuilder();
		$qb->update($table)
			->set('ldap_dn_hash', $qb->createParameter('dn_hash'))
			->where($qb->expr()->eq('owncloud_name', $qb->createParameter('name')));
		return $qb;
	}

	/**
	 * @throws Exception
	 */
	protected function processDuplicateUUIDs(string $table): void {
		$uuids = $this->getDuplicatedUuids($table);
		$idsWithUuidToInvalidate = [];
		foreach ($uuids as $uuid) {
			array_push($idsWithUuidToInvalidate, ...$this->getNextcloudIdsByUuid($table, $uuid));
		}
		$this->invalidateUuids($table, $idsWithUuidToInvalidate);
	}

	/**
	 * @throws Exception
	 */
	protected function invalidateUuids(string $table, array $idList): void {
		$update = $this->dbc->getQueryBuilder();
		$update->update($table)
			->set('directory_uuid', $update->createParameter('invalidatedUuid'))
			->where($update->expr()->eq('owncloud_name', $update->createParameter('nextcloudId')));

		while ($nextcloudId = array_shift($idList)) {
			$update->setParameter('nextcloudId', $nextcloudId);
			$update->setParameter('invalidatedUuid', 'invalidated_' . \bin2hex(\random_bytes(6)));
			try {
				$update->executeStatement();
				$this->logger->warning(
					'LDAP user or group with ID {nid} has a duplicated UUID value which therefore was invalidated. You may double-check your LDAP configuration and trigger an update of the UUID.',
					[
						'app' => 'user_ldap',
						'nid' => $nextcloudId,
					]
				);
			} catch (Exception $e) {
				// Catch possible, but unlikely duplications if new invalidated errors.
				// There is the theoretical chance of an infinity loop is, when
				// the constraint violation has a different background. I cannot
				// think of one at the moment.
				if ($e->getReason() !== Exception::REASON_CONSTRAINT_VIOLATION) {
					throw $e;
				}
				$idList[] = $nextcloudId;
			}
		}
	}

	/**
	 * @throws \OCP\DB\Exception
	 * @return array<string>
	 */
	protected function getNextcloudIdsByUuid(string $table, string $uuid): array {
		$select = $this->dbc->getQueryBuilder();
		$select->select('owncloud_name')
			->from($table)
			->where($select->expr()->eq('directory_uuid', $select->createNamedParameter($uuid)));

		$result = $select->executeQuery();
		$idList = [];
		while (($id = $result->fetchOne()) !== false) {
			$idList[] = $id;
		}
		$result->closeCursor();
		return $idList;
	}

	/**
	 * @return Generator<string>
	 * @throws \OCP\DB\Exception
	 */
	protected function getDuplicatedUuids(string $table): Generator {
		$select = $this->dbc->getQueryBuilder();
		$select->select('directory_uuid')
			->from($table)
			->groupBy('directory_uuid')
			->having($select->expr()->gt($select->func()->count('owncloud_name'), $select->createNamedParameter(1)));

		$result = $select->executeQuery();
		while (($uuid = $result->fetchOne()) !== false) {
			yield $uuid;
		}
		$result->closeCursor();
	}
}