Skip to content

[Bugfix:System] Quote DB URL credentials - #13384

Open
SajalDevX wants to merge 21 commits into
Submitty:mainfrom
SajalDevX:fix/db-connect-string-escaping
Open

SajalDevX wants to merge 21 commits into
Submitty:mainfrom
SajalDevX:fix/db-connect-string-escaping

Conversation

@SajalDevX

@SajalDevX SajalDevX commented Sep 26, 2026 •

Copy link
Copy Markdown

Why is this Change Important & Necessary?

submitty_utils.db_utils.generate_connect_string() puts the database user and password into the postgresql:// URL as-is. The password is whatever the admin typed into CONFIGURE_SUBMITTY.py, so it can contain characters that mean something in a URL. With an @ in the password, SQLAlchemy splits the URL at the wrong place: the part after the @ becomes the host and the password is cut short. A %xx sequence in the password gets decoded as well, so the password sent to Postgres is not the configured one.

Every Python script that builds its connection through this helper then fails to connect: sbin/adduser.py, sbin/adduser_course.py, sbin/anonymize.py and bin/generate_repos.py. The PHP site is not affected because it builds a key=value PDO DSN rather than a URL.

There is no existing issue for this; I found it while reading db_utils.py.

What is the New Behavior?

The user and password are percent-encoded with urllib.parse.quote(..., safe='') before they go into the URL, as SQLAlchemy's docs suggest for passwords with special characters (quote rather than quote_plus, so a space also round-trips). SQLAlchemy decodes them again, so Postgres receives the original values. Passwords without special characters produce exactly the same string as before.

Before, with the database password set to se@cret%40x:

localhost FAILED: (psycopg2.OperationalError) could not translate host name "cret%40x@localhost" to address: Name or service not known
/var/run/postgresql FAILED: (psycopg2.OperationalError) connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  password authentication failed for user "submitty_dbuser"

After:

localhost connected as submitty_dbuser
/var/run/postgresql connected as submitty_dbuser

What steps should a reviewer take to reproduce or test the bug or new feature?

  1. Create a Postgres role with a password that contains @, e.g. CREATE ROLE submitty_dbuser LOGIN PASSWORD 'se@cret%40x';, and a database it owns.
  2. Build the URL with db_utils.generate_connect_string("localhost", 5432, "submitty", "submitty_dbuser", "se@cret%40x") and connect with sqlalchemy.create_engine(...).connect() (I used the pinned sqlalchemy==2.0.52 and psycopg2-binary==2.9.12).
  3. On main the connection fails as shown above; on this branch it connects, over TCP and over the Unix socket.

Automated Testing & Documentation

Added two unit tests to python_submitty_utils/tests/test_db_utils.py:

  • the exact encoded URL for a user and password containing @, :, / and %;
  • a round trip for both the TCP and the socket form: the password parsed back out of the URL equals the original one.

Both fail on main and pass here. The existing tests are unchanged and still pass, and python -m unittest discover in python_submitty_utils passes (25 tests). ruff check is clean. No documentation change is needed.

Other information

Not a breaking change and no migration needed. Some .setup/bin sample-data scripts and autograder/insert_database_version_data.py / sbin/cleanup_active_graders.py build their own URLs the same way; I left them out to keep this PR small and can move them onto this helper in a follow-up if that is wanted.

I used an AI assistant (Claude) while tracing this and writing the tests. I reviewed the change and ran the tests and the Postgres check above myself.

Update: The same percent-encoding (urllib.parse.quote(..., safe='')) is now also applied to every other place that built a PostgreSQL URL from the DB user and password by hand: migration/migrator/db.py (so install/update work with an @ in the password), bin/set_allowed_mins.py, bin/insert_build_data.py, autograder/autograder/insert_database_version_data.py, sbin/auto_rainbow_scheduler.py, sbin/cleanup_active_graders.py, sbin/database_queries.py, sbin/send_email.py, sbin/send_notification.py, sbin/grading_clustering/clustering_database_queries.py, and the dev setup scripts in .setup/bin/ (setup_sample_courses.py, setup_sample_emails.py, populate_office_hours_queue.py, reupload_old_assignments.py, recreate_submissions.py, sample_courses/models/course/course_create.py).

New migrator unit tests check that a user and password containing @, :, / and % are escaped and parse back to the original values through SQLAlchemy, for both a TCP host and a socket directory.

Test coverage is incomplete: the bin/, sbin/, autograder and .setup/bin/ scripts build the URL inline next to the connection code and have no existing unit tests, so they were only checked by hand and with ruff.

Left out on purpose: the shell scripts and the os.system(... PGPASSWORD='...' psql ...) calls in .setup/, since they pass the password through PGPASSWORD instead of a URL (their shell quoting is a separate issue).

Percent-encode user and password in connection string.
Added tests for connection string generation, including user and password escaping and round-trip verification.
@codecov

codecov Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 23.01%. Comparing base (be3c743) to head (ce3c5c2).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff            @@
##               main   #13384   +/-   ##
=========================================
  Coverage     23.01%   23.01%           
  Complexity    10244    10244           
=========================================
  Files           307      307           
  Lines         39643    39646    +3     
  Branches        672      672           
=========================================
+ Hits           9122     9125    +3     
  Misses        29952    29952           
  Partials        569      569           
Flag Coverage Δ
autograder 21.16% <ø> (ø)
js 0.30% <ø> (ø)
migrator 100.00% <ø> (ø)
php 21.10% <ø> (ø)
python_submitty_utils 80.07% <100.00%> (+0.24%) ⬆️
submitty_daemon_jobs 56.25% <ø> (ø)
vue 96.31% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@RichardJSun RichardJSun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The quoting is correct, and both test files pass for me.

This PR adds the same quote(..., safe='') code to 17 files. Can the scripts call db_utils.generate_connect_string instead? That function now does the escaping. adduser.py, anonymize.py and generate_repos.py already use it. Then the escaping is in one location. Five of the 15 scripts already import submitty_utils. The other scripts need the import. The migrator can keep its own copy if it must not depend on submitty_utils.

Posted with assistance from Claude Opus 5.5.

The scripts touched earlier in this PR each built their own
SQLAlchemy URL and each called quote() on the user and password.
db_utils.generate_connect_string already does that escaping, so the
scripts now call it instead and the escaping lives in one place, as
adduser.py, anonymize.py and generate_repos.py already do.

The port now comes from database_port in the config each script
already loads (falling back to 5432 like the migrator). For a socket
host the port is no longer passed, and for a TCP host the configured
port is now used where it used to be left out.

The migrator keeps its own quote() call because it is installed and
run before python_submitty_utils during setup.
@SajalDevX

Copy link
Copy Markdown
Author

Thanks @RichardJSun, done in 893c3e1.

All 15 scripts now build the URL with db_utils.generate_connect_string(...) (from submitty_utils import db_utils, same as adduser.py), and the quote imports are gone. The escaping is now only in db_utils.py, plus the migrator.

The migrator keeps its own quote(). install_migrator.sh runs it in INSTALL_SUBMITTY_HELPER.sh before python_submitty_utils is pip-installed, and nothing in migration/ imports submitty_utils today. The other scripts all run after that install. Several of them, or their packages, already import submitty_utils.dateutils.

Some of the scripts had no port before. They now read database_port from the database.json they already load, with the same 5432 fallback the migrator uses. Two small behaviour changes come from this, and neither matters with the default port 5432:

  • Scripts that used os.path.isdir(host) and a TCP host used to leave the port out of the URL, so they always connected on 5432. They now use the configured database_port.
  • The setup scripts that used the postgresql:///db?host=..&port=.. form (populate_office_hours_queue, recreate_submissions, course_create, setup_sample_courses) no longer pass the port when the host is a socket directory. That now matches adduser.py and the sbin scripts.

Also, reupload_old_assignments.py always used user:pass@host/db, so it could not connect through a socket host. It now can.

Tests: python_submitty_utils, migration and autograder unit tests pass locally, and ruff check . is clean.

@github-actions github-actions Bot added the Abandoned PR - Needs New Owner No activity on PR for more than 2 weeks -- seeking new owner to complete label Oct 18, 2026
@SajalDevX

Copy link
Copy Markdown
Author

I merged the latest main into the branch and fixed the conflicts from the ruff format change, so every script still builds its URL through db_utils.generate_connect_string and the files pass ruff check and ruff format. The db_utils and migrator tests pass locally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Abandoned PR - Needs New Owner No activity on PR for more than 2 weeks -- seeking new owner to complete

Projects

Status: Seeking Reviewer

Development

Successfully merging this pull request may close these issues.

2 participants