Database Security & RLS Tiers

Last updated: 2026-07-08

SparkyFitness uses PostgreSQL Row-Level Security (RLS) to enforce strict data isolation between accounts, caregivers, family members, and third-party integrations (API keys). This document covers the security design, context switching mechanism, and the three-tier database table classifications.


Identity & Context Functions

PostgreSQL session variables are initialized at the start of every pool client transaction (via the public.set_app_context(userId, authenticatedUserId) helper). RLS policies evaluate access using these functions:

  1. current_user_id(): Returns the ID of the active profile context being viewed (which changes during family delegation context switching; read from app.user_id).
  2. authenticated_user_id(): Returns the ID of the true authenticated logged-in actor (which never changes during context switching; read from app.authenticated_user_id).
  3. can_access_user_data(targetUserId, permissionType, authenticatedUserId): Checks whether the authenticated user holds the given logical permission over the target user's data (diary, checkin, medications, reports, and read-only *_read variants). Domain helpers such as has_diary_read_access, has_checkin_read_access, and has_medication_access wrap it. Cycle and pregnancy are owner-only and are not delegatable.

The Three Security Tiers

All tables in the SparkyFitness database are classified into one of three security tiers to isolate data access according to the least-privilege principle:

Tier 1: Strictly Private (Owner-Only Read & Write)

These tables contain highly sensitive credentials, API keys, SSO tokens, 2FA recovery data, or private log histories. Only the owner (authenticated_user_id()) can view or modify these records. Family delegates and context-switched API keys have absolutely zero access.

Table NameDescriptionWrite (insert/update/delete)Read (select)
userAccount identity, password hash, role, email statusOwner-Only (authenticated_user_id())Owner-Only
two_factorTwo-factor authentication (2FA) recovery codes and secretsOwner-OnlyOwner-Only
verificationEmail verification tokensOwner-OnlyOwner-Only
api_keyUser-generated API keys for external accessOwner-OnlyOwner-Only
user_oidc_linksOpenID Connect SSO credentials linksOwner-OnlyOwner-Only
passkeyPasskey credentials for passwordless loginOwner-OnlyOwner-Only
sessionActive user authentication sessionsOwner-OnlyOwner-Only
passkey_registration_ticketsShort-lived (~60s), single-use tickets bridging the mobile→browser passkey registration handoff (transient session material)System-Only (RLS on, no policies; getSystemClient only)System-Only
accountAuth credentials and email accountsOwner-OnlyOwner-Only
sparky_chat_historyAI Assistant chat messages and historyOwner-OnlyOwner-Only
user_ignored_updatesRecords of skipped release updatesOwner-OnlyOwner-Only
admin_activity_logsAdmin action auditsAdmin-OnlyAdmin-Only
ai_service_settingsUser-defined custom assistant configurationsOwner-OnlyOwner-Only (Public configs readable by all)
cycle_settingsCycle & pregnancy hub settings (mode, cycle parameters, birth control, conditions)Owner-OnlyOwner-Only
cycle_daily_entriesPer-day cycle logs (flow, period products, BBT, cervical mucus, moods, libido, notes)Owner-OnlyOwner-Only
cyclesDerived/manually-corrected period & cycle history recordsOwner-OnlyOwner-Only
user_cycle_display_preferencesPrivate preference on cycle dashboard tile/card visibilityOwner-OnlyOwner-Only
user_mood_display_preferencesPersonal show/hide config for the mood pickerOwner-OnlyOwner-Only
cycle_test_entriesOvulation (OPK) and pregnancy test logsOwner-OnlyOwner-Only
pregnanciesPregnancy records (due date, status, linked prenatal medication)Owner-OnlyOwner-Only
pregnancy_kick_sessionsFetal kick-counter sessionsOwner-OnlyOwner-Only
pregnancy_contractionsContraction timer logsOwner-OnlyOwner-Only
pregnancy_photosBump photo journalOwner-OnlyOwner-Only
pregnancy_checklist_stateWeekly pregnancy checklist completion/custom itemsOwner-OnlyOwner-Only
health_appointmentsPrenatal & other health appointmentsOwner-OnlyOwner-Only

Tier 2: View-Only Shared (Owner-Only Write, Delegate-Read)

These tables contain user profiles, layouts, display settings, and custom databases (like the foods/exercises database libraries). Switched delegates can view this data to render the dashboard, but only the account owner is allowed to create or edit them.

Table NameDescriptionWrite (insert/update/delete)Read (select)
profilesUser full name, height, and display metricsOwner-Only (authenticated_user_id())Switched Delegate (current_user_id())
user_preferencesUnit display preferences (Metric vs Imperial)Owner-Only (authenticated_user_id())Switched Delegate
user_nutrient_display_preferencesRearranged nutrient column preferencesOwner-OnlySwitched Delegate
user_medication_display_preferencesPrivate preference on GLP-1/Medication displayOwner-OnlyDelegate with can_manage_medications or can_view_reports
user_dashboard_layoutsRearranged dashboard widget positionsOwner-OnlySwitched Delegate
onboarding_dataInitial user onboarding metricsOwner-OnlySwitched Delegate
onboarding_statusUser onboarding statusOwner-OnlySwitched Delegate
meal_typesCustom breakfast, lunch, dinner, snack layoutsOwner-OnlySwitched Delegate with can_manage_diary or can_view_reports
foodsCustom food items created by the userOwner-OnlyDelegate with can_view_food_library, can_manage_diary, or can_view_reports
food_variantsServing options / sizes for custom foodsOwner-OnlyDelegate with can_view_food_library, can_manage_diary, or can_view_reports
mealsCustom meals created by the userOwner-OnlyDelegate with can_view_food_library, can_manage_diary, or can_view_reports
meal_foodsIngredients assigned inside a custom meal — either a food (food_id) or a linked reusable sub-meal (child_meal_id, item_type='meal'). Writing a linked-meal row requires the caller to also have library access to the referenced sub-meal, in addition to owning the parent meal.Owner-Only (and the referenced food/sub-meal must be accessible to the owner)Delegate with can_view_food_library, can_manage_diary, or can_view_reports
exercisesCustom exercises created by the userOwner-OnlyDelegate with can_view_exercise_library, can_manage_diary, or can_view_reports
workout_presetsCustom workouts/presets created by the userOwner-OnlyDelegate with can_view_exercise_library, can_manage_diary, or can_view_reports
workout_preset_exercisesExercises assigned inside a workout presetOwner-OnlyDelegate with can_view_exercise_library, can_manage_diary, or can_view_reports
workout_preset_exercise_setsReps/sets configured inside a preset exerciseOwner-OnlyDelegate with can_view_exercise_library, can_manage_diary, or can_view_reports
workout_plan_templatesTemplates for weekly workout schedulesOwner-OnlyDelegate with can_view_exercise_library, can_manage_diary, or can_view_reports
external_data_providersConfigured API integrations (FatSecret, USDA)Owner-OnlyDelegate with share_external_providers
family_accessSharing rules & delegation credentialsOwner-OnlyOwner or Switched Delegate
user_goalsActive daily calorie/macro goalsOwner-OnlyDelegate with can_manage_diary or can_view_reports
user_nutrient_goal_preferencesPer-user minimum/maximum/target goal direction override per nutrientOwner-OnlyDelegate with can_manage_diary or can_view_reports
weekly_goal_plansScheduled goal plan adjustmentsOwner-OnlyDelegate with can_manage_diary or can_view_reports
user_water_containersConfigured container sizes (e.g. 500ml bottle)Owner-OnlyDelegate with can_manage_diary or can_view_reports

Tier 3: Delegate-Writable (Daily Logs & Schedules)

These tables contain daily diaries, logging entries, and scheduler items. Caregivers/delegates with active delegation permissions are granted full read and write access to log or modify data on behalf of the owner.

A. Diary Logs (Writable by delegates with can_manage_diary / Readable by can_view_reports or can_manage_diary)

Table NameDescriptionWrite (insert/update/delete)Read (select)
food_entriesLogged meals/calories consumed for the dayDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
food_entry_mealsMeal details associated with logged food entriesDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
food_favoritesStarred (favorite) foods/meals for quick re-loggingDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
exercise_entriesLogged exercises/sets completed for the dayDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
exercise_preset_entriesLogged workout presets for the dayDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
exercise_entry_setsReps, weights, and sets completed for the logged exercisesDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
exercise_entry_activity_detailsHeart rate, distance, and activity details for workout logsDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
water_intakeTotal water logged for the dayDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
water_intake_entriesIndividual logged water cups/containers for the dayDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
meal_plan_template_assignmentsActive meal templates scheduled to the calendarDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
workout_plan_template_assignmentsActive workout templates scheduled to the calendarDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports
workout_plan_assignment_setsActive sets scheduled in workout plansDelegate with can_manage_diaryDelegate with can_manage_diary or can_view_reports

B. Medication & Symptom Logs (Writable by delegates with can_manage_medications / Readable by can_view_reports or can_manage_medications)

Table NameDescriptionWrite (insert/update/delete)Read (select)
medicationsCustom medication inventory lists (e.g. insulin)Delegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports
medication_schedulesReminders/schedules to take medicationsDelegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports
medication_entriesLogs of medications takenDelegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports
medication_pensTrackers for medication delivery pensDelegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports
injection_entriesInjection logs (e.g., site of injection)Delegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports
medication_titration_stepsAutomated titration dosage plansDelegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports
user_custom_symptomsCustom tracked health symptomsDelegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports
symptom_entriesLogs of daily tracked symptom severityDelegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports
user_custom_symptom_locationsCustom locations where symptoms occurDelegate with can_manage_medicationsDelegate with can_manage_medications or can_view_reports

C. Check-In & Wellness Logs (Writable by delegates with can_manage_checkin / Readable by can_view_reports or can_manage_checkin)

Table NameDescriptionWrite (insert/update/delete)Read (select)
check_in_measurementsWeight, neck, waist, hips measurementsDelegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
check_in_photosProgress photosDelegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
sleep_entriesSleep logs (bedtime, wake time)Delegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
sleep_entry_stagesSleep stage breakdowns (REM, Deep, Light)Delegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
sleep_need_calculationsAI sleep need calculationsDelegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
daily_sleep_needSleep goals calculated for the dayDelegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
fasting_logsLogs of fasting timelines (start/end fast)Delegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
mood_entriesLogged mood and energy levelsDelegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
day_classification_cacheDaily summary caching logsDelegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
custom_categoriesUser-defined custom measurement categories (e.g. GLP-1 daily check-in metrics)Delegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
custom_measurementsLogged values for custom measurement categoriesDelegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports
user_custom_moodsUser-defined mood tags (icon/color) for the mood pickerDelegate with can_manage_checkinDelegate with can_manage_checkin or can_view_reports

System & Global Reference Tables (Public Read, Admin Write)

These tables store global configuration settings, lookup values, and reference metadata. They do not contain user-specific data and do not have Row-Level Security enabled. All authenticated users can read them, but only administrators can update them.

Table NameDescriptionWrite (insert/update/delete)Read (select)
global_settingsApplication global feature flags and system configurationsAdmin-OnlyAuthenticated Users
backup_settingsAutomated database backup timing and storage credentialsAdmin-OnlyAdmin-Only
sso_providerActive Single Sign-On providers (Google, Apple, etc.)Admin-OnlyPublic (Login page)
oidc_providersOpenID Connect integration settings and metadataAdmin-OnlyPublic
external_provider_typesSearch provider configurations lookup (FATSecret, USDA)Admin-OnlyAuthenticated Users
medication_typesMedication categories lookup (GLP-1, Insulin, ADHD, etc.)Admin-OnlyAuthenticated Users
medication_route_typesMedication administration route lookup (Subcutaneous, Oral)Admin-OnlyAuthenticated Users
medication_schedule_typesMedication scheduling frequencies lookup (Daily, Weekly)Admin-OnlyAuthenticated Users