CRM stands for "[Customer Relationship Management](https://en.wikipedia.org/wiki/Customer_relationship_management)" but we actually
use it to manage contacts and donations. It is how we send our massive
newsletter once in a while.

[[_TOC_]]

# Tutorial

## Basic access

The main website is at:

<https://crm.torproject.org/>

It is protected by basic authentication and the site's login as well,
so you actually need *two* sets of password to get in.

# Howto

## Monitoring mailings

The CiviCRM server can generate large mailings, in the order of
hundreds of thousands of unique email addresses. Those can create
significant load on the server if mishandled, and worse, trigger
blocking at various providers if not correctly rate-limited.

For this, we have various knobs and tools:

 * [Grafana dashboard watching the two main mailservers](https://grafana.torproject.org/d/Ds5BxBYGk/postfix-mtail?orgId=1&from=now-24h&to=now&var-node=eugeni.torproject.org&var-node=crm-int-01.torproject.org)
 * [Place to enable/disable mailing](https://crm.torproject.org/civicrm/admin/job?reset=1&action=browse) (grep for `Send sched`...)
 * [Where the batches are defined](https://crm.torproject.org/civicrm/admin/mail?reset=1)
 * The [Civimail](https://crm.torproject.org/civicrm/mailing?reset=1) interface should show the latest mailings (when
   clicking twice on "STARTED", from there click the Report button to
   see how many mails have been sent, bounced, etc

The Grafana dashboard is based on metrics from Prometheus, which can
be inspected live with the following command:

    curl -s localhost:3903/metrics | grep -v -e ^go_ -e '^#' -e '^mtail' -e ^process -e _tls_; postfix-queues-sizes

Using `lnav` can also be useful to monitor logs in real time, as it
provides per-queue ID navigation, marks warnings (deferred messages)
in yellow and errors (bounces) in red. 

A few commands to inspect the email queue:

 * list the queue, with more recent entries first

        postqueue -j | jq -C .recipients[] | tac

 * find how many emails in the queue, per domain:
 
        postqueue -j | jq -r .recipients[].address | sed 's/.*@//' | sort | uniq -c | sort -n

   Note that the `qshape deferred` command gives a similar (and
   actually better) output.

In case of a major problem, you can stop the mailing in CiviCRM and
put all emails on hold with:

    postsuper -h ALL

Then the `postfix-trickle` script can be used to slowly release
emails:

    postfix-trickle 10 5

When an email bounces, it should go to `civicrm@crm.torproject.org`,
which is an IMAP mailbox periodically checked by CiviCRM. It will
ingest bounces landing in that mailbox and disable them for the next
mailings. It's also how users can unsubscribe from those mailings, so
it is critical that this service runs correctly.

A lot of those notes come from the [issue where we enabled CiviCRM to
receive its bounces](https://gitlab.torproject.org/tpo/tpa/team/-/issues/33037).

## Handling abuse complains

Our postmaster alias can receive emails like this:

    Subject: Abuse Message [AbuseID:809C16:27]: AbuseFBL: UOL Abuse Report

Those emails usually contain enough information to figure out which
email address filed a complaint. The action to take is to remove them
from the mailing. Here's an example email sample:

    Received: by crm-int-01.torproject.org (Postfix, from userid 33)
            id 579C510392E; Thu, 4 Feb 2021 17:30:12 +0000 (UTC)
    [...]
    Message-Id: <20210204173012.579C510392E@crm-int-01.torproject.org>
    [...]
    List-Unsubscribe: <mailto:civicrm+u.2936.7009506.26d7b951968ebe4b@crm.torproject.org>
    job_id: 2936
    Precedence: bulk
    [...]
    X-CiviMail-Bounce: civicrm+b.2936.7009506.26d7b951968ebe4b@crm.torproject.org
    [...]

Your bounce might have only some of those. Possible courses of action
to find the victim's email:

 1. Grep for the queue ID (`579C510392E`) in the mail logs
 2. Grep for the Message-Id
    (`20210204173012.579C510392E@crm-int-01.torproject.org`) in mail
    logs (with `postfix-trace`)

Once you have the email address:

 1. head for the [CiviCRM search interface](https://crm.torproject.org/civicrm/contact/search?reset=1) to find that user
 2. remove the from the "Tor News" group, in the `Group` tab
 
You can also just send email to the `List-Unsubscribe` address or
click the "unsubscribe" links at the bottom of the email.

## Granting access to the CiviCRM backend

The main CiviCRM is protected by Apache-based authentication,
accessible only by TPA. To add a user, on the backend server
(currently `crm-int-01`):

    htdigest /etc/apache2/htdigest 'Tor CRM' $USERNAME

## Pager playbook

<!-- information about common errors from the monitoring system and -->
<!-- how to deal with them. this should be easy to follow: think of -->
<!-- your future self, in a stressful situation, tired and hungry. -->

## Disaster recovery

If Redis dies, we might lose in-process donations. But otherwise, it
is disposable and data should be recreated as needed.

If the entire database gets destroyed, it needs to be restored from
backups, by TPA.

# Reference

## Installation

Full documentation on the installation of this system is somewhat out
of scope for TPA: sysadmins only installed the servers and setup basic
services like a VPN (using [IPsec](howto/ipsec)) and an Apache, PHP, MySQL
stack.

The Puppet classes used on the two servers are
`roles::civicrm_int_2018` and `roles::civicrm_ext_2018`.

## SLA

This service is critical, as it is used to host donations, and should
be as highly available as possible. Unfortunately, its design has
multiple single point of failures, which, in practice, makes this
target difficult to fulfill at this point.

## Design

### Services

The CRM service is built with two distinct servers:

 * `crm-int-01.torproject.org`, AKA `crm-int-01`
   * software:
     * CiviCRM on top of Drupal
     * Drupal has a `tor_donation` module which has the code to
       receive/process Redis messages and initiate the corresponding
       actions in CiviCRM
     * Apache with PHP FPM
     * MariaDB (MySQL) database (Drupal storage backend)
     * Redis cache (?)
     * Dovecot IMAP server (to handle bounces)
   * sites:
     * `crm.torproject.org`: production CiviCRM site
     * `staging.crm.torproject.org`: staging site
     * `test.crm.torproject.org`: testing site
 * `crm-ext-01.torproject.org`, AKA `crm-ext-01`. Runs:
   * software:
     * Apache with PHP FPM
   * sites:
     * `donate-api.torproject.org`: production donation API middleware
     * `staging.donate-api.torproject.org`: staging API
     * `test.donate-api.torproject.org`: testing API
     * `api.donate.torproject.org`: not live yet
     * `staging-api.donate.torproject.org`: not live yet
     * `test-api.donate.torproject.org`: test site to rename the API
       middleware (see [issue 40123](https://gitlab.torproject.org/tpo/tpa/team/-/issues/40123))
     * those sites live in `/srv/donate.torproject.org`

There is also the <https://donate.torproject.org> static site hosted
in our [static hosting mirror network](howto/static-component). A donation campaign *must*
be setup both inside the static site and CiviCRM.

The monthly newsletter is configured on CiviCRM and also archived on
the <https://newsletter.torproject.org> static site.

### Authentication

The `crm-int-01` server doesn't talk to the outside internet and can
be accessed only via HTTP authentication.

Users that need to access the CRM must be added to both CiviCRM and on
the Apache on `crm-int-01.tpo`.

The <https://donate.torproject.org> website is built with Lektor like
all the other torproject.org [static websites](https://gitlab.torproject.org/tpo/web/). It doesn't talk to
CiviCRM directly. Instead it talks with with the donation API
middleware through Javascript, through a React component (available in
the [donate-static repository](https://gitlab.torproject.org/tpo/web/donate-static)). GR calls that middleware API
"slim".

In other words, the `donate-api` PHP app is the component that allows
communications between the `donate.torproject.org` site and
CiviCRM. The public has access to the `donate-api` app, but not the
backend CiviCRM server. The middle and the CiviCRM server talk to each
other through a Redis instance, accessible only through an [IPsec](howto/ipsec)
tunnel (as a 172.16/12 private IP address).

In order to receive contribution data and provide endpoints reachable
by Stripe/PayPal, the API server is configured to receive those
requests and pass specific messages using Redis over a secure tunnel
to the CRM server

Both servers have firewalled SSH servers (rules defined in Puppet,
`profile::civicrm`). To get access to the port, [ask TPA][File].

Once inside SSH, regular users must use `sudo` to access the
`tordonate` (on the external server) and `torcivicrm` (on the internal
server) accounts, e.g.

    crm-ext-01$ sudo -u tordonate git -C /srv/donate.torproject.org/htdocs-stag/ status

### Queues

CiviCRM can hold a large queue of emails to send, when a new
newsletter is generated. This, in turn, can turn in large Postfix
email queues when CiviCRM releases those mails in the email system.

TODO: It's unclear what other queues might exist in the system, Redis?

### Deployment

As stated above, a new donation campaign involves changes to both the
static website (`donate.tpo`) and the CiviCRM server.

Changes to the CiviCRM server and donation middleware can be deployed
progressively through the test/staging/production sites, which all
have their own databases.

TODO: clarify the GiantRabbit deployment workflow. They seem to have
one branch per environment, but what does that include? Does it matter
for us?

There's a `drush` script that edits the dev/stage databases to
replace PII in general, and in particular change the email of everyone
to dummy aliases so that emails sent by accident wouldn't end up in
real people's mail boxes.

## Issues

Since there are many components, here's a table outlining the known
projects and issue trackers for the different sites.

| Site                                | Project      | Issues      |
|-------------------------------------|--------------|-------------|
| <https://crm.torproject.org>        | [project][crm] | [issues][crm-issues] |
| <https://donate-api.torproject.org> | [project][donate-api] | [issues][donate-api-issues] |
| <https://donate.torproject.org>     | [project][donate] | [issues][donate-issues] |
| <https://newsletter.torproject.org> | [project][newsletter] | [issues][newsletter-issues] |

[crm-issues]: https://gitlab.torproject.org/tpo/web/civicrm/-/issues
[crm]: https://gitlab.torproject.org/tpo/web/civicrm/
[donate-api-issues]: https://gitlab.torproject.org/tpo/web/donate/-/issues
[donate-api]: https://gitlab.torproject.org/tpo/web/donate
[donate-issues]: https://gitlab.torproject.org/tpo/web/donate-static/-/issues
[donate]: https://gitlab.torproject.org/tpo/web/donate-static/
[newsletter-issues]: https://gitlab.torproject.org/tpo/web/newsletter/-/issues
[newsletter]: https://gitlab.torproject.org/tpo/web/newsletter

Issues with the server-level issues should be [filed][File] or
in the [TPA team issue tracker][search].

 [File]: https://gitlab.torproject.org/tpo/tpa/team/-/issues/new
 [search]: https://gitlab.torproject.org/tpo/tpa/team/-/issues

## Maintainer, users, and upstream

CiviCRM, the PHP application and the Javascript component on
`donate-static` are all maintained by the external CiviCRM
contractors.

The `donate.tpo` website is maintained by TPO (communication and
donations teams), except for the Javascript component. Any major
modification that involves also some Civi development is done by the
CiviCRM contractors.

## Monitoring and testing

As other TPA servers, the CRM servers are monitored by
[Nagios](howto/nagios). The Redis server (and the related IPsec tunnel) is
particularly monitored by Nagios, using a special `PING` check, to
make sure both ends can talk to each other.

Exceptions are logged and emailed by slim and the donation processor
(which deal with the redis backend). See the logging configuration
below.

## Logs and metrics

As other TPA servers, the CRM servers are monitored by [Prometheus](howto/prometheus)
with graphs rendered by [Grafana](howto/grafana). This includes an elaborate
[Postfix dashboard](https://grafana.torproject.org/d/Ds5BxBYGk/postfix-mtail?orgId=1&from=now-24h&to=now&var-node=eugeni.torproject.org&var-node=crm-int-01.torproject.org) watching to two mailservers.

The donate side (on `crm-ext-01.torproject.org`) uses the Monolog
framework for logging. Errors that take place on the production
environment are currently configured to send errors via email to to a
Giant Rabbit email address and the Tor Project email address
`donation-drivers@`.

The logging configuration is in:
`crm-ext-01:/srv/donate.torproject.org/htdocs-prod/src/dependencies.php`.

The CRM side (`crm-int-01.torproject.org`) has a similar configuration
and sends production environment errors via email.

The logging configuration is in:
`crm-int-01:/srv/crm.torproject.org/htdocs-prod/sites/all/modules/custom/tor_donation/src/Donation/ErrorHandler.php`.

## Backups

Backups are done with the regular [backup procedures](howto/backup) except for
the MariaDB/MySQL database, which are backed up in
`/var/backups/local/mysql/`. See also the [MySQL section in the backup
documentation](#mysql-backup-system).

## Other documentation

The folks at GiantRabbit probably have their own documentation.

# Discussion

This section is reserved for future large changes proposed to this
infrastructure. It can also be used to perform an audit on the current implementation.

## Overview

<!-- if this is an old project being documented, summarize the known -->
<!-- issues with the project. to quote the "audit procedure":

TODO:

 6. When was the last risk assessment done? Something that would cover
    risks from the data stored, the access required, etc.

 7. Are there any in-progress projects? Technical debt cleanup?
    Migrations? What state are they in? What's the urgency? What's the
    next steps?

 8. What urgent things need to be done on this project?

-->

The CiviCRM deployment is complex and feels a bit brittle. The
separation between the CiviCRM backend and the middleware API evolved
from an initial strict, two-server setup, into the current three-parts
component after the static site frontend was added around 2020. The
original two-server separation was performed out of a concern for
security: we were worried about exposing CiviCRM to the public,
because we felt the attack surface of both Drupal and CiviCRM was too
wide to be reasonably defended against a determined attacker.

The downside is, obviously, a lot of complexity, which also makes the
service more fragile. The Redis monitoring, for example, was added
after we discovered the `ipsec` tunnel would sometimes fail, which
would completely break donations.

Obviously, if either the donation middleware or CiviCRM fails,
donations go down as well, so we have actually two single point of
failures in that design.

A security review should probably be performed to make sure React,
Drupal, its modules, CiviCRM, and other dependencies, are all up to
date. Other components like Apache, Redis, or MariaDB are managed
through Debian package, and supported by the Debian security team, so
should be fairly up to date, in terms of security issues.

TODO: clarify which versions of CiviCRM, Drupal, Yarn, NVM, PHP,
Redis, and who knows what else are deployed, and whether it matters.

## Goals

<!-- include bugs to be fixed -->

### Must have

### Nice to have

### Non-Goals

## Approvals required

<!-- for example, legal, "vegas", accounting, current maintainer -->

## Proposed Solution

## Cost

## Alternatives considered

<!-- include benchmarks and procedure if relevant -->
