English
User, folders, database and settings
Step 1. The service user
Why. A program runs with the rights of its user. If the API ran as root and an attacker found a hole in it — in our code or in a library — they would own the whole machine. Linux answers with the principle of least privilege: every service gets its own user that owns nothing but the service's data. The API will run as chatex, a user that cannot log in and cannot write its own program files.
Do.
bash
useradd --system --home-dir /var/lib/chatex --shell /usr/sbin/nologin chatex--systemcreates a system account: a user id below 1000, no password ageing, and no home folder is created.--home-dir /var/lib/chatexrecords the data folder as the account's home. Some libraries look for a writable home folder; this one will be writable (Step 2).--shell /usr/sbin/nologin— nobody can log in aschatex, not even with a password or a key; the account exists only to run the service.
Check
bash
id chatexuid=993(chatex) gid=993(chatex) groups=993(chatex)The number may differ; a system user and its group of the same name were created.
Step 2. The folders
Why. The files of the application fall into three groups with different owners and lifetimes, and the folder layout follows the Linux conventions for them:
- program files under
/opt(add-on software): written only byrootat deployment, read by the service; - data under
/var/lib(state of programs): uploaded files and keys, written by the service, kept across deployments; - settings under
/etc: written by the administrator, read byroot.
Do.
bash
mkdir -p /opt/chatex/incoming /opt/chatex/releases /var/lib/chatex/uploads /etc/chatex && chown -R chatex:chatex /var/lib/chatexmkdir -p creates the folders with their parents and is silent if they already exist; chown -R gives the data folder to chatex. All other folders stay owned by root. After the first deployment of topic 24, the server holds this tree:
/opt/chatex/
├── incoming/<sha>/ upload from GitHub Actions (rsync)
├── releases/
│ ├── 3c6b219…/ an older release (the newest 5 are kept)
│ └── 03be410…/
│ ├── api/ published Chatex.Api.dll
│ ├── efbundle migration executable
│ ├── web/ Angular build
│ └── REVISION commit hash
└── current → releases/03be410… symlink, swapped atomically
/etc/chatex/chatex.env settings and secrets, mode 600
/var/lib/chatex/ uploads/ and keys/: the only writable folder
/usr/local/bin/chatex-activateFig. 23.2. Files of Chatex on the server
releases/holds complete versions of the application, each in a folder named after its Git commit.currentis not a folder but a symbolic link to one release. The service runscurrent/api, Nginx servescurrent/web; switching the whole application to another version means replacing one link (topic 24).incoming/receives uploads, so a half-copied release never appears inreleases/./var/lib/chatexsurvives every deployment: uploaded files inuploads/, the Data Protection keys inkeys/(created by the API on its first start).
Check
bash
ls -ld /opt/chatex/incoming /opt/chatex/releases /var/lib/chatex /var/lib/chatex/uploads /etc/chatexdrwxr-xr-x 2 root root 4096 Nov 15 21:25 /etc/chatex
drwxr-xr-x 2 root root 4096 Nov 15 21:25 /opt/chatex/incoming
drwxr-xr-x 2 root root 4096 Nov 15 21:25 /opt/chatex/releases
drwxr-xr-x 3 chatex chatex 4096 Nov 15 21:25 /var/lib/chatex
drwxr-xr-x 2 chatex chatex 4096 Nov 15 21:25 /var/lib/chatex/uploadsOnly the data folders belong to chatex.
Step 3. PostgreSQL
Why. The package has already created a database cluster and started it. On a developer machine we connected as the superuser postgres (topic 2); on a server the application gets its own role that owns its own database and nothing else. Even a successful SQL injection could then not read other databases, create roles or read files of the server.
Do. Choose a password of letters and digits (for example the output of openssl rand -hex 24) and use it instead of CHANGE_ME:
bash
sudo -u postgres psql -c "CREATE ROLE chatex LOGIN PASSWORD 'CHANGE_ME'" -c "CREATE DATABASE chatex OWNER chatex"sudo -u postgresrunspsqlas the operating-system userpostgres, which the package created. PostgreSQL trusts it as the database superuser through peer authentication over the local socket — no password exists for it, and none is needed.CREATE ROLE chatex LOGIN PASSWORD '…'— a role that may log in, with a password; it is not a superuser and cannot create databases or roles.CREATE DATABASE chatex OWNER chatex— the role owns its database, so the migrations of topic 24 can create tables in it.
The database is still empty; the migration bundle creates the schema during the first deployment.
Check
bash
sudo -u postgres psql -c "\l chatex" List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | Locale | ICU Rules | Access privileges
--------+--------+----------+-----------------+---------+---------+--------+-----------+-------------------
chatex | chatex | UTF8 | libc | C.UTF-8 | C.UTF-8 | | |
(1 row)The database exists and is owned by chatex.
Why the firewall need not block port 5432
PostgreSQL on Ubuntu listens only on localhost (listen_addresses in /etc/postgresql/18/main/postgresql.conf), so the port is not open to the internet in the first place. The firewall is a second line of defence: even if somebody changed that setting, port 5432 would stay blocked.
Step 4. The settings file
Why. The production settings — the connection string with the database password, the JWT signing key — are secrets. They must not be in the repository, where every collaborator, every fork and every leaked backup would see them. What the repository can and should contain is a template: which settings exist, what they mean, and safe placeholder values. The real file lives only on the server, readable only by root.
ASP.NET Core reads configuration from environment variables too, and systemd can load environment variables from a file. So the settings are a plain file of KEY=value lines; a double underscore stands for the : of a configuration section, so Jwt__SigningKey sets Jwt:SigningKey.
Do. On your computer, create the template in a new folder Deploy:
ini
# Production settings for the Chatex API, read by systemd (EnvironmentFile) and by chatex-activate.
# Install as /etc/chatex/chatex.env, owned root:root, mode 600. systemd syntax: KEY=value, no export,
# no quotes needed. '__' stands for ':' in configuration keys (Jwt__SigningKey = Jwt:SigningKey).
ConnectionStrings__Chatex=Host=localhost;Database=chatex;Username=chatex;Password=CHANGE_ME
Jwt__Issuer=https://chatex.mvano.com
Jwt__Audience=https://chatex.mvano.com
# At least 32 characters, for example: openssl rand -base64 48
Jwt__SigningKey=CHANGE_ME
Storage__RootPath=/var/lib/chatex/uploads
# Keeps the Data Protection keys across restarts; the API creates the folder (/var/lib/chatex is writable for it).
DataProtection__KeysPath=/var/lib/chatex/keys
# Requests for any other Host header are rejected with 400; 127.0.0.1 is for the health check in chatex-activate.
AllowedHosts=chatex.mvano.com;127.0.0.1
# Optional (defaults shown):
# Jwt__AccessTokenLifetime=00:15:00
# Jwt__RefreshTokenLifetime=30.00:00:00
# Attachments__MaxBytes=20971520
# Presence__OfflineGraceSeconds=5
# Maintenance__Interval=01:00:00
# Maintenance__StaleUploadAge=1.00:00:00
# RateLimiting__AuthPermitLimit=20
# RateLimiting__AuthWindowSeconds=60ConnectionStrings__Chatex— the connection string ofAddData(topic 5): the local database, the rolechatexand its password.Jwt__Issuer,Jwt__Audience— the public address of the site, written into every access token and checked on every request (topics 8 and 13).Jwt__SigningKey— the HMAC key, at least 32 characters ([MinLength(32)]ofJwtOptionsstops the API at start-up otherwise).openssl rand -base64 48produces 64 random characters.Storage__RootPath— the folder for uploaded files (topic 5).DataProtection__KeysPath— where ASP.NET Core keeps its Data Protection keys (topic 13). Without it the keys would live only in memory and change on every restart.AllowedHosts— the host filter of ASP.NET Core: a request whoseHostheader is not in the list is answered with400 Bad Request. The domain is for the requests that come through Nginx;127.0.0.1is for the health check of the activation script in topic 24, which calls the API directly.- The optional settings at the end show the defaults of the options classes; uncomment a line to change one, for example
Attachments__MaxBytes.
Commit the template and push it:
powershell
git add Deploypowershell
git commit -m "Add the production settings template"powershell
git pushOn the server, fetch it and install it as the real settings file, readable only by root:
bash
git pullbash
cp Deploy/chatex.env.example /etc/chatex/chatex.env && chmod 600 /etc/chatex/chatex.env && nano /etc/chatex/chatex.envIn the editor nano, change four things, then save with Ctrl+O, Enter and leave with Ctrl+X:
Password=CHANGE_ME→ the database password of Step 3;https://chatex.mvano.cominJwt__IssuerandJwt__Audience→https://<your domain>;Jwt__SigningKey=CHANGE_ME→ a new random key. Generate it in a second SSH window withopenssl rand -base64 48and paste it;chatex.mvano.cominAllowedHosts→<your domain>; keep;127.0.0.1at the end.
Check
bash
ls -l /etc/chatex/chatex.envThe line starts with -rw------- 1 root root: only root can read the file. systemd reads it as root before it starts the service as chatex, so the API receives the values without being able to read the file itself. Make sure no placeholder is left:
bash
grep -c CHANGE_ME /etc/chatex/chatex.envThe answer is 0.
Never commit the real file
The .gitignore of topic 2 ignores *.env and .env.*, and the template is called chatex.env.example precisely so that it is not ignored. Never copy real values back into the template, and never paste the signing key or the database password into an issue, a chat or a screenshot. If a secret leaks, replace it (topic 24 shows how).