Skip to content

Fix/profile production readiness - #9

Merged
Devpaul-01 merged 38 commits into
mainfrom
fix/profile-production-readiness
Nov 27, 2026
Merged

Devpaul-01 merged 38 commits into
mainfrom
fix/profile-production-readiness

Conversation

@Devpaul-01

Copy link
Copy Markdown
Owner

No description provided.

@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c4853676-c726-4e37-afd5-00d415d15ff2
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Pure functions used by the profile routes: plain-text fields reject angle
brackets and control characters, lists reject non-string items, class
level is checked against the onboarding set and the study schedule uses
the day/slot format that onboarding and matching already share.
POST /profile/visibility-settings reset every omitted key to its default,
so saving one setting could silently make a private profile public, and
string values such as "false" were stored as truthy text.

Only the keys present in the body are now changed, values must be real
booleans, unknown keys and empty bodies are rejected, and the user row is
locked while the JSON value is rewritten. The dead set_dark_mode and
send_weekly_notification keys are ignored and no longer returned.

Refs PRF-02
Neither setting had any backend behaviour: no job sends a weekly summary
and nothing reads the server-side dark-mode flag. Drop the weekly-summary
toggle from the privacy modal, stop seeding both keys for new accounts and
update the API reference and OpenAPI spec.

Refs PRF-28
…y first

The private-profile message promised that connecting unlocks the full
profile, but accepted connections still got the short payload. Own
profile requests through the public route also got the private view with
is_own_profile=false.

view_profile now checks visibility before running any of the stats,
badge, post, thread and activity queries, returns the full payload for
the owner and for accepted connections, sets is_own_profile correctly and
answers 404 for unknown users. Pinned posts are only queried for the
private view that actually uses them.

Refs PRF-05, PRF-25, PRF-30
A blocked user could keep reading the blocker's profile, stats and
posts. view_profile now returns the same 404 as for a missing user when
a block exists in either direction.

Refs PRF-06
show_active_status=false only flipped a boolean; the public profile
response still carried last_active and login_streak, so anyone calling
the API directly could track users who opted out. Both are now null
unless the owner allows it. Owners always see their own values.

Refs PRF-04
The Stats tab always displayed 0 for "Marked Helpful" because the value
was a hard-coded constant. Use User.total_helpful, which
mark_comment_helpful already maintains.

Refs PRF-13
…profile

posts_liked actually counted reactions received, helpful_count was a
constant 0, total_created_threads and activity_heatmap were never read by
the profile page. Remove them from GET /profile/<username> and document
the resulting contract.

Refs PRF-13, PRF-30
POST /profile/me, GET /profile/help/suggestions and GET
/profile/can-help/suggestions had no caller (the app uses /profile/me/data
and /threads/help/suggestions) and there are no external consumers. They
also carried real defects: POST /profile/me crashed when last_active was
NULL, and the suggestion endpoints loaded every user into memory per
request and failed for everyone if one user stored malformed subjects.

GET /profile/me still serves the app shell. API reference and OpenAPI
spec updated.

Refs PRF-03, PRF-14, PRF-26, PRF-29
…ute names

/profile/me and /profile/view/<username> are HTML shells with no user
data, but they required a token and answered logged-out navigation with
raw JSON. They are now served without one; the page's first API call
returns 401 and core/api.js sends the visitor to the login screen.

A user registered as "homepage" could never be viewed because the
static /profile/homepage route shadows /profile/<username>. Reserve the
names that collide with fixed profile URL segments at registration.

Refs PRF-27
…state

PATCH /profile/update stored name, bio and department verbatim, so markup
could reach other users' browsers, a non-string name surfaced as a
generic failure, and over-long values only failed on Postgres. It also
wrote department and class to StudentProfile only, leaving the onboarding
copy that /profile/academic-info reads stale.

Name, bio, department and class level now go through the shared
validators (plain text, length limits matching the columns, canonical
class levels) and validation failures return a specific 400. Department
and class level are mirrored onto the onboarding record.

Refs PRF-01, PRF-07, PRF-08
Needed by deletes that identify the target by value rather than by URL
path, such as removing a skill whose name contains a slash.
profile.templates.js interpolated names, bios, departments, skills, goals,
tags and other users' names straight into innerHTML, including the
connections tab and the badge "recently earned by" list (attribute
context). A user who set their name to markup could run script in the
browser of anyone who opened those views.

Add a shared escapeHtml module, use it for every user-controlled value in
the profile templates and reuse it in the public profile page. A node
test renders the templates with hostile payloads; it fails against the
previous templates and passes now, and runs under pytest when node is
available.

Post titles and bodies are rendered by the posts feature's own helpers
and are left unchanged here.

Refs PRF-01
…e row

Skills were deleted via /profile/skills/<name>, so a skill containing a
slash ("C/C++") could be added but never removed (404). Goals were
deleted by list index, so a stale page could remove a different goal than
the one clicked. Skill and goal text was stored without validation.

DELETE /profile/skills and DELETE /profile/learning-goals now take the
text in the JSON body. Added values are validated as plain text with
case-insensitive de-duplication, and add/remove/pin lock the user row so
concurrent requests cannot lose an update or exceed the skill, goal or
pin limits. The frontend sends the new requests.

Refs PRF-01, PRF-10, PRF-16
PUT /profile/academic-info stored whatever list items it was given. A
dict or nested list in strong_subjects made the subject-matching code
that reads other users' rows fail for everyone matched against that
user, and items could be arbitrarily large. An empty learning_style was
ignored while the response claimed it had changed, and last_updated was
bumped even when nothing changed.

Lists must now be lists of short plain-text strings (trimmed and
de-duplicated), non-lists are rejected instead of silently skipped,
learning_style can be cleared, and last_updated only moves on a real
change.

Refs PRF-03, PRF-20
Subject and preference lists are read for every user by the connection,
discovery, thread and suggestion code, which calls string and set
operations on each item. The profile API now rejects bad items, but the
onboarding flow and scripts write the same columns, so one malformed
entry could still break matching for everyone compared against that user.

OnboardingDetails now drops non-string items, strips angle brackets,
limits item length, de-duplicates and caps each of the four list columns
on assignment, whichever code path writes them.

Refs PRF-03
The profile editor read and wrote User.study_schedule, a column nothing
else reads, while compatibility and discovery score
OnboardingDetails.study_schedule. Editing the schedule changed nothing,
and the schedule captured during onboarding was never shown or editable.

The study-schedule endpoints now read and write the onboarding schedule
in the format the scorer expects (capitalised day names, morning /
afternoon / evening). The unscored "night" slot is removed from the
editor and the API, input is validated and de-duplicated so a huge slot
list cannot be stored, and the API keeps returning lowercase day keys so
the editor is unchanged otherwise.

Refs PRF-09, PRF-24
…ounts

The edit modal reads skills from /profile/me/data, but that payload never
included them, so a user's saved skills never appeared when they opened
the editor. total_posts came from a cached counter here while the public
profile used a live count, so the two could disagree.

/profile/me/data now includes skills and both own-profile endpoints count
posts live, the same source as the public view. Fields the page never
reads (joined_at, last_active, help_streak, the onboarding block and
total_helps_given) are dropped.

Refs PRF-11, PRF-32
Creating or deleting a post did a Python read-modify-write on
User.total_posts, so two simultaneous requests (two tabs, two app
instances) could lose an update, and the counter is not reconciled
anywhere. Use a single in-SQL update that cannot go below zero and expire
the cached attribute so later reads in the request see the new value.

Refs PRF-32
validate_and_normalize_image can now reject images above a pixel count
before decoding them and shrink the longest side to a maximum, and a
Pillow decompression-bomb error is reported as a validation error instead
of escaping as an unhandled exception. CloudinaryStorage.upload_file
accepts an optional timeout. Defaults leave every existing caller
unchanged.

Refs PRF-17
Avatars were stored at full resolution (a 6000x6000 image was forwarded
unchanged) although they are shown at 28-144 px, a small highly
compressible file could force a very large in-memory decode, removing an
avatar left the image reachable on Cloudinary, provider error text
(possibly containing account details) was returned to the client, and
the unreachable local-disk fallback reported success while writing an
empty file.

Uploads are now limited to 25 megapixels, shrunk to 512 px, sent with a
timeout after the DB connection is released, and fail with a generic
502. Removal deletes the stored asset on a best-effort basis. The broken
local fallback is removed.

Refs PRF-17, PRF-22, PRF-23
A device's FCM token could be stored on several accounts (shared
computer, switching accounts) and was never cleared on logout, so
notifications for one account, including message previews, could keep
appearing on a device now used by someone else.

Saving a token now detaches it from any other account that held it, and
logout clears the logging-out account's token (best effort, never blocks
logout).

Refs PRF-18
GET /skills/popular was unauthenticated and, on every request, loaded
every user row to count skill names in Python, so an anonymous client
could keep workers busy and each app instance repeated the same work.

The result is identical for everyone, so compute it from the skills
column only, cache it in Redis for five minutes (shared by all
instances) and require a logged-in user; its only caller is the profile
editor.

Refs PRF-14
Eleven profile routes behind @token_required used the bare IP as the
rate-limit key, contrary to the rate-limit service's own rule for
authenticated routes. Students sharing a campus NAT shared one bucket
and could throttle each other while opening a single profile (which
fires several of these requests).

Use user_or_ip_key everywhere in the profile blueprint and add a test
that fails if an IP-keyed limit is reintroduced.

Refs PRF-15
Profile handlers caught every exception, logged only str(e) and returned
HTTP 400, so server faults looked like client mistakes, never reached
5xx monitoring and produced Sentry events without a stack trace.

Route the last four handlers through the shared _server_error helper
(rollback, logger.exception, 500) and add tests that a forced failure
yields a 500 with an attached traceback, that validation failures stay
400, and that no handler goes back to the bare-message pattern.

Refs PRF-31
core/api.js throws Error(<server message>) on any non-2xx response, but
every write helper in profile.api.js caught it and returned null, so
callers' res?.message was always undefined and users only ever saw
generic toasts such as "Could not save" instead of "Name must be at
least 3 characters" or "Maximum 10 skills allowed".

Write helpers now return { status: 'error', message } on failure, which
the existing callers already handle. Node tests cover the wrappers and
run under pytest alongside the template escaping tests.

Refs PRF-12
… a failed load

Tab renderers painted whatever response arrived last, so a slow request
for one tab could overwrite the content of the tab the user had switched
to, and an older post-filter response could replace the list for the
newer filter. initProfile also reset the current tab to posts after
awaiting the header, discarding a tab chosen in the meantime, and a
failed first load left a dead "Failed to load profile" message with no
way to retry short of reloading the page.

Tabs only paint when still current, superseded post-filter responses are
dropped, the default tab is set before any await (header and first tab
load in parallel), and a failed header shows a Retry button. Node tests
with a fake DOM and controllable requests fail on the previous code and
pass now.

Refs PRF-19
… URLs

last_active is only written when a user logs in, but the public profile
presented it as "Active 3d ago", which reads as presence and is wrong for
anyone who stays signed in. Relabel it "Last signed in" (it is already
hidden entirely when the owner opts out). Also escape avatar URLs in the
public profile's attribute context.

Refs PRF-21
The FCM token endpoints and the profile-view page shell were missing from
the API reference and OpenAPI spec. Document them and add a test that
compares the profile blueprint's routes with openapi.yml in both
directions, so an undocumented or stale endpoint fails the suite.

Refs PRF-28
Registration, onboarding completion and Google sign-up stored names
verbatim, the same root cause as the profile editor accepting markup in
name. Registration and onboarding now use the shared plain-text
validator (3rd-party Google display names have angle brackets stripped
and are length-limited), so a name can no longer carry markup into any
template that forgets to escape it.

Refs PRF-01
First, non-destructive half of the profile clean-up (expand step), safe
to run before the new code is deployed. It builds on the auth/onboarding
migration c3a1d94e7b52.

- student_profiles.full_name becomes nullable so the new code, which no
  longer writes it, can insert rows (pin too, if a database still has it).
- Study schedules saved through the old profile editor are copied to the
  onboarding record the matching code reads (only where onboarding has
  none), converted to its format.
- onboarding_details.department/class_level follow student_profiles.
- Dead set_dark_mode / send_weekly_notification privacy keys are removed
  and string booleans become real booleans.
- Angle brackets are stripped from names, departments, skills, goals and
  subject lists, non-string list items are dropped and tags removed from
  bios, so stored data matches what the API now enforces.

Each step checks that the table or column exists, and a test runs the
real migration against a SQLite file seeded with legacy data in a
subprocess.

Refs PRF-01, PRF-02, PRF-03, PRF-07, PRF-09
…opped

Remove ProfileChangeHistory (never written or read) and the unused
StudentProfile columns: date_of_birth, guardian_name, guardian_contact,
registered_at, status, and the username / pin / full_name copies of
User fields that nothing read (the pin copy duplicated a password hash
and was only ever written by one of the password flows). Also remove
User.study_schedule, which the study-schedule endpoints no longer use.

Registration, the password helper, the seed script, test factories and
tests no longer write them. The database objects themselves are dropped
by the next migration, after this code is deployed.

Refs PRF-07, PRF-09
Second, destructive half of the profile clean-up (contract step). Run it
after the application code that no longer touches these objects is
deployed. Drops, each only if present:

- table profile_change_history (never written or read)
- student_profiles.full_name (a copy of users.name nothing read) and
  registered_at (never read)
- users.study_schedule (replaced by onboarding_details.study_schedule,
  copied there by the previous revision)

The other unused student_profiles columns (pin, username, status,
date_of_birth, guardian_*) were already dropped by the auth/onboarding
migration c3a1d94e7b52. The downgrade re-creates what it drops, empty
and nullable.

Refs PRF-07, PRF-09
…gres concurrency tests

The row lock added for skills, goals, pins and privacy settings did not
protect anything: the locked SELECT returned the user object already
loaded earlier in the request, so after waiting for the lock the handler
still modified a stale copy and simultaneous requests overwrote each
other. populate_existing() makes the locked query refresh the row.

SQLite shares one connection and ignores row locks, so the existing
tests could not show this. The integration suite can now run against a
real database via TEST_DATABASE_URL, and a new set of tests (skipped
unless that points at PostgreSQL) fires 8 simultaneous requests at each
write path: skill adds keep every skill, the skill limit and the pin cap
of 5 hold, partial privacy updates do not overwrite each other and
concurrent post creation counts every post. They failed before this fix.

Refs PRF-16
…ects

The questionnaire accepted weekday names in any case but stored them as
sent, while the schedule-overlap scoring compares capitalised names
("Monday"). A client sending "monday" would never overlap with anyone.
Store capitalised names and merge a day given in several spellings.

Refs PRF-09
Profile editing was written against its own limits, which no longer
matched the onboarding questionnaire: subjects were cut to 15 items of 50
characters (the questionnaire allows 30 of 100), departments were capped
at 50 (the column and questionnaire allow 100), names at 80 (100), class
levels also accepted legacy labels the questionnaire rejects, and
learning style / study preferences were free text where the
questionnaire uses fixed values.

Take the constants from the onboarding service so both entry points
accept exactly the same values, reject over-long lists instead of
silently cutting them, and drop the duplicate class-level list. A test
keeps the schedule vocabulary of the two in step.

Refs PRF-03, PRF-08, PRF-20
create_app() gives app.logger its own handlers and sets propagate=False,
so pytest's caplog (attached to the root logger) never receives its
records and the test failed on main as well as on this branch. Attach a
capturing handler to the app logger instead; the assertions are unchanged.
@Devpaul-01
Devpaul-01 force-pushed the fix/profile-production-readiness branch from 2475384 to 65d4609 Compare November 27, 2026 05:43
@Devpaul-01
Devpaul-01 merged commit 65d4609 into main Nov 27, 2026
1 of 2 checks passed
@railway-app
railway-app Bot temporarily deployed to extraordinary-education / production November 27, 2026 05:43 Inactive

This branch was previously deployed

1 inactive deployment
extraordinary-education / production — 65d4609b Deployed Nov 27, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant