Skip to content

Remediation plan

A worked plan for closing everything in Known issues, plus the findings turned up while writing this page. Each item states what is wrong, which files change, how to verify the change, and what could break.

Read the revival runbook first

The production deployment no longer exists — every towitlinks.com hostname stopped resolving. Revival runbook is the plan for bringing the system back up on tacocars.com, and it reorders some of the work below: parts of Phase 1 and Phase 3 are prerequisites for redeploying, while Phase 4.1 becomes moot once the console moves to Cloudflare Pages. This page still describes every fix; the runbook decides what happens first.

Two architectural decisions are now settled and this plan assumes them:

  • Celery is abandoned. Recurring work runs as scripts scheduled from Google Cloud, calling the existing HTTP endpoints under /google/hooks/.
  • WebSockets are abandoned. Real-time delivery is Cloud Firestore.

Both were already true in practice. The work below is making the repository say so.

Suggested order

The phases are ordered by risk reduction per hour spent, not by size. Phase 0 is the only one with a deadline attached to it; everything after is cleanup that can be scheduled.

Phase Theme Items Rough effort
0 Security 4 1–2 days
1 Delete the phantom infrastructure 3 1 day
2 Correctness bugs 3 half a day
3 Supply chain and CI 4 1–2 days
4 Deployment quality 2 1–2 days
5 Consolidation 2 open-ended

Each phase is a pull request, or a small series of them. Phase 1 and Phase 2 touch different files and can run in parallel; Phase 0 should land alone so it is easy to review and revert.


Phase 0 — Security

0.1 Finish the secrets remediation

Commit f3a79e66 removed backend/google_credentials.json and frontend/towitlink.jks from the index. The history still contains both. The remaining work is operational, not code:

  1. Rotate the Google service-account key in the Google Cloud console for project towitlinknotify. Disable the leaked key after the new one is in place, not before.
  2. Place towitlink.jks on the Android build host (154.53.40.104, ~/build_apk/VoIP) outside the repository checkout, and point frontend/android/key.properties at the new path. The host currently receives the keystore from a git pull and will lose it on the next one, breaking release signing.
  3. Decide about the keystore password, published in plain text at frontend/android.md:22. A published app's signing key cannot be rotated without Play App Signing; if the app is not yet enrolled, enrolling it is the only route to recovering from this.

Rewriting history is a separate decision

git filter-repo would remove both blobs from every commit, but it rewrites every SHA and invalidates every outstanding clone, branch and pull request. It is only worth doing if the repository will become public or is shared outside the team. Rotation protects against the leak regardless; history rewriting only reduces the blast radius of a future clone.

0.2 A third credential is committed

frontend/package.json:25 carries a Chromatic project token in the chromatic script:

"chromatic": "npx chromatic --project-token=chpt_a94db6b5bac0ae3 --exit-zero-on-changes",

A Chromatic project token allows publishing builds to that project. Rotate it in the Chromatic project settings, move it to CHROMATIC_PROJECT_TOKEN in the environment, and change the script to npx chromatic --exit-zero-on-changes — the CLI reads that variable on its own.

0.3 Authenticate the Google Cloud hooks

backend/google_hooks/urls.py registers three endpoints and none of the three views declares permission_classes or authentication_classes:

Endpoint View What it does
POST /google/hooks/reminders RemindersWebhookView Reads due NoteReminder rows and creates notifications
POST /google/hooks/records RecordsWebhookView Runs record_task() — recording payment and auto-removal
POST /google/hooks/charges ChargesUpdaterView update_all_twilio_data() — pulls Twilio usage into the billing mirror

Because DRF has no default permission class (see 0.4), all three are reachable by anyone who knows the URL. Two of them mutate billing state.

Recommended approach: OIDC tokens from Cloud Scheduler. Cloud Scheduler can attach a Google-signed ID token to its HTTP target, which the backend verifies against a known service account and audience. No shared secret ever travels in a header or appears in a proxy log, and the token expires on its own.

  • Add a permission class, e.g. settings/google/permissions/is_cloud_scheduler.py, that reads the Authorization: Bearer header and calls google.oauth2.id_token.verify_oauth2_token(token, Request(), audience=settings.GOOGLE_HOOKS_AUDIENCE), then checks claims["email"] == settings.GOOGLE_HOOKS_SERVICE_ACCOUNT and claims.get("email_verified"). google-auth already ships as a dependency of firebase-admin; pin it explicitly rather than relying on that.
  • Add GOOGLE_HOOKS_AUDIENCE and GOOGLE_HOOKS_SERVICE_ACCOUNT to settings.py, entrypoint.sh and backend/.env.example.
  • Set permission_classes = [IsCloudScheduler] on all three views.
  • In Cloud Scheduler, configure each job with an OIDC token, the service account, and an audience matching the setting.

A shared-secret header (X-Hooks-Token compared with hmac.compare_digest) is the cheaper fallback if OIDC is not practical. It is meaningfully weaker: the secret is long-lived, is replayable, and lands in every intermediate access log.

Open question — resolve this before writing any code

Nobody has confirmed what currently calls /records and /charges, or how often. Find the existing scheduler jobs before adding authentication, or the first deploy after this change silently stops billing reconciliation. If no scheduler exists, that is the finding — these jobs have not been running.

Nothing in this repository configures a scheduler: there is no Terraform, no schedule: trigger in any workflow, and no cron file. Whatever calls these endpoints is configured entirely outside version control. Bring it into the repository as part of this phase, so the next person does not have to run the same audit.

How to run the audit

Signed in as a user with roles/cloudscheduler.viewer on every project the team owns:

gcloud projects list --format='value(projectId)' | while read -r p; do
  echo "== $p"
  gcloud scheduler jobs list --project="$p" --location=- \
    --format='table(name, schedule, state, httpTarget.uri, httpTarget.oidcToken.serviceAccountEmail)' 2>/dev/null
done

--location=- searches every region; a job created in a region nobody thinks about is the usual reason an audit like this comes back empty when it should not.

If Cloud Scheduler is empty, widen the search before concluding the jobs do not exist:

gcloud functions list --project="$p"                      # a function on a Pub/Sub schedule
gcloud run jobs list --project="$p" --region=-            # a Cloud Run job with a trigger
gcloud compute instances list --project="$p"              # a VM carrying a plain crontab

Also check outside Google Cloud — a host-level crontab -l on the Swarm node, a Portainer scheduled task, or a third-party pinger such as cron-job.org are all plausible and none of them would appear above.

Record the result here when it is known, whatever it turns out to be.

Related: RemindersWebhookView computes start_date and then does not use it in the queryset (date__lt=end_date, active=True matches every past-due reminder, not a one-minute window). The behaviour is correct — reminders are not missed if a run is skipped — but the print claims a window that the filter does not apply. Fix the message while touching the file.

0.4 Give DRF a default permission class

backend/settings/settings.py:173-188 sets DEFAULT_AUTHENTICATION_CLASSES but not DEFAULT_PERMISSION_CLASSES, so DRF falls back to AllowAny for any view that forgets to declare its own.

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
    ...
}

Current exposure is small — an audit of all 36 modules that define views found only two that rely on the default:

  • backend/voip/client/api/newsletter.py — NewsLetterView, a public newsletter signup called from the landing. Intentionally public: add permission_classes = [AllowAny] explicitly.
  • backend/voip/redirects/api.py — CompanyRedirectsView, which reads and writes a company's call-redirect rules. Not intentionally public. Today an anonymous POST reaches get_company_from_request (voip/company/features.py:212), which calls request.user.defaultCompanyUser() on AnonymousUser and raises AttributeError → HTTP 500. So it is a crash rather than a data leak, but nothing except that attribute error is stopping it. Add permission_classes = [IsAuthenticated].

The Twilio webhooks are not affected: BaseAdapterCallView (voip/calls/adapters/base_api_call.py:29) and both message adapters declare permission_classes = [IsTwilio], which verifies the X-Twilio-Signature header. That path is sound.

After the default is in place, run the full route list and confirm nothing that should be public (health checks, the landing contact form, redirects' own public side if one exists) started returning 401.


Phase 1 — Delete the phantom infrastructure

1.1 Remove Celery and RabbitMQ

There is no Celery task code anywhere in the backend: no settings/celery.py, no @shared_task, no .delay() or .apply_async(). The worker and beat containers have never been able to do anything.

Files to change:

File Change
backend/requirements.txt:10 Drop celery
backend/Dockerfile.celery Delete the file
backend/rabbitmq.conf Delete the file
backend/docker-compose.yml:20 Drop depends_on: rabbitmq from the web service
backend/docker-compose.yml:22-27, 33-42 Delete the celery_worker and celery_beat services
backend/docker-compose.yml:44-52 Delete the rabbitmq service
backend/docker-compose-dev.yml:16-23, 25-29, 35, 37-41, 46 Same removals
backend/entrypoint.sh:89 Drop load_secret CELERY_BROKER

RabbitMQ has no consumer other than the Channels layer, which Phase 1.2 removes, so the two removals must land together or RabbitMQ must stay until 1.2 does. Prefer one pull request covering both.

Also remove the TWTLNKPROD_CELERY_BROKER and the RabbitMQ Swarm secrets from Portainer once the stack no longer references them, and delete the rabbitmq volume.

1.2 Remove Django Channels and the WebSocket plumbing

Nothing sends or receives over a WebSocket today. Both routers are empty.

Backend:

File Change
backend/requirements.txt:13,18,19,20 Drop daphne, channels, channels-rabbitmq, channels-redis
backend/requirements.txt Also drop websockets and websocket-client if nothing else imports them — check first
backend/settings/settings.py:56 Drop "daphne" from INSTALLED_APPS
backend/settings/settings.py:109-138 Delete the whole CHANNEL_LAYERS block and the CHANNELS_BACKEND branch
backend/settings/asgi.py:13-23 Replace ProtocolTypeRouter with application = django_asgi_app
backend/settings/ws_urls.py Delete
backend/voip/ws_urls.py, backend/calls/ws_urls.py Delete
backend/settings/ws_middlewares/ Delete the package — nothing imports it
backend/calls/hooks/streaming.py Delete StreamingWS — never routed, never instantiated
backend/entrypoint.sh:82-86 Drop WEBSOCKET_DOMAIN and the four CHANNELS_* loads
backend/.env.example:100,114-116 Drop the matching entries

Check WEBSOCKET_DOMAIN before deleting it

settings.py:359 reads WEBSOCKET_DOMAIN, and settings.py:378 uses it to build TWILIO_VOICE_STREAM_WEBSOCKET. That is Twilio Media Streams, a different feature from Django Channels. It appears dead — its only consumer would be calls/hooks/streaming.py, which is not routed — but confirm no Twilio phone number or TwiML <Stream> verb points at it before removing the setting. If media streaming is planned, keep WEBSOCKET_DOMAIN and remove only the Channels half.

notify.py is a live caller

backend/voip/messages/features/notify.py makes four async_to_sync(layer.group_send) calls (lines 38, 65, 91, 122), reached from features/instruct.py:102, features/unread.py:29,49 and features/subscriptions.py. They publish into MessagesNotifyGroup, which no consumer subscribes to, so the payloads are discarded today. Deleting them changes no observable behaviour — but confirm first that the Firestore path in voip/messages/infrastructure/rep_imp_message.py covers the same four events (new message, unread count, removal, unsubscription) for the console. If it does not, the console is already missing those updates and that is a bug to fix, not a line to delete. Note that notify.py:7 imports FSBlocked and never uses it, which suggests a Firestore migration that was started and abandoned in this file.

ASGI stays. asgi.py routes plain HTTP as well, and the app is served by uvicorn in backend/Dockerfile:31, docker-compose.yml:5 and docker-compose-staging.yml:17. Removing the WebSocket protocol does not mean switching to WSGI.

Frontend:

File Change
frontend/.env.example:3 Drop VITE_WSAPI_URL — read nowhere in src/
frontend/src/lib/actions/msg/MsgCTL.ts:44,84-89,110,210,217 Remove the stale WebSocket JSDoc and the commented-out this.ws.onUnsubscribed block
frontend/src/lib/actions/notifications/NotificationCTL.ts:14 Same, in the class docstring
frontend/src/lib/actions/session/SessionDataCTL.ts:62 Same
frontend/src/lib/actions/msg/messages/MessageCTL.ts:32 Drop the @param {MessageWS} line if the parameter is gone

Also remove VITE_WSAPI_URL from any FRONTEND_ENV / STAGING_FRONTEND_ENV repository secret.

1.3 Delete the dead and misleading files

File Action
landing/wrangler.jsonc, frontend/wrangler.jsonc Delete — neither app is served by Cloudflare
frontend/src/lib/shared/constants.ts Delete — references a Prisma Part type from another project and does not type-check
backend/calls/urls.py Delete or reduce to the lines that are actually included; the live webhooks are under /webhooks/
frontend/src/lib/fetchWithRefresh.ts Delete after migrating its last callers to Fetcher
Root Dockerfile Stop copying frontend/ into the landing image
backend/settings/firebase/firebase_init.py Delete — initialize_firebase() begins with a bare return, so its body never runs. The real initialisation is the module-level code in settings/firebase/__init__.py
frontend/frontend.conf Decide: it describes app.towitlinks.com but nothing copies it into an image, while frontend_staging.conf is the one in use. Either wire it into the production image or delete it and document where the production nginx config actually lives

Deleting fetchWithRefresh.ts and constants.ts needs a grep for importers first; the rest have no importers.


Phase 2 — Correctness bugs

2.1 Three dead API routes

In backend/voip/urls.py:

  • :272 registers "extension/int:extension_id" without angle brackets, so the literal string int:extension_id is the path and no numeric URL reaches GetUpdateAndDeleteExtensionView. Change to "extension/<int:extension_id>".
  • :293 and :296-298 both register "stateTrace". ListAndCreateStateTracesAPIView always wins. GetAndCreateStateTracesAPIView's handlers also expect a state_trace_id kwarg the route never supplies, so it would raise TypeError even if reached. Give it its own path (stateTrace/<int:state_trace_id>) or delete the view and its import at :72.
  • ListAndCreatePhoneNumberView defines no post despite the name. Either implement it or rename the view and its route to match what it does.
  • :176 includes voip.messages.urls_api — an empty urlpatterns — at path("/", ...), mounting it at the double-slash /api/v1//. Delete the include and the file.

Each of these is a one-line change. Check the console for callers before changing the extension path: a client that has been working around the broken route will break when it is fixed.

2.2 Guard the nullable tenancy call

request.user.defaultCompanyUser() (backend/voip/companyUser/models.py:59) returns the CompanyUser flagged is_default=True and can return None. Call sites that dereference it without a guard include voip/user/features.py:122 and voip/dashboard/api.py:17.

The cheapest durable fix is to stop returning None ambiguously:

  1. Change get_company_from_request (voip/company/features.py:212-214) to raise a DRF PermissionDenied when defaultCompanyUser() returns None, so every caller gets a 403 instead of an AttributeError 500.
  2. Route the remaining direct defaultCompanyUser() call sites through that helper.
  3. Add a database constraint or a save() guard ensuring every User with a CompanyUser row has exactly one marked is_default=True, then backfill.

Separately, voip/company/permissions.py:9-10 carries a FIXME noting that the super-tenant mechanism assumes exactly one Company has isAdmin=True. Add a UniqueConstraint with a condition on isAdmin=True and a data migration that fails loudly if more than one row exists.

2.3 Two parallel message implementations

voip/messages/features/ (Django ORM plus the channel layer) and voip/messages/{domain,application,infrastructure,adapters}/ (hexagonal, Firestore-backed) both handle messages. The hexagonal side is what the Twilio webhooks reach; the legacy side is what instruct.py uses for outbound sends.

This is not a bug by itself, but it is why notify.py exists and why 1.2 needs a verification step. Decide which side owns message state and migrate the other, or at minimum write down the split in docs/architecture/backend.md so the next person does not pick the wrong one.


Phase 3 — Supply chain and CI

3.1 Pin the backend dependencies

backend/requirements.txt pins only pytest and hypothesis. Django, DRF, Twilio, Stripe and firebase-admin float, so two image builds weeks apart can ship different versions and an upstream regression is invisible in the diff.

  1. Build the current production image and capture the resolved set: docker run --rm <image> pip freeze > backend/requirements.lock.
  2. Keep requirements.txt as the human-edited direct dependency list, with == pins taken from the lock for every entry.
  3. Change backend/Dockerfile to install from the lock.
  4. Enable Dependabot or Renovate for backend/requirements.txt so the pins move deliberately.

Do this after Phase 1, so the lock does not capture Celery and Channels.

3.2 Reconcile the .env.example files

docs/operations/configuration.md documents the real variable set. The example files have drifted from it: the backend example is missing seven variables the code reads and carries one it does not, and the frontend example names the Firebase keys with the wrong prefix and lists two variables nothing reads.

Fix the files to match the documentation, then delete the drift warnings from docs/operations/configuration.md and the corresponding section of docs/known-issues.md. Phase 0.3 and Phase 1.2 both change this set, so sequence this after them.

3.3 Make CI run checks

No workflow runs tests, linting or type checking, and nothing gates a merge. The tooling is already installed in frontend/package.json — ESLint, Prettier, Vitest and Playwright are all devDependencies with no scripts calling them.

Add a ci.yml triggered on pull requests to develop and main:

jobs:
  backend:
    steps:
      - run: pip install -r backend/requirements.txt
      - run: python backend/manage.py check --deploy
      - run: pytest backend
  frontend:
    steps:
      - run: pnpm --dir frontend install --frozen-lockfile
      - run: pnpm --dir frontend validate      # svelte-check, exists today
      - run: pnpm --dir frontend format:check  # add the script
      - run: pnpm --dir frontend lint          # add the script and an eslint config

Supporting changes:

  • Add "format": "prettier --write .", "format:check": "prettier --check ." and "lint": "eslint ." to frontend/package.json. A .prettierrc already exists; ESLint has only the inline eslintConfig extending plugin:storybook/recommended, so a real eslint.config.js has to be written.
  • Expect the first format:check and lint runs to fail on the existing tree. Land one formatting-only commit first, and start ESLint with a narrow rule set that passes, then tighten.
  • manage.py check --deploy will flag genuine issues (SECURE_* settings). Read its output rather than suppressing it.
  • Enable branch protection on develop and main requiring the new job.

Also delete the four unused repository secrets FRONTEND_ENV, STAGING_FRONTEND_ENV, PORTAINER_WEBHOOK_VOIP_FRONTEND_DEV and PORTAINER_WEBHOOK_VOIP_NGINX_DEV, or wire them into Phase 4.2. Leaving credentials in a secret store that nothing reads is a standing risk with no benefit.

3.4 Clean up .gitignore

The root .gitignore ignores package.json (line 15), pnpm-lock.yaml (line 14) and pyproject.toml (line 16); frontend/.gitignore:45 repeats the lockfile. The files are already tracked so the patterns do nothing today, but they will silently drop a regenerated lockfile, and backend/Dockerfile copies package.json and pnpm-lock.yaml at build time. Remove those three patterns. Keep the secrets and build-artifact blocks as they are.


Phase 4 — Deployment quality

4.1 Make the console deploy atomic

frontend/Dockerfile builds an image that serves nothing: frontend/entrypoint.sh runs rm -rf /voip-frontend/*, copies the build in, and sleeps, while a separate nginx service serves that shared volume. For the duration of the copy, nginx serves a mixture of old and new files — typically an old index.html referencing hashed assets that no longer exist, which is a hard failure for a SPA.

Replace the wipe-and-copy with a symlink swap:

RELEASE="/voip-frontend/releases/$(date +%s)"
mkdir -p "$RELEASE"
cp -R /built-files/. "$RELEASE/"
ln -sfn "$RELEASE" /voip-frontend/current.tmp
mv -T /voip-frontend/current.tmp /voip-frontend/current
ls -1dt /voip-frontend/releases/* | tail -n +4 | xargs -r rm -rf

mv -T on a symlink is atomic on the same filesystem. Point the nginx root at /voip-frontend/current and the switch becomes instantaneous, with the previous release still on disk for a rollback.

The longer-term fix is to serve the build from the image itself — an nginx base image with the static files copied in — and let Swarm do a rolling update. That removes the shared volume, the sleeping container and the ordering problem in one step, and is worth the larger change if the console is deployed often.

4.2 Give the console a pipeline

The two frontend workflows were deleted in b036a2d7, so the web console has no CI/CD at all and every production release is manual. Only the staging backend redeploys automatically.

Restore a workflow that builds the console image on a push to main, pushes it to Docker Hub alongside the backend, and calls the Portainer webhook — the pattern backend developer.yml already uses. The four orphaned secrets in 3.3 are most likely the remains of exactly this.

Decide deliberately whether production should redeploy on merge or stay a manual Portainer action. Either is defensible; the current state — the capability was deleted and the secrets left behind — is not a decision, it is a leftover.


Phase 5 — Consolidation

5.1 One query library in the console

@sveltestack/[email protected] and @tanstack/svelte-query@5 are both installed. Every controller uses the former; nothing uses the latter.

The cheap move is to uninstall @tanstack/svelte-query now and remove the ambiguity. The expensive move is to migrate to it — @sveltestack/svelte-query is unmaintained and does not support Svelte 5, so this becomes mandatory the day the console moves off Svelte 4. Do the cheap move today and open an issue for the migration, scoped together with the Svelte 5 upgrade rather than as a standalone refactor.

5.2 Document what remains

As each phase lands, update the documentation in the same pull request:

Phase Pages to update
0 known-issues.md, reference/api.md, architecture/backend.md
1 architecture/overview.md, architecture/backend.md, operations/configuration.md, operations/environments.md, getting-started.md, README.md, CLAUDE.md
2 reference/api.md, known-issues.md
3 operations/configuration.md, operations/deployment.md
4 operations/deployment.md, operations/environments.md

A finished item is deleted from known-issues.md, not marked done there. That page describes the present, and a plan page that disagrees with it is worse than no plan page.


Items deliberately not in this plan

  • Rewriting git history. Covered as a decision in 0.1, not scheduled.
  • Migrating off Svelte 4. Large, independent of everything here, and 5.1 is its prerequisite.
  • Replacing the hexagonal/legacy split in voip/messages. 2.3 asks for a decision and a written record, not a refactor.