Skip to content

Commit d56c485

Browse files
[MISC] Define charm constants (#862)
1 parent f3b7667 commit d56c485

File tree

7 files changed

+51
-25
lines changed

7 files changed

+51
-25
lines changed

lib/charms/postgresql_k8s/v0/postgresql.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@
3535

3636
# Increment this PATCH version before using `charmcraft publish-lib` or reset
3737
# to 0 if you are raising the major API version
38-
LIBPATCH = 42
38+
LIBPATCH = 43
39+
40+
# Groups to distinguish database permissions
41+
PERMISSIONS_GROUP_ADMIN = "admin"
3942

4043
INVALID_EXTRA_USER_ROLE_BLOCKING_MESSAGE = "invalid role(s) for extra user roles"
4144

@@ -187,7 +190,7 @@ def create_database(
187190
Identifier(database)
188191
)
189192
)
190-
for user_to_grant_access in [user, "admin", *self.system_users]:
193+
for user_to_grant_access in [user, PERMISSIONS_GROUP_ADMIN, *self.system_users]:
191194
cursor.execute(
192195
SQL("GRANT ALL PRIVILEGES ON DATABASE {} TO {};").format(
193196
Identifier(database), Identifier(user_to_grant_access)
@@ -236,15 +239,17 @@ def create_user(
236239
roles = privileges = None
237240
if extra_user_roles:
238241
extra_user_roles = tuple(extra_user_roles.lower().split(","))
239-
admin_role = "admin" in extra_user_roles
242+
admin_role = PERMISSIONS_GROUP_ADMIN in extra_user_roles
240243
valid_privileges, valid_roles = self.list_valid_privileges_and_roles()
241244
roles = [
242-
role for role in extra_user_roles if role in valid_roles and role != "admin"
245+
role
246+
for role in extra_user_roles
247+
if role in valid_roles and role != PERMISSIONS_GROUP_ADMIN
243248
]
244249
privileges = {
245250
extra_user_role
246251
for extra_user_role in extra_user_roles
247-
if extra_user_role not in roles and extra_user_role != "admin"
252+
if extra_user_role not in roles and extra_user_role != PERMISSIONS_GROUP_ADMIN
248253
}
249254
invalid_privileges = [
250255
privilege for privilege in privileges if privilege not in valid_privileges
@@ -566,7 +571,7 @@ def set_up_database(self) -> None:
566571
)
567572
)
568573
self.create_user(
569-
"admin",
574+
PERMISSIONS_GROUP_ADMIN,
570575
extra_user_roles="pg_read_all_data,pg_write_all_data",
571576
)
572577
cursor.execute("GRANT CONNECT ON DATABASE postgres TO admin;")

src/charm.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
from constants import (
8787
APP_SCOPE,
8888
BACKUP_USER,
89+
DATABASE_DEFAULT_NAME,
8990
METRICS_PORT,
9091
MONITORING_PASSWORD_KEY,
9192
MONITORING_USER,
@@ -417,7 +418,7 @@ def postgresql(self) -> PostgreSQL:
417418
current_host=self.endpoint,
418419
user=USER,
419420
password=self.get_secret(APP_SCOPE, f"{USER}-password"),
420-
database="postgres",
421+
database=DATABASE_DEFAULT_NAME,
421422
system_users=SYSTEM_USERS,
422423
)
423424

src/constants.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
"""File containing constants to be used in the charm."""
55

6+
DATABASE_DEFAULT_NAME = "postgres"
67
DATABASE_PORT = "5432"
78
PEER = "database-peers"
89
BACKUP_USER = "backup"

tests/integration/helpers.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
wait_fixed,
3333
)
3434

35+
from constants import DATABASE_DEFAULT_NAME
36+
3537
CHARM_BASE = "[email protected]"
3638
CHARM_SERIES = "jammy"
3739
METADATA = yaml.safe_load(Path("./metadata.yaml").read_text())
@@ -325,7 +327,7 @@ async def execute_query_on_unit(
325327
unit_address: str,
326328
password: str,
327329
query: str,
328-
database: str = "postgres",
330+
database: str = DATABASE_DEFAULT_NAME,
329331
sslmode: str | None = None,
330332
):
331333
"""Execute given PostgreSQL query on a unit.

tests/integration/new_relations/test_new_relations_1.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
from pytest_operator.plugin import OpsTest
1313
from tenacity import Retrying, stop_after_attempt, wait_fixed
1414

15+
from constants import DATABASE_DEFAULT_NAME
16+
1517
from ..helpers import (
1618
CHARM_BASE,
1719
check_database_users_existence,
@@ -218,7 +220,10 @@ async def test_two_applications_doesnt_share_the_same_relation_data(ops_test: Op
218220
(another_application_app_name, f"{APPLICATION_APP_NAME.replace('-', '_')}_database"),
219221
]:
220222
connection_string = await build_connection_string(
221-
ops_test, application, FIRST_DATABASE_RELATION_NAME, database="postgres"
223+
ops_test,
224+
application,
225+
FIRST_DATABASE_RELATION_NAME,
226+
database=DATABASE_DEFAULT_NAME,
222227
)
223228
with pytest.raises(psycopg2.Error):
224229
psycopg2.connect(connection_string)
@@ -448,7 +453,7 @@ async def test_admin_role(ops_test: OpsTest):
448453

449454
# Check that the user can access all the databases.
450455
for database in [
451-
"postgres",
456+
DATABASE_DEFAULT_NAME,
452457
f"{APPLICATION_APP_NAME.replace('-', '_')}_database",
453458
"another_application_database",
454459
]:
@@ -472,11 +477,11 @@ async def test_admin_role(ops_test: OpsTest):
472477
)
473478
assert version == data
474479

475-
# Write some data (it should fail in the "postgres" database).
480+
# Write some data (it should fail in the default database name).
476481
random_name = (
477482
f"test_{''.join(secrets.choice(string.ascii_lowercase) for _ in range(10))}"
478483
)
479-
should_fail = database == "postgres"
484+
should_fail = database == DATABASE_DEFAULT_NAME
480485
cursor.execute(f"CREATE TABLE {random_name}(data TEXT);")
481486
if should_fail:
482487
assert False, (
@@ -494,7 +499,7 @@ async def test_admin_role(ops_test: OpsTest):
494499

495500
# Test the creation and deletion of databases.
496501
connection_string = await build_connection_string(
497-
ops_test, DATA_INTEGRATOR_APP_NAME, "postgresql", database="postgres"
502+
ops_test, DATA_INTEGRATOR_APP_NAME, "postgresql", database=DATABASE_DEFAULT_NAME
498503
)
499504
connection = psycopg2.connect(connection_string)
500505
connection.autocommit = True
@@ -503,8 +508,10 @@ async def test_admin_role(ops_test: OpsTest):
503508
cursor.execute(f"CREATE DATABASE {random_name};")
504509
cursor.execute(f"DROP DATABASE {random_name};")
505510
try:
506-
cursor.execute("DROP DATABASE postgres;")
507-
assert False, "the admin extra user role was able to drop the `postgres` system database"
511+
cursor.execute(f"DROP DATABASE {DATABASE_DEFAULT_NAME};")
512+
assert False, (
513+
f"the admin extra user role was able to drop the `{DATABASE_DEFAULT_NAME}` system database"
514+
)
508515
except psycopg2.errors.InsufficientPrivilege:
509516
# Ignore the error, as the admin extra user role mustn't be able to drop
510517
# the "postgres" system database.

tests/integration/new_relations/test_relations_coherence.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import pytest
1010
from pytest_operator.plugin import OpsTest
1111

12+
from constants import DATABASE_DEFAULT_NAME
13+
1214
from ..helpers import CHARM_BASE, DATABASE_APP_NAME, build_and_deploy
1315
from .helpers import build_connection_string
1416
from .test_new_relations_1 import DATA_INTEGRATOR_APP_NAME
@@ -120,14 +122,14 @@ async def test_relations(ops_test: OpsTest, charm):
120122

121123
for database in [
122124
DATA_INTEGRATOR_APP_NAME.replace("-", "_"),
123-
"postgres",
125+
DATABASE_DEFAULT_NAME,
124126
]:
125127
logger.info(f"connecting to the following database: {database}")
126128
connection_string = await build_connection_string(
127129
ops_test, DATA_INTEGRATOR_APP_NAME, "postgresql", database=database
128130
)
129131
connection = None
130-
should_fail = database == "postgres"
132+
should_fail = database == DATABASE_DEFAULT_NAME
131133
try:
132134
with psycopg2.connect(
133135
connection_string
@@ -136,7 +138,7 @@ async def test_relations(ops_test: OpsTest, charm):
136138
data = cursor.fetchone()
137139
assert data[0] == "some data"
138140

139-
# Write some data (it should fail in the "postgres" database).
141+
# Write some data (it should fail in the default database name).
140142
random_name = f"test_{''.join(secrets.choice(string.ascii_lowercase) for _ in range(10))}"
141143
cursor.execute(f"CREATE TABLE {random_name}(data TEXT);")
142144
if should_fail:

tests/unit/test_postgresql.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,22 @@
55
import psycopg2
66
import pytest
77
from charms.postgresql_k8s.v0.postgresql import (
8+
PERMISSIONS_GROUP_ADMIN,
89
PostgreSQLCreateDatabaseError,
910
PostgreSQLGetLastArchivedWALError,
1011
)
1112
from ops.testing import Harness
1213
from psycopg2.sql import SQL, Composed, Identifier, Literal
1314

1415
from charm import PostgresqlOperatorCharm
15-
from constants import PEER
16+
from constants import (
17+
BACKUP_USER,
18+
MONITORING_USER,
19+
PEER,
20+
REPLICATION_USER,
21+
REWIND_USER,
22+
USER,
23+
)
1624

1725

1826
@pytest.fixture(autouse=True)
@@ -75,7 +83,7 @@ def test_create_database(harness):
7583
SQL("GRANT ALL PRIVILEGES ON DATABASE "),
7684
Identifier(database),
7785
SQL(" TO "),
78-
Identifier("admin"),
86+
Identifier(PERMISSIONS_GROUP_ADMIN),
7987
SQL(";"),
8088
])
8189
),
@@ -84,7 +92,7 @@ def test_create_database(harness):
8492
SQL("GRANT ALL PRIVILEGES ON DATABASE "),
8593
Identifier(database),
8694
SQL(" TO "),
87-
Identifier("backup"),
95+
Identifier(BACKUP_USER),
8896
SQL(";"),
8997
])
9098
),
@@ -93,7 +101,7 @@ def test_create_database(harness):
93101
SQL("GRANT ALL PRIVILEGES ON DATABASE "),
94102
Identifier(database),
95103
SQL(" TO "),
96-
Identifier("replication"),
104+
Identifier(REPLICATION_USER),
97105
SQL(";"),
98106
])
99107
),
@@ -102,7 +110,7 @@ def test_create_database(harness):
102110
SQL("GRANT ALL PRIVILEGES ON DATABASE "),
103111
Identifier(database),
104112
SQL(" TO "),
105-
Identifier("rewind"),
113+
Identifier(REWIND_USER),
106114
SQL(";"),
107115
])
108116
),
@@ -111,7 +119,7 @@ def test_create_database(harness):
111119
SQL("GRANT ALL PRIVILEGES ON DATABASE "),
112120
Identifier(database),
113121
SQL(" TO "),
114-
Identifier("operator"),
122+
Identifier(USER),
115123
SQL(";"),
116124
])
117125
),
@@ -120,7 +128,7 @@ def test_create_database(harness):
120128
SQL("GRANT ALL PRIVILEGES ON DATABASE "),
121129
Identifier(database),
122130
SQL(" TO "),
123-
Identifier("monitoring"),
131+
Identifier(MONITORING_USER),
124132
SQL(";"),
125133
])
126134
),

0 commit comments

Comments
 (0)