Skip to content

Commit

Permalink
DPE-4643 ensure username uniqueness (#439)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
paulomach authored Jul 5, 2024
1 parent 7b438e9 commit 36254a9
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 10 deletions.
11 changes: 5 additions & 6 deletions lib/charms/mysql/v0/mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -1215,29 +1215,28 @@ def delete_users_for_unit(self, unit_name: str) -> None:
logger.exception(f"Failed to query and delete users for unit {unit_name}")
raise MySQLDeleteUsersForUnitError(e.message)

def delete_users_for_relation(self, relation_id: int) -> None:
def delete_users_for_relation(self, username: str) -> None:
"""Delete users for a relation.
Args:
relation_id: The id of the relation for which to delete mysql users for
username: The username do drop
Raises:
MySQLDeleteUsersForRelationError if there is an error deleting users for the relation
"""
user = f"relation-{str(relation_id)}"
drop_users_command = [
f"shell.connect_to_primary('{self.server_config_user}:{self.server_config_password}@{self.instance_address}')",
f"session.run_sql(\"DROP USER IF EXISTS '{user}'@'%';\")",
f"session.run_sql(\"DROP USER IF EXISTS '{username}'@'%';\")",
]
# If the relation is with a MySQL Router charm application, delete any users
# created by that application.
drop_users_command.extend(
self._get_statements_to_delete_users_with_attribute("created_by_user", f"'{user}'")
self._get_statements_to_delete_users_with_attribute("created_by_user", f"'{username}'")
)
try:
self._run_mysqlsh_script("\n".join(drop_users_command))
except MySQLClientError as e:
logger.exception(f"Failed to delete users for relation {relation_id}")
logger.exception(f"Failed to delete {username=}")
raise MySQLDeleteUsersForRelationError(e.message)

def delete_user(self, username: str) -> None:
Expand Down
28 changes: 26 additions & 2 deletions src/relations/mysql_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ def _get_or_set_password(self, relation) -> str:
self.database.update_relation_data(relation.id, {"password": password})
return password

def _get_username(self, relation_id: int, legacy: bool = False) -> str:
"""Generate a unique username for the relation using the model uuid and the relation id.
Args:
relation_id (int): The relation id.
legacy (bool): If True, generate a username without the model uuid.
Returns:
str: A valid unique username (limited to 26 characters)
"""
if legacy:
return f"relation-{relation_id}"
return f"relation-{relation_id}_{self.model.uuid.replace('-', '')}"[:26]

# =============
# Handlers
# =============
Expand All @@ -94,7 +108,7 @@ def _on_database_requested(self, event: DatabaseRequestedEvent) -> None:
if event.extra_user_roles:
extra_user_roles = event.extra_user_roles.split(",")
# user name is derived from the relation id
db_user = f"relation-{relation_id}"
db_user = self._get_username(relation_id)
db_pass = self._get_or_set_password(event.relation)

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

relation_id = event.relation.id
try:
self.charm._mysql.delete_users_for_relation(relation_id)
if self.charm._mysql.does_mysql_user_exist(self._get_username(relation_id), "%"):
self.charm._mysql.delete_users_for_relation(self._get_username(relation_id))
elif self.charm._mysql.does_mysql_user_exist(
self._get_username(relation_id, legacy=True), "%"
):
self.charm._mysql.delete_users_for_relation(
self._get_username(relation_id, legacy=True)
)
else:
logger.warning(f"User(s) not found for relation {relation_id}")
return
logger.info(f"Removed user(s) for relation {relation_id}")
except MySQLDeleteUsersForRelationError:
logger.error(f"Failed to delete user(s) for relation {relation_id}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ async def test_deploy_router_and_app(first_model: Model) -> None:
MYSQL_ROUTER_APP_NAME,
application_name=MYSQL_ROUTER_APP_NAME,
series="jammy",
channel="8.0/stable",
channel="8.0/edge",
num_units=1,
trust=True,
)
Expand Down
5 changes: 4 additions & 1 deletion tests/unit/test_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,15 @@ def test_database_requested(
self.database_relation_id, "app", {"database": "test_db"}
)

username = (
f"relation-{self.database_relation_id}_{self.harness.model.uuid.replace('-', '')}"
)[:26]
self.assertEqual(
database_relation_databag,
{
"data": '{"database": "test_db"}',
"password": "super_secure_password",
"username": f"relation-{self.database_relation_id}",
"username": username,
"endpoints": "mysql-k8s-primary:3306",
"version": "8.0.29-0ubuntu0.20.04.3",
"read-only-endpoints": "mysql-k8s-replicas:3306",
Expand Down

0 comments on commit 36254a9

Please sign in to comment.