aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Setup/PostgreSQL.php
blob: 4ece8957ce63a5ee91f796ca625f9b5da2fccc65 (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
<?php

/**
 * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
 * SPDX-License-Identifier: AGPL-3.0-only
 */
namespace OC\Setup;

use OC\DatabaseException;
use OC\DB\Connection;
use OC\DB\QueryBuilder\Literal;
use OCP\Security\ISecureRandom;

class PostgreSQL extends AbstractDatabase {
	public $dbprettyname = 'PostgreSQL';

	/**
	 * @param string $username
	 * @throws \OC\DatabaseSetupException
	 */
	public function setupDatabase($username) {
		try {
			$connection = $this->connect([
				'dbname' => 'postgres'
			]);
			if ($this->tryCreateDbUser) {
				//check for roles creation rights in postgresql
				$builder = $connection->getQueryBuilder();
				$builder->automaticTablePrefix(false);
				$query = $builder
					->select('rolname')
					->from('pg_roles')
					->where($builder->expr()->eq('rolcreaterole', new Literal('TRUE')))
					->andWhere($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));

				try {
					$result = $query->execute();
					$canCreateRoles = $result->rowCount() > 0;
				} catch (DatabaseException $e) {
					$canCreateRoles = false;
				}

				if ($canCreateRoles) {
					$connectionMainDatabase = $this->connect();
					//use the admin login data for the new database user

					//add prefix to the postgresql user name to prevent collisions
					$this->dbUser = 'oc_' . strtolower($username);
					//create a new password so we don't need to store the admin config in the config file
					$this->dbPassword = \OC::$server->get(ISecureRandom::class)->generate(30, ISecureRandom::CHAR_ALPHANUMERIC);

					$this->createDBUser($connection);

					// Go to the main database and grant create on the public schema
					// The code below is implemented to make installing possible with PostgreSQL version 15:
					// https://www.postgresql.org/docs/release/15.0/
					// From the release notes: For new databases having no need to defend against insider threats, granting CREATE permission will yield the behavior of prior releases
					// Therefore we assume that the database is only used by one user/service which is Nextcloud
					// Additional services should get installed in a separate database in order to stay secure
					// Also see https://www.postgresql.org/docs/15/ddl-schemas.html#DDL-SCHEMAS-PATTERNS
					$connectionMainDatabase->executeQuery('GRANT CREATE ON SCHEMA public TO "' . addslashes($this->dbUser) . '"');
					$connectionMainDatabase->close();
				}
			}

			$this->config->setValues([
				'dbuser' => $this->dbUser,
				'dbpassword' => $this->dbPassword,
			]);

			//create the database
			$this->createDatabase($connection);
			// the connection to dbname=postgres is not needed anymore
			$connection->close();
		} catch (\Exception $e) {
			$this->logger->warning('Error trying to connect as "postgres", assuming database is setup and tables need to be created', [
				'exception' => $e,
			]);
			$this->config->setValues([
				'dbuser' => $this->dbUser,
				'dbpassword' => $this->dbPassword,
			]);
		}

		// connect to the database (dbname=$this->dbname) and check if it needs to be filled
		$this->dbUser = $this->config->getValue('dbuser');
		$this->dbPassword = $this->config->getValue('dbpassword');
		$connection = $this->connect();
		try {
			$connection->connect();
		} catch (\Exception $e) {
			$this->logger->error($e->getMessage(), [
				'exception' => $e,
			]);
			throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL Login and/or password not valid'),
				$this->trans->t('You need to enter details of an existing account.'), 0, $e);
		}
	}

	private function createDatabase(Connection $connection) {
		if (!$this->databaseExists($connection)) {
			//The database does not exists... let's create it
			$query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER \"" . addslashes($this->dbUser) . '"');
			try {
				$query->execute();
			} catch (DatabaseException $e) {
				$this->logger->error('Error while trying to create database', [
					'exception' => $e,
				]);
			}
		} else {
			$query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
			try {
				$query->execute();
			} catch (DatabaseException $e) {
				$this->logger->error('Error while trying to restrict database permissions', [
					'exception' => $e,
				]);
			}
		}
	}

	private function userExists(Connection $connection) {
		$builder = $connection->getQueryBuilder();
		$builder->automaticTablePrefix(false);
		$query = $builder->select('*')
			->from('pg_roles')
			->where($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
		$result = $query->execute();
		return $result->rowCount() > 0;
	}

	private function databaseExists(Connection $connection) {
		$builder = $connection->getQueryBuilder();
		$builder->automaticTablePrefix(false);
		$query = $builder->select('datname')
			->from('pg_database')
			->where($builder->expr()->eq('datname', $builder->createNamedParameter($this->dbName)));
		$result = $query->execute();
		return $result->rowCount() > 0;
	}

	private function createDBUser(Connection $connection) {
		$dbUser = $this->dbUser;
		try {
			$i = 1;
			while ($this->userExists($connection)) {
				$i++;
				$this->dbUser = $dbUser . $i;
			}

			// create the user
			$query = $connection->prepare("CREATE USER \"" . addslashes($this->dbUser) . "\" CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
			$query->execute();
			if ($this->databaseExists($connection)) {
				$query = $connection->prepare('GRANT CONNECT ON DATABASE ' . addslashes($this->dbName) . ' TO "' . addslashes($this->dbUser) . '"');
				$query->execute();
			}
		} catch (DatabaseException $e) {
			$this->logger->error('Error while trying to create database user', [
				'exception' => $e,
			]);
		}
	}
}