Skip to content

Commit 36254a9

Browse files
authored
DPE-4643 ensure username uniqueness (#439)
* ensure username uniqueness * using temporary branch on router * using revision since test cannot deploy temp branch * support legacy usernames * undo unnecessary renaming * model uuid as suffix * trunc on 26chars * leftover
1 parent 7b438e9 commit 36254a9

File tree

4 files changed

+36
-10
lines changed

4 files changed

+36
-10
lines changed

lib/charms/mysql/v0/mysql.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1215,29 +1215,28 @@ def delete_users_for_unit(self, unit_name: str) -> None:
12151215
logger.exception(f"Failed to query and delete users for unit {unit_name}")
12161216
raise MySQLDeleteUsersForUnitError(e.message)
12171217

1218-
def delete_users_for_relation(self, relation_id: int) -> None:
1218+
def delete_users_for_relation(self, username: str) -> None:
12191219
"""Delete users for a relation.
12201220
12211221
Args:
1222-
relation_id: The id of the relation for which to delete mysql users for
1222+
username: The username do drop
12231223
12241224
Raises:
12251225
MySQLDeleteUsersForRelationError if there is an error deleting users for the relation
12261226
"""
1227-
user = f"relation-{str(relation_id)}"
12281227
drop_users_command = [
12291228
f"shell.connect_to_primary('{self.server_config_user}:{self.server_config_password}@{self.instance_address}')",
1230-
f"session.run_sql(\"DROP USER IF EXISTS '{user}'@'%';\")",
1229+
f"session.run_sql(\"DROP USER IF EXISTS '{username}'@'%';\")",
12311230
]
12321231
# If the relation is with a MySQL Router charm application, delete any users
12331232
# created by that application.
12341233
drop_users_command.extend(
1235-
self._get_statements_to_delete_users_with_attribute("created_by_user", f"'{user}'")
1234+
self._get_statements_to_delete_users_with_attribute("created_by_user", f"'{username}'")
12361235
)
12371236
try:
12381237
self._run_mysqlsh_script("\n".join(drop_users_command))
12391238
except MySQLClientError as e:
1240-
logger.exception(f"Failed to delete users for relation {relation_id}")
1239+
logger.exception(f"Failed to delete {username=}")
12411240
raise MySQLDeleteUsersForRelationError(e.message)
12421241

12431242
def delete_user(self, username: str) -> None:

src/relations/mysql_provider.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,20 @@ def _get_or_set_password(self, relation) -> str:
7373
self.database.update_relation_data(relation.id, {"password": password})
7474
return password
7575

76+
def _get_username(self, relation_id: int, legacy: bool = False) -> str:
77+
"""Generate a unique username for the relation using the model uuid and the relation id.
78+
79+
Args:
80+
relation_id (int): The relation id.
81+
legacy (bool): If True, generate a username without the model uuid.
82+
83+
Returns:
84+
str: A valid unique username (limited to 26 characters)
85+
"""
86+
if legacy:
87+
return f"relation-{relation_id}"
88+
return f"relation-{relation_id}_{self.model.uuid.replace('-', '')}"[:26]
89+
7690
# =============
7791
# Handlers
7892
# =============
@@ -94,7 +108,7 @@ def _on_database_requested(self, event: DatabaseRequestedEvent) -> None:
94108
if event.extra_user_roles:
95109
extra_user_roles = event.extra_user_roles.split(",")
96110
# user name is derived from the relation id
97-
db_user = f"relation-{relation_id}"
111+
db_user = self._get_username(relation_id)
98112
db_pass = self._get_or_set_password(event.relation)
99113

100114
remote_app = event.app.name
@@ -246,7 +260,17 @@ def _on_database_broken(self, event: RelationBrokenEvent) -> None:
246260

247261
relation_id = event.relation.id
248262
try:
249-
self.charm._mysql.delete_users_for_relation(relation_id)
263+
if self.charm._mysql.does_mysql_user_exist(self._get_username(relation_id), "%"):
264+
self.charm._mysql.delete_users_for_relation(self._get_username(relation_id))
265+
elif self.charm._mysql.does_mysql_user_exist(
266+
self._get_username(relation_id, legacy=True), "%"
267+
):
268+
self.charm._mysql.delete_users_for_relation(
269+
self._get_username(relation_id, legacy=True)
270+
)
271+
else:
272+
logger.warning(f"User(s) not found for relation {relation_id}")
273+
return
250274
logger.info(f"Removed user(s) for relation {relation_id}")
251275
except MySQLDeleteUsersForRelationError:
252276
logger.error(f"Failed to delete user(s) for relation {relation_id}")

tests/integration/high_availability/test_async_replication.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ async def test_deploy_router_and_app(first_model: Model) -> None:
194194
MYSQL_ROUTER_APP_NAME,
195195
application_name=MYSQL_ROUTER_APP_NAME,
196196
series="jammy",
197-
channel="8.0/stable",
197+
channel="8.0/edge",
198198
num_units=1,
199199
trust=True,
200200
)

tests/unit/test_database.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,15 @@ def test_database_requested(
9494
self.database_relation_id, "app", {"database": "test_db"}
9595
)
9696

97+
username = (
98+
f"relation-{self.database_relation_id}_{self.harness.model.uuid.replace('-', '')}"
99+
)[:26]
97100
self.assertEqual(
98101
database_relation_databag,
99102
{
100103
"data": '{"database": "test_db"}',
101104
"password": "super_secure_password",
102-
"username": f"relation-{self.database_relation_id}",
105+
"username": username,
103106
"endpoints": "mysql-k8s-primary:3306",
104107
"version": "8.0.29-0ubuntu0.20.04.3",
105108
"read-only-endpoints": "mysql-k8s-replicas:3306",

0 commit comments

Comments
 (0)