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

Review email configuration #2241

Merged
merged 29 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
ec1671c
add use_login to mail settings
ychiucco Feb 3, 2025
ca98d2e
new settings variables
ychiucco Feb 3, 2025
dc51fa4
Merge branch 'main' into 2224-review-email-configuration
tcompa Feb 3, 2025
249ff4a
Revert "new settings variables"
ychiucco Feb 3, 2025
ac90e02
fix secrets and keys
ychiucco Feb 3, 2025
5fb7b99
Merge branch 'main' into 2224-review-email-configuration
ychiucco Feb 3, 2025
570e811
Merge remote-tracking branch 'refs/remotes/origin/2224-review-email-c…
ychiucco Feb 3, 2025
bfceb8c
not encrypted env variables
ychiucco Feb 3, 2025
04f2d81
Merge branch 'main' into 2224-review-email-configuration
tcompa Feb 4, 2025
204c1e8
fix tests
ychiucco Feb 4, 2025
58662cf
Merge remote-tracking branch 'refs/remotes/origin/2224-review-email-c…
ychiucco Feb 4, 2025
7014467
obfuscate keys
ychiucco Feb 4, 2025
d3ce2fc
changes from comments
ychiucco Feb 4, 2025
e87aba0
test unit config
ychiucco Feb 4, 2025
0cb23c3
fix test config
ychiucco Feb 4, 2025
a0741c3
solve bug with override_settings_factory
ychiucco Feb 4, 2025
eb57e63
use use_login
ychiucco Feb 4, 2025
f18111b
fix bug
ychiucco Feb 4, 2025
c644bdf
improve security
ychiucco Feb 4, 2025
f166355
fix tests
ychiucco Feb 4, 2025
fc36b13
Merge branch 'main' into 2224-review-email-configuration
tcompa Feb 4, 2025
69602e6
Rename variable in test
tcompa Feb 4, 2025
11ed043
Combine two try/except together
tcompa Feb 4, 2025
3013d86
Rename `FRACTAL_EMAIL_SETTINGS->mail_settings`
tcompa Feb 4, 2025
9fdcc78
minor
tcompa Feb 4, 2025
87097e2
Improve error message
tcompa Feb 4, 2025
e19e5f4
Complete renaming
tcompa Feb 4, 2025
ee1aa67
Fix docstrings
tcompa Feb 4, 2025
931153d
CHANGELOG
tcompa Feb 4, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions .github/workflows/oauth.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -56,20 +56,29 @@ jobs:
FRACTAL_RUNNER_BACKEND: local
JWT_SECRET_KEY: jwt_secret_key
JWT_EXPIRE_SECONDS: 1000
# Postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: fractal_test
POSTGRES_HOST: localhost
POSTGRES_PORT: 5432
# FRACTAL_EMAIL_SETTINGS and KEY are generated with the following command
# `printf "fakepassword\n" | poetry run fractalctl email-settings sender@example.org localhost 1025 test --skip-starttls`
FRACTAL_EMAIL_SETTINGS: gAAAAABnYvLgoSeECnrXlv1UoP4D_c9Of0xmwMJVopBA3TIDjOvx6YDVfe2ULz8yGr8Ba5Id8rRLjCXa_Ys8iHjvuniJyvsX0mDrc3IGSoofMEeeSCvYEe4iSWLeb_qTNVNPc4IT2-SLB-F7dEvkwzyAFnEm9dVmApd4_lQLm9_wJoS-tz1Q1K8E1_jJSgpfGgwHaINHICVh1UL_qHjIa3DwFvDPvt32tLLBZTL7oN88A8RCmg00ThIZs4HN7OQkvfninfOiM060Lb-AeNViCVgBX-bIPWZaeQ==
FRACTAL_EMAIL_SETTINGS_KEY: 4otDt3R-8p4S97QT0gcUzynCalByypTv01YntqQ9XFk=
FRACTAL_EMAIL_RECIPIENTS: recipient1@example.org,recipient2@example.org
# Dex (OAuth)
OAUTH_DEXIDP_CLIENT_ID: client_test_id
OAUTH_DEXIDP_CLIENT_SECRET: client_test_secret
OAUTH_DEXIDP_REDIRECT_URL: http://localhost:8001/auth/dexidp/callback/
OAUTH_DEXIDP_OIDC_CONFIGURATION_ENDPOINT: http://127.0.0.1:5556/dex/.well-known/openid-configuration
# Email
FRACTAL_EMAIL_SENDER: sender@example.org
FRACTAL_EMAIL_SMTP_SERVER: localhost
FRACTAL_EMAIL_SMTP_PORT: 1025
FRACTAL_EMAIL_INSTANCE_NAME: test
FRACTAL_EMAIL_RECIPIENTS: recipient1@example.org,recipient2@example.org
FRACTAL_EMAIL_USE_STARTTLS: false
ychiucco marked this conversation as resolved.
Show resolved Hide resolved
FRACTAL_EMAIL_USE_LOGIN: true
# FRACTAL_EMAIL_PASSWORD and FRACTAL_EMAIL_PASSWORD_KET are generated with the following command
# `printf "fakepassword\n" | poetry run fractalctl encrypt-email-password`
FRACTAL_EMAIL_PASSWORD: gAAAAABnoQUGHMsDgLkpDtwUtrKtf9T1so44ahEXExGRceAnf097mVY1EbNuMP5fjvkndvwCwBJM7lHoSgKQkZ4VbvO9t3PJZg==
FRACTAL_EMAIL_PASSWORD_KEY: lp3j2FVDkzLd0Rklnzg1pHuV9ClCuDE0aGeJfTNCaW4=
run: |
fractalctl set-db
fractalctl start --port 8001 &
Expand Down
71 changes: 11 additions & 60 deletions fractal_server/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,45 +63,18 @@
description="Apply data-migration script to an existing database.",
)

# fractalctl email-settings
email_settings_parser = subparsers.add_parser(
"email-settings",
# fractalctl encrypt-email-password
encrypt_email_password_parser = subparsers.add_parser(
"encrypt-email-password",
description=(
"Generate valid values for environment variables "
"`FRACTAL_EMAIL_SETTINGS` and `FRACTAL_EMAIL_SETTINGS_KEY`."
"FRACTAL_EMAIL_PASSWORD and FRACTAL_EMAIL_PASSWORD_KEY."
),
)
email_settings_parser.add_argument(
"sender",
type=str,
help="Email of the sender",
)
email_settings_parser.add_argument(
"server",
type=str,
help="SMPT server used to send emails",
)
email_settings_parser.add_argument(
"port",
type=int,
help="Port of the SMPT server",
)
email_settings_parser.add_argument(
"instance",
type=str,
help="Name of the Fractal instance sending emails",
)
email_settings_parser.add_argument(
"--skip-starttls",
action="store_true",
default=False,
help="If set, skip the execution of `starttls` when sending emails",
)


def save_openapi(dest="openapi.json"):
from fractal_server.main import start_application
import json

app = start_application()
openapi_schema = app.openapi()
Expand Down Expand Up @@ -227,31 +200,15 @@ def _slugify_version(raw_version: str) -> str:
current_update_db_data_module.fix_db()


def print_mail_settings(
sender: str,
server: str,
port: int,
instance: str,
skip_starttls: bool,
):
def print_encrypted_password():
from cryptography.fernet import Fernet

password = input(f"Insert email password for sender '{sender}': ")
password = input("Insert email password: ").encode("utf-8")
key = Fernet.generate_key().decode("utf-8")
fractal_mail_settings = json.dumps(
dict(
sender=sender,
password=password,
smtp_server=server,
port=port,
instance_name=instance,
use_starttls=(not skip_starttls),
)
).encode("utf-8")
email_settings = Fernet(key).encrypt(fractal_mail_settings).decode("utf-8")
encrypted_password = Fernet(key).encrypt(password).decode("utf-8")

print(f"\nFRACTAL_EMAIL_SETTINGS: {email_settings}")
print(f"FRACTAL_EMAIL_SETTINGS_KEY: {key}")
print(f"\nFRACTAL_EMAIL_PASSWORD={encrypted_password}")
print(f"FRACTAL_EMAIL_PASSWORD_KEY={key}")


def run():
Expand All @@ -270,14 +227,8 @@ def run():
port=args.port,
reload=args.reload,
)
elif args.cmd == "email-settings":
print_mail_settings(
sender=args.sender,
server=args.server,
port=args.port,
instance=args.instance,
skip_starttls=args.skip_starttls,
)
elif args.cmd == "encrypt-email-password":
print_encrypted_password()
else:
sys.exit(f"Error: invalid command '{args.cmd}'.")

Expand Down
9 changes: 6 additions & 3 deletions fractal_server/app/security/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,18 @@ async def on_after_register(
# Send mail section
settings = Inject(get_settings)

if this_user.oauth_accounts and settings.MAIL_SETTINGS is not None:
if (
this_user.oauth_accounts
and settings.FRACTAL_EMAIL_SETTINGS is not None
):
try:
logger.info(
"START sending email about new signup to "
f"{settings.MAIL_SETTINGS.recipients}."
f"{settings.FRACTAL_EMAIL_SETTINGS.recipients}."
)
mail_new_oauth_signup(
msg=f"New user registered: '{this_user.email}'.",
mail_settings=settings.MAIL_SETTINGS,
mail_settings=settings.FRACTAL_EMAIL_SETTINGS,
)
logger.info("END sending email about new signup.")
except Exception as e:
Expand Down
13 changes: 9 additions & 4 deletions fractal_server/app/security/signup_email.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from email.message import EmailMessage
from email.utils import formataddr

from cryptography.fernet import Fernet

from fractal_server.config import MailSettings


Expand All @@ -28,10 +30,13 @@
if mail_settings.use_starttls:
server.starttls()
server.ehlo()

server.login(
user=mail_settings.sender, password=mail_settings.password
)
if mail_settings.use_login:
password = (
Fernet(mail_settings.encryption_key)
.decrypt(mail_settings.encrypted_password)
.decode("utf-8")
)
server.login(user=mail_settings.sender, password=password)

Check notice on line 39 in fractal_server/app/security/signup_email.py

View workflow job for this annotation

GitHub Actions / Coverage

Missing coverage

Missing coverage on lines 33-39
server.sendmail(
from_addr=mail_settings.sender,
to_addrs=mail_settings.recipients,
Expand Down
Loading
Loading