Skip to content

Commit

Permalink
Fix Privileges for public Schema in PostgreSQL 15+ (#339)
Browse files Browse the repository at this point in the history
  • Loading branch information
devsarfo authored Nov 7, 2024
1 parent 82933e2 commit 945c2e7
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
5 changes: 5 additions & 0 deletions app/SSH/Services/Database/AbstractDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,15 @@ public function deleteUser(string $username, string $host): void
public function link(string $username, string $host, array $databases): void
{
$ssh = $this->service->server->ssh();
$version = $this->service->version;

foreach ($databases as $database) {
$ssh->exec(
$this->getScript($this->getScriptsDir().'/link.sh', [
'username' => $username,
'host' => $host,
'database' => $database,
'version' => $version,
]),
'link-user-to-database'
);
Expand All @@ -132,10 +134,13 @@ public function link(string $username, string $host, array $databases): void

public function unlink(string $username, string $host): void
{
$version = $this->service->version;

$this->service->server->ssh()->exec(
$this->getScript($this->getScriptsDir().'/unlink.sh', [
'username' => $username,
'host' => $host,
'version' => $version,
]),
'unlink-user-from-databases'
);
Expand Down
15 changes: 13 additions & 2 deletions app/SSH/Services/Database/scripts/postgresql/link.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
if ! sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE __database__ TO __username__;"; then
USER_TO_LINK='__username__'
DB_NAME='__database__'
DB_VERSION='__version__'

if ! sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE \"$DB_NAME\" TO $USER_TO_LINK;"; then
echo 'VITO_SSH_ERROR' && exit 1
fi

echo "Linking to __database__ finished"
# Check if PostgreSQL version is 15 or greater
if [ "$DB_VERSION" -ge 15 ]; then
if ! sudo -u postgres psql -d "$DB_NAME" -c "GRANT USAGE, CREATE ON SCHEMA public TO $USER_TO_LINK;"; then
echo 'VITO_SSH_ERROR' && exit 1
fi
fi

echo "Linking to $DB_NAME finished"
6 changes: 6 additions & 0 deletions app/SSH/Services/Database/scripts/postgresql/unlink.sh
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
USER_TO_REVOKE='__username__'
DB_VERSION='__version__'

DATABASES=$(sudo -u postgres psql -t -c "SELECT datname FROM pg_database WHERE datistemplate = false;")

for DB in $DATABASES; do
echo "Revoking privileges in database: $DB"
sudo -u postgres psql -d "$DB" -c "REVOKE ALL PRIVILEGES ON DATABASE \"$DB\" FROM $USER_TO_REVOKE;"

# Check if PostgreSQL version is 15 or greater
if [ "$DB_VERSION" -ge 15 ]; then
sudo -u postgres psql -d "$DB" -c "REVOKE USAGE, CREATE ON SCHEMA public FROM $USER_TO_REVOKE;"
fi
done

echo "Privileges revoked from $USER_TO_REVOKE"

0 comments on commit 945c2e7

Please sign in to comment.