Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Casefold when processing email addresses #374

Merged
merged 32 commits into from Aug 24, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
087bd4a
add casefolding to bind and associated functions
H-Shay Jul 7, 2021
0988bdd
add casefolding to necessary functions + lints
H-Shay Jul 7, 2021
d80191a
add changelog
H-Shay Jul 7, 2021
3227de7
fix broken terms test
H-Shay Jul 27, 2021
5950186
draft migration script
H-Shay Jul 27, 2021
80a33f3
draft test for migration script
H-Shay Jul 27, 2021
406c9ac
add send email and email test
H-Shay Jul 28, 2021
d20c2bc
function for updating global table added
H-Shay Jul 29, 2021
4449f00
lints
H-Shay Jul 29, 2021
9b363c5
requested changes
H-Shay Aug 2, 2021
a99a18e
lints
H-Shay Aug 2, 2021
568b603
fix lint fail
H-Shay Aug 2, 2021
775f0ec
update tests + misc requested changes
H-Shay Aug 4, 2021
7ae6d36
extract casefold logic to function and add to affected files
H-Shay Aug 5, 2021
5d3ecc8
update email template and associated test
H-Shay Aug 5, 2021
76ad036
lints
H-Shay Aug 5, 2021
e23232a
requested changes
H-Shay Aug 10, 2021
3871005
rename file, rework to be script, rework tests to test script
H-Shay Aug 12, 2021
1f8ebfe
update tests and dry run/no email versions
H-Shay Aug 12, 2021
69f654d
update tests + scripts
H-Shay Aug 12, 2021
4b83b25
lints
H-Shay Aug 13, 2021
ac08265
add ability to call script from command line and update tests
H-Shay Aug 16, 2021
91d98d3
remove deleted files
H-Shay Aug 16, 2021
ec585a3
refine commandline invocation, add print statement
H-Shay Aug 16, 2021
ef40611
lints
H-Shay Aug 16, 2021
e774fa1
requested changes
H-Shay Aug 18, 2021
83560a4
requested changes + lints
H-Shay Aug 19, 2021
eb5ad93
requested changes
H-Shay Aug 23, 2021
f1b4f9e
lints
H-Shay Aug 23, 2021
969dda4
Actually let me just do that myself - doesn't have to wait till Shay …
babolivier Aug 24, 2021
b6b95c6
Merge branch 'matrix-org:main' into casefold
H-Shay Aug 24, 2021
96eee48
lints
H-Shay Aug 24, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions res/matrix-org/migration_template.eml
Expand Up @@ -11,10 +11,13 @@ Content-Type: multipart/alternative;
Content-Type: text/plain; charset=UTF-8
Content-Disposition: inline

Hi,
Hello,

This is a notification to let you know that matrix id %(mxid)s was associated with
a depreciated version of your email address and has been deleted.
In the past, identity services did not take case into account when creating and storing
mxids. This led to your email address, %(to)s being stored with two mxids. A recent update
changed this behavior and streamlined the mxids associated with your email address.
This is a notification to let you know that matrix id %(mxid)s has been deleted in accordance
with this update.
H-Shay marked this conversation as resolved.
Show resolved Hide resolved


About Matrix:
Expand Down
109 changes: 62 additions & 47 deletions sydent/db/migration.py
Expand Up @@ -5,38 +5,45 @@

from sydent.util import json_decoder
from sydent.util.emailutils import sendEmail
from sydent.util.hash import sha256_and_url_safe_base64


def update_assosc(self, conn: sqlite3.Connection):
# from table local_threepid_associations, select all associations where the medium is 'email'
def update_local_associations(self, conn: sqlite3.Connection):
"""Update the DB table local_threepid_associations so that all stored
emails are casefolded, and any duplicate mxid's associated with the
given email are deleted.

:return: None
"""
cur = conn.cursor()

res = cur.execute(
"SELECT address, mxid FROM local_threepid_associations WHERE medium = 'email'"
"ORDER BY ts DESC"
)

# a dict that associates an email address with correspoinding mxids and lookup hashes
associations: Dict[str, List[Tuple[str, str, str]]] = {}
H-Shay marked this conversation as resolved.
Show resolved Hide resolved

# iterate through selected associations, casefold email, rehash it, and add to
# associations dict
for row in res.fetchall():
casefold_address = row[0].casefold()
for address, mxid in res.fetchall():
casefold_address = address.casefold()

# rehash the email since hash functions are case-sensitive
pepper_result = cur.execute("SELECT lookup_pepper from hashing_metadata")
pepper = pepper_result.fetchone()[0]
combo = "%s %s %s" % (casefold_address, "email", pepper)
lookup_hash = sha256_and_url_safe_base64(combo)
# rehash email since hashes are case-sensitive
lookup_hash = self.calculate_lookup(casefold_address)

if casefold_address in associations:
associations[casefold_address].append((row[0], row[1], lookup_hash))
associations[casefold_address].append((address, mxid, lookup_hash))
else:
associations[casefold_address] = [(row[0], row[1], lookup_hash)]
associations[casefold_address] = [(address, mxid, lookup_hash)]

# list of arguments to update db with
db_update_args: List[Tuple[str, str, str, str]] = []
to_delete: List[str] = []

# list of mxids to delete
to_delete: List[Tuple[str]] = []

# list of mxids to send emails to letting them know the mxid has been deleted
mxids: List[str] = []

for casefold_address, assoc_tuples in associations.items():
Expand All @@ -52,26 +59,23 @@ def update_assosc(self, conn: sqlite3.Connection):
if len(assoc_tuples) > 1:
H-Shay marked this conversation as resolved.
Show resolved Hide resolved
# Iterate over all associations except for the first one, since we've already
# processed it.
for assoc_tuple in assoc_tuples[1:]:
to_delete.append([assoc_tuple[0]])
mxids.append(assoc_tuple[1])
for address, mxid, _ in assoc_tuples[1:]:
to_delete.append((address,))
mxids.append((mxid, address))

# iterate through the mxids and send email
for mxid in mxids:
for mxid, address in mxids:
templateFile = self.sydent.get_branded_template(
"matrix-org",
"migration_template.eml",
("email", "email.template"),
)
res = cur.execute(
"SELECT address FROM local_threepid_associations WHERE mxid = ?", (mxid,)
)
address = res.fetchone()[0]

sendEmail(
self.sydent,
templateFile,
address,
{"mxid": "mxid", "subject_header_value": "MatrixID Deletion"},
{"mxid": "mxid", "subject_header_value": "MatrixID Update"},
)

if len(to_delete) > 0:
Expand All @@ -90,46 +94,61 @@ def update_assosc(self, conn: sqlite3.Connection):


def update_global_assoc(self, conn: sqlite3.Connection):
H-Shay marked this conversation as resolved.
Show resolved Hide resolved
"""Update the DB table global_threepid_associations so that all stored
emails are casefolded, the signed association is re-signed and any duplicate
mxid's associated with the given email are deleted.

:return: None
"""

# get every row where the local server is origin server and medium is email
originServer = self.sydent.server_name
origin_server = self.sydent.server_name
medium = "email"

cur = self.sydent.db.cursor()
res = cur.execute(
"SELECT address, mxid, sgAssoc FROM global_threepid_associations WHERE medium = ?"
"AND originServer = ? ORDER BY ts DESC",
(medium, originServer),
(medium, origin_server),
)

associations: Dict[str, List[Tuple[str, str, str]]] = {}
# dict that stores email address with mxid, email address, lookup hash, and
# signed association
associations: Dict[str, List[Tuple[str, str, str, str]]] = {}

# iterate through selected associations, casefold email, rehash it, and add to
# associations dict
for row in res.fetchall():
casefold_address = row[0].casefold()
# iterate through selected associations, casefold email, rehash it, re-sign the
# associations and add to associations dict
for address, mxid, sg_assoc in res.fetchall():
casefold_address = address.casefold()

# rehash the email since hash functions are case-sensitive
lookup_hash = self.calculate_lookup(casefold_address)
H-Shay marked this conversation as resolved.
Show resolved Hide resolved

# update associations with new casefolded address and re-sign
sgassoc = json_decoder.decode(row[2])
sgassoc["address"] = row[0].casefold()
sgAssoc = json.dumps(
# update signed associations with new casefolded address and re-sign
sg_assoc = json_decoder.decode(sg_assoc)
sg_assoc["address"] = address.casefold()
sg_assoc = json.dumps(
signedjson.sign.sign_json(
sgassoc, self.sydent.server_name, self.sydent.keyring.ed25519
sg_assoc, self.sydent.server_name, self.sydent.keyring.ed25519
)
)

if casefold_address in associations:
associations[casefold_address].append(
(row[0], row[1], lookup_hash, sgAssoc)
(address, mxid, lookup_hash, sg_assoc)
)
else:
associations[casefold_address] = [(row[0], row[1], lookup_hash, sgAssoc)]
associations[casefold_address] = [(address, mxid, lookup_hash, sg_assoc)]

# list of arguments to update db with
db_update_args: List[Tuple[str, str, str, str]] = []
to_delete: List[str] = []
mxids: List[str] = []

# list of mxids to delete
to_delete: List[Tuple[str]] = []

# list of mxids and addresses to send emails to letting them know the mxid
# has been deleted
mxids: List[Tuple[str]] = []

for casefold_address, assoc_tuples in associations.items():
db_update_args.append(
Expand All @@ -145,27 +164,23 @@ def update_global_assoc(self, conn: sqlite3.Connection):
if len(assoc_tuples) > 1:
# Iterate over all associations except for the first one, since we've already
# processed it.
for assoc_tuple in assoc_tuples[1:]:
to_delete.append([assoc_tuple[0]])
mxids.append(assoc_tuple[1])
for address, mxid, _, _ in assoc_tuples[1:]:
to_delete.append((address,))
mxids.append((mxid, address))

# iterate through the mxids and send email
for mxid in mxids:
for mxid, address in mxids:
templateFile = self.sydent.get_branded_template(
"matrix-org",
"migration_template.eml",
("email", "email.template"),
)
res = cur.execute(
"SELECT address FROM local_threepid_associations WHERE mxid = ?", (mxid,)
)
address = res.fetchone()[0]

sendEmail(
self.sydent,
templateFile,
address,
{"mxid": "mxid", "subject_header_value": "MatrixID Deletion"},
{"mxid": "mxid", "subject_header_value": "MatrixID Update"},
)

if len(to_delete) > 0:
Expand Down
7 changes: 5 additions & 2 deletions tests/test_migration.py
Expand Up @@ -4,7 +4,7 @@

from twisted.trial import unittest

from sydent.db.migration import update_assosc, update_global_assoc
from sydent.db.migration import update_global_assoc, update_local_associations
from sydent.util import json_decoder
from sydent.util.emailutils import sendEmail
from sydent.util.hash import sha256_and_url_safe_base64
Expand Down Expand Up @@ -197,9 +197,12 @@ def test_migration_email(self):
email_contents = smtp.sendmail.call_args[0][2].decode("utf-8")
self.assertIn("This is a notification", email_contents)

# test email was sent
smtp.sendmail.assert_called()

def test_local_db_migration(self):
H-Shay marked this conversation as resolved.
Show resolved Hide resolved
with patch("sydent.util.emailutils.smtplib"):
update_assosc(self, self.sydent.db)
update_local_associations(self, self.sydent.db)

cur = self.sydent.db.cursor()
res = cur.execute("SELECT * FROM local_threepid_associations")
Expand Down