fix: full verification against the brief — 137 confirmed findings fixed over six passes #4
No files matched your search
@@ -1,5 +1,6 @@
|
||||
TITANO_ADMIN_PASSWORD=change-me-at-first-login
|
||||
TITANO_DB_PASSWORD=choose-a-long-random-password
|
||||
# Folder of your archive, owned by PUID:PGID (an empty or root-owned folder is given to them at the first start)
|
||||
TITANO_ARCHIVE=/mnt/user/Timelapse
|
||||
TITANO_DATA=./data
|
||||
TITANO_PGDATA=./pgdata
|
||||
|
||||
@@ -21,6 +21,8 @@ LABEL org.opencontainers.image.title="Titano Server" \
|
||||
org.opencontainers.image.description="Time-lapse archive, uploads, jobs and rendering server" \
|
||||
org.opencontainers.image.version="$TITANO_VERSION" \
|
||||
org.opencontainers.image.licenses="LicenseRef-Titano-EULA"
|
||||
# ASPNETCORE_HTTP_PORTS is emptied: the server binds its own ports, and the base image's 8080 only made Kestrel warn
|
||||
# "Overriding address(es)" at every start.
|
||||
ENV TITANO_ARCHIVE_PATH=/archive \
|
||||
TITANO_DATA_PATH=/data \
|
||||
TITANO_HTTP_PORT=8080 \
|
||||
@@ -28,6 +30,7 @@ ENV TITANO_ARCHIVE_PATH=/archive \
|
||||
TITANO_DB=postgres \
|
||||
PUID=1000 \
|
||||
PGID=1000 \
|
||||
ASPNETCORE_HTTP_PORTS= \
|
||||
DOTNET_gcServer=1 \
|
||||
DOTNET_GCHeapAffinitizeMask= \
|
||||
DOTNET_NOLOGO=1
|
||||
|
||||
@@ -8,6 +8,10 @@ services:
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
# Publishing a port as another host port ("18443:8443")? Set TITANO_PUBLIC_HTTPS_PORT (and _HTTP_PORT) below to the
|
||||
# host port. LAN discovery reaches clients only with "network_mode: host"; on this bridge network clients add the
|
||||
# server by its address. With host networking drop "ports", give the postgres service
|
||||
# ports: ["127.0.0.1:5432:5432"] and set TITANO_DB_HOST to 127.0.0.1: the name "postgres" no longer resolves there.
|
||||
ports:
|
||||
- "8080:8080"
|
||||
- "8443:8443"
|
||||
@@ -20,7 +24,11 @@ services:
|
||||
TITANO_DB_NAME: titano
|
||||
TITANO_DB_USER: titano
|
||||
TITANO_DB_PASSWORD: ${TITANO_DB_PASSWORD:?set TITANO_DB_PASSWORD in .env}
|
||||
# auto (self-signed), pem or proxy; behind a proxy, set TITANO_TRUSTED_PROXIES to its address or network (for a
|
||||
# proxy container on this network, the network's subnet; only loopback is trusted otherwise)
|
||||
TITANO_TLS_MODE: auto
|
||||
# TITANO_TRUSTED_PROXIES: "172.18.0.0/16"
|
||||
# TITANO_PUBLIC_HTTPS_PORT: "8443"
|
||||
TITANO_SERVER_NAME: Titano Server
|
||||
# Trace, Debug, Information, Warning or Error
|
||||
TITANO_LOG_LEVEL: Information
|
||||
@@ -28,6 +36,8 @@ services:
|
||||
PGID: ${PGID:-1000}
|
||||
TZ: ${TZ:-UTC}
|
||||
volumes:
|
||||
# The archive folder should belong to PUID:PGID; an empty or root-owned one is given to them at start (the folder
|
||||
# only, never its contents).
|
||||
- ${TITANO_ARCHIVE:-./archive}:/archive
|
||||
- ${TITANO_DATA:-./data}:/data
|
||||
|
||||
|
||||
@@ -1,18 +1,48 @@
|
||||
#!/bin/sh
|
||||
# Runs Titano Server as PUID:PGID (Unraid/NAS convention). /data is owned by that user; /archive is left as
|
||||
# mounted (it may hold terabytes) and only checked for write access.
|
||||
# Runs Titano Server as PUID:PGID (Unraid/NAS convention). The data folder is owned by that user. The archive is left
|
||||
# as mounted (it may hold terabytes) and only checked for write access; only when that user cannot write it and the
|
||||
# folder is empty or owned by root (Docker creates a missing bind source or a fresh volume that way) is the folder
|
||||
# itself, never its contents, given to PUID:PGID.
|
||||
set -eu
|
||||
|
||||
PUID="${PUID:-1000}"
|
||||
PGID="${PGID:-1000}"
|
||||
DATA="${TITANO_DATA_PATH:-/data}"
|
||||
ARCHIVE="${TITANO_ARCHIVE_PATH:-/archive}"
|
||||
umask 002
|
||||
|
||||
# Help and the health probe touch neither folder.
|
||||
case "${1:-}" in
|
||||
--help | -h | -\? | /\? | --healthcheck) exec dotnet /app/Titano.Server.dll "$@" ;;
|
||||
esac
|
||||
|
||||
as_user() {
|
||||
setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- "$@"
|
||||
}
|
||||
|
||||
if [ "$(id -u)" = "0" ]; then
|
||||
mkdir -p /data
|
||||
chown -R "$PUID:$PGID" /data
|
||||
if ! setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- test -w "${TITANO_ARCHIVE_PATH:-/archive}"; then
|
||||
echo "warning: ${TITANO_ARCHIVE_PATH:-/archive} is not writable by $PUID:$PGID" >&2
|
||||
mkdir -p "$DATA" "$ARCHIVE"
|
||||
chown -R "$PUID:$PGID" "$DATA"
|
||||
if ! as_user test -w "$ARCHIVE"; then
|
||||
if [ -z "$(ls -A "$ARCHIVE")" ] || [ "$(stat -c %u "$ARCHIVE")" = "0" ]; then
|
||||
owner="$(stat -c %u:%g "$ARCHIVE")"
|
||||
if chown "$PUID:$PGID" "$ARCHIVE" 2>/dev/null; then
|
||||
echo "titano: $ARCHIVE belonged to $owner; it now belongs to $PUID:$PGID (the folder only, not its contents)"
|
||||
fi
|
||||
fi
|
||||
if ! as_user test -w "$ARCHIVE"; then
|
||||
echo "error: $ARCHIVE is not writable by $PUID:$PGID; give that user write access to the archive folder on the host, or set PUID and PGID to its owner" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
# The server writes into the archive's .titano folders at once (staging, trash, locks); one left to root by an
|
||||
# earlier run as root, or copied in by root, would stop it in a restart loop. Reported, never chowned.
|
||||
for dir in "$ARCHIVE/.titano" "$ARCHIVE/.titano"/*/; do
|
||||
if [ -d "$dir" ] && ! as_user test -w "$dir"; then
|
||||
echo "error: ${dir%/} is not writable by $PUID:$PGID; give that user write access to it on the host (for example chown -R $PUID:$PGID <archive>/.titano)" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Titano.Server.dll "$@"
|
||||
fi
|
||||
|
||||
|
||||
@@ -64,6 +64,10 @@ curl -L -o .env https://raw.githubusercontent.com/alby96/titano-releases/main/do
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Create the archive folder owned by `PUID:PGID` first (for example `mkdir -p <folder> && chown 1000:1000 <folder>`). An
|
||||
empty folder, or one owned by root (as Docker creates a missing one), is given to `PUID:PGID` at start: the folder
|
||||
itself, never its contents. Any other folder that user cannot write stops the container with a one-line error.
|
||||
|
||||
Open `http://<host>:8080/admin`, sign in as `admin` with the password from `.env` and choose a new one. Titano
|
||||
clients connect to `https://<host>:8443`; the first connection shows the server's certificate fingerprint, which the
|
||||
admin panel shows under Settings so you can compare them.
|
||||
@@ -75,6 +79,19 @@ admin panel shows under Settings so you can compare them.
|
||||
- Upgrade: `docker compose pull && docker compose up -d`. Jobs in progress resume from their last checkpoint.
|
||||
- All settings: environment variables `TITANO_*` (see `docker-compose.yml`) or `/data/server.json`. Run
|
||||
`docker run --rm ghcr.io/alby96/titano-server:latest --help` for the list.
|
||||
- Other host ports: when you publish the container's ports as other host ports (`18443:8443`), set
|
||||
`TITANO_PUBLIC_HTTPS_PORT` (and `TITANO_PUBLIC_HTTP_PORT`) to the host ports, so the admin panel's redirect to HTTPS
|
||||
and LAN discovery name the ports clients can reach.
|
||||
- LAN discovery (`TITANO_DISCOVERY`, on by default) needs host networking (`network_mode: host` in compose, Network
|
||||
type *Host* on Unraid): on a bridge network its broadcasts never leave the container's network. Without it, add the
|
||||
server in Titano by its address. With `network_mode: host` the name `postgres` no longer resolves: remove the
|
||||
`ports` of the `titano` service, publish PostgreSQL on loopback (`ports: ["127.0.0.1:5432:5432"]` under `postgres`)
|
||||
and set `TITANO_DB_HOST: 127.0.0.1`.
|
||||
- Behind a reverse proxy (`TITANO_TLS_MODE=proxy`), only the proxies listed in `TITANO_TRUSTED_PROXIES` may set
|
||||
`X-Forwarded-*` headers. By default that is loopback only: other machines on your network reach the HTTP port
|
||||
directly, so they must not choose the address the sign-in limit and the audit log see. List your proxy's address,
|
||||
or the subnet of the Docker network it shares with Titano (for example `172.18.0.0/16`). The admin panel shows *Not
|
||||
via proxy* when a page did not come through a trusted proxy over HTTPS.
|
||||
|
||||
## Titano Server on Unraid
|
||||
|
||||
@@ -82,18 +99,28 @@ admin panel shows under Settings so you can compare them.
|
||||
role `titano` (for example with `docker exec -it postgresql17 psql -U postgres -c "CREATE ROLE titano LOGIN
|
||||
PASSWORD '…'" -c "CREATE DATABASE titano OWNER titano"`).
|
||||
2. In Docker › *Template repositories* add `https://github.com/alby96/titano-releases` and save.
|
||||
3. Docker › *Add container* › Template `titano-server`. Set the admin password, the database host (the PostgreSQL
|
||||
container's name or IP), password and the archive share (default `/mnt/user/Timelapse`).
|
||||
3. Docker › *Add container* › Template `titano-server`. Set the admin password, the database host, password and the
|
||||
archive share (default `/mnt/user/Timelapse`). The database host is the Unraid server's IP address (the PostgreSQL
|
||||
template publishes port 5432): container names resolve only when both containers are on the same custom Docker
|
||||
network, not on the default *bridge*. If you change the HTTPS port, enter the same port in *Public HTTPS port*.
|
||||
4. Open the WebUI (`http://[IP]:8080/admin`).
|
||||
|
||||
The template file is [`unraid/titano.xml`](unraid/titano.xml).
|
||||
|
||||
## Titano Server on Windows
|
||||
|
||||
Unpack `Titano-Server-win-x64-<version>.zip` (or choose the *Server* component in the setup). It uses SQLite in
|
||||
Choose the *Server* component in the setup, or unpack `Titano-Server-win-x64-<version>.zip`. It uses SQLite in
|
||||
`C:\ProgramData\Titano Server` by default, or PostgreSQL with `TITANO_DB=postgres` and the `TITANO_DB_*` variables.
|
||||
The data folder is readable only by the server's account, SYSTEM and Administrators; without `TITANO_ADMIN_PASSWORD`
|
||||
the first start writes a temporary admin password to `initial-admin-password.txt` there (open it from an
|
||||
administrator prompt). Everything in it must belong to those accounts and nothing in it may be a link: otherwise the
|
||||
server does not start and names the file to check. A new archive folder (default `C:\TitanoArchive`) can be changed
|
||||
only by those accounts and read by other users; when other users can change an existing archive, the log says so.
|
||||
|
||||
Run `Titano.Server.exe` in a console, or install it as a Windows service from an administrator prompt with
|
||||
`Titano.Server.exe --install-service` (remove it with `--uninstall-service`).
|
||||
`Titano.Server.exe --install-service` (remove it with `--uninstall-service`). The service runs as LocalSystem, so it
|
||||
registers only from a copy inside `Program Files` that only administrators can change: install for *All users*, or
|
||||
unpack the zip into a folder under `Program Files`.
|
||||
|
||||
## Translations
|
||||
|
||||
|
||||
@@ -22,21 +22,23 @@
|
||||
<DonateLink/>
|
||||
<Requires>A PostgreSQL 16 or 17 container (official "postgres" template) with a database and user for Titano.</Requires>
|
||||
<Config Name="HTTP port" Target="8080" Default="8080" Mode="tcp" Description="Admin panel and API over HTTP." Type="Port" Display="always" Required="true" Mask="false">8080</Config>
|
||||
<Config Name="HTTPS port" Target="8443" Default="8443" Mode="tcp" Description="API over TLS for Titano clients." Type="Port" Display="always" Required="true" Mask="false">8443</Config>
|
||||
<Config Name="HTTPS port" Target="8443" Default="8443" Mode="tcp" Description="API over TLS for Titano clients. When you change it, enter the same port in Public HTTPS port." Type="Port" Display="always" Required="true" Mask="false">8443</Config>
|
||||
<Config Name="Public HTTPS port" Target="TITANO_PUBLIC_HTTPS_PORT" Default="" Mode="" Description="The HTTPS port above, when it is not 8443; the admin panel redirects there." Type="Variable" Display="always" Required="false" Mask="false"/>
|
||||
<Config Name="Archive" Target="/archive" Default="/mnt/user/Timelapse" Mode="rw" Description="Originals, sidecars, proxies and renders." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/Timelapse</Config>
|
||||
<Config Name="App data" Target="/data" Default="/mnt/user/appdata/titano" Mode="rw" Description="Settings, TLS certificate, uploads in progress and logs." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/titano</Config>
|
||||
<Config Name="Admin user" Target="TITANO_ADMIN_USER" Default="admin" Mode="" Description="Created at first start when no administrator exists." Type="Variable" Display="always" Required="true" Mask="false">admin</Config>
|
||||
<Config Name="Admin password" Target="TITANO_ADMIN_PASSWORD" Default="" Mode="" Description="Initial password; a change is required at first sign-in." Type="Variable" Display="always" Required="true" Mask="true"/>
|
||||
<Config Name="Database host" Target="TITANO_DB_HOST" Default="postgresql17" Mode="" Description="Host name or IP of the PostgreSQL container." Type="Variable" Display="always" Required="true" Mask="false">postgresql17</Config>
|
||||
<Config Name="Database host" Target="TITANO_DB_HOST" Default="" Mode="" Description="IP address of the Unraid server (PostgreSQL's port mapped), or the PostgreSQL container's name when both containers are on the same custom network; names do not resolve on bridge." Type="Variable" Display="always" Required="true" Mask="false"/>
|
||||
<Config Name="Database port" Target="TITANO_DB_PORT" Default="5432" Mode="" Description="PostgreSQL port." Type="Variable" Display="advanced" Required="true" Mask="false">5432</Config>
|
||||
<Config Name="Database name" Target="TITANO_DB_NAME" Default="titano" Mode="" Description="Database owned by the Titano user." Type="Variable" Display="always" Required="true" Mask="false">titano</Config>
|
||||
<Config Name="Database user" Target="TITANO_DB_USER" Default="titano" Mode="" Description="PostgreSQL role." Type="Variable" Display="always" Required="true" Mask="false">titano</Config>
|
||||
<Config Name="Database password" Target="TITANO_DB_PASSWORD" Default="" Mode="" Description="PostgreSQL password." Type="Variable" Display="always" Required="true" Mask="true"/>
|
||||
<Config Name="Database TLS" Target="TITANO_DB_SSLMODE" Default="prefer" Mode="" Description="disable, prefer, require or verify-full." Type="Variable" Display="advanced" Required="false" Mask="false">prefer</Config>
|
||||
<Config Name="TLS mode" Target="TITANO_TLS_MODE" Default="auto" Mode="" Description="auto (self-signed), pem (own certificate) or proxy (behind a reverse proxy)." Type="Variable" Display="advanced" Required="false" Mask="false">auto</Config>
|
||||
<Config Name="Trusted proxies" Target="TITANO_TRUSTED_PROXIES" Default="" Mode="" Description="TLS mode proxy: IP address or network of your reverse proxy (for example 172.17.0.0/16); only loopback is trusted otherwise." Type="Variable" Display="advanced" Required="false" Mask="false"/>
|
||||
<Config Name="Server name" Target="TITANO_SERVER_NAME" Default="Titano Server" Mode="" Description="Name shown to clients." Type="Variable" Display="advanced" Required="false" Mask="false">Titano Server</Config>
|
||||
<Config Name="Log level" Target="TITANO_LOG_LEVEL" Default="Information" Mode="" Description="Trace, Debug, Information, Warning or Error." Type="Variable" Display="advanced" Required="false" Mask="false">Information</Config>
|
||||
<Config Name="PUID" Target="PUID" Default="99" Mode="" Description="User id that owns files." Type="Variable" Display="advanced" Required="true" Mask="false">99</Config>
|
||||
<Config Name="PGID" Target="PGID" Default="100" Mode="" Description="Group id that owns files." Type="Variable" Display="advanced" Required="true" Mask="false">100</Config>
|
||||
<Config Name="Time zone" Target="TZ" Default="Europe/Rome" Mode="" Description="Time zone of logs and schedules." Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
|
||||
<Config Name="Time zone" Target="TZ" Default="Europe/Rome" Mode="" Description="Local time used to name folders of photos without a capture time; logs stay in UTC." Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
|
||||
</Container>
|
||||
@@ -288,6 +288,8 @@
|
||||
<data name="Admin.Settings.Network" xml:space="preserve"><value>Network and TLS</value></data>
|
||||
<data name="Admin.Settings.PemMissing" xml:space="preserve"><value>The PEM file was not found; enter its full path on the server.</value><comment>long</comment></data>
|
||||
<data name="Admin.Settings.PemOnly.Tip" xml:space="preserve"><value>Used only in Own certificate mode</value></data>
|
||||
<data name="Admin.Settings.ProxyBypassed" xml:space="preserve"><value>Not via proxy</value></data>
|
||||
<data name="Admin.Settings.ProxyBypassed.Tip" xml:space="preserve"><value>TLS mode is Reverse proxy, but this page did not come through a trusted proxy over HTTPS. Open it through your proxy, or add the proxy's address to TITANO_TRUSTED_PROXIES.</value></data>
|
||||
<data name="Admin.Settings.Restart" xml:space="preserve"><value>Restart required</value></data>
|
||||
<data name="Admin.Settings.Restart.Tip" xml:space="preserve"><value>Saved ports, TLS, workers, chunk size or job history apply after a restart</value></data>
|
||||
<data name="Admin.Settings.Server" xml:space="preserve"><value>Server</value></data>
|
||||
|
||||
@@ -69,6 +69,7 @@
|
||||
<data name="Server.Error.NotFound" xml:space="preserve"><value>Not found.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NotTitano" xml:space="preserve"><value>That address is not a Titano Server.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Change your password first.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProxyUntrusted" xml:space="preserve"><value>This page did not come through a trusted proxy over HTTPS. Open it through your proxy, or add the proxy's address to TITANO_TRUSTED_PROXIES.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.QuotaExceeded" xml:space="preserve"><value>This upload would exceed your quota.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.RateLimited" xml:space="preserve"><value>Too many attempts; wait a minute and try again.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.SamePassword" xml:space="preserve"><value>Choose a password different from the current one.</value><comment>long</comment></data>
|
||||
@@ -110,6 +111,8 @@
|
||||
<data name="Server.Role.Uploader" xml:space="preserve"><value>Uploader</value></data>
|
||||
<data name="Server.Role.Viewer" xml:space="preserve"><value>Viewer</value></data>
|
||||
<data name="Server.Service.Description" xml:space="preserve"><value>Titano time-lapse archive, uploads, jobs and rendering server.</value><comment>long</comment></data>
|
||||
<data name="Server.Service.NotProgramFiles" xml:space="preserve"><value>Titano Server is not in Program Files ({0}), so it cannot run as a service; install it for all users and register the service from there.</value><comment>long</comment></data>
|
||||
<data name="Server.Service.Writable" xml:space="preserve"><value>Users who are not administrators can change {0}, so Titano Server cannot run as a service from there; reinstall it for all users and register the service again.</value><comment>long</comment></data>
|
||||
<data name="Server.Setting.Aspect" xml:space="preserve"><value>Aspect</value></data>
|
||||
<data name="Server.Setting.Auto" xml:space="preserve"><value>auto</value></data>
|
||||
<data name="Server.Setting.Batch" xml:space="preserve"><value>Batch list</value></data>
|
||||
|
||||
@@ -288,6 +288,8 @@
|
||||
<data name="Admin.Settings.Network" xml:space="preserve"><value>Rete e TLS</value></data>
|
||||
<data name="Admin.Settings.PemMissing" xml:space="preserve"><value>File PEM non trovato; inserisci il percorso completo sul server.</value></data>
|
||||
<data name="Admin.Settings.PemOnly.Tip" xml:space="preserve"><value>Usato solo in modalità Certificato proprio</value></data>
|
||||
<data name="Admin.Settings.ProxyBypassed" xml:space="preserve"><value>Senza proxy</value></data>
|
||||
<data name="Admin.Settings.ProxyBypassed.Tip" xml:space="preserve"><value>La modalità TLS è Reverse proxy, ma questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a TITANO_TRUSTED_PROXIES.</value></data>
|
||||
<data name="Admin.Settings.Restart" xml:space="preserve"><value>Riavvio richiesto</value></data>
|
||||
<data name="Admin.Settings.Restart.Tip" xml:space="preserve"><value>Porte, TLS, worker, dimensione blocchi o cronologia job salvati valgono dopo un riavvio</value></data>
|
||||
<data name="Admin.Settings.Server" xml:space="preserve"><value>Server</value></data>
|
||||
|
||||
@@ -67,6 +67,7 @@
|
||||
<data name="Server.Error.NotFound" xml:space="preserve"><value>Non trovato.</value></data>
|
||||
<data name="Server.Error.NotTitano" xml:space="preserve"><value>Questo indirizzo non è un Titano Server.</value></data>
|
||||
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Cambia prima la password.</value></data>
|
||||
<data name="Server.Error.ProxyUntrusted" xml:space="preserve"><value>Questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a TITANO_TRUSTED_PROXIES.</value></data>
|
||||
<data name="Server.Error.QuotaExceeded" xml:space="preserve"><value>Questo caricamento supererebbe la tua quota.</value></data>
|
||||
<data name="Server.Error.RateLimited" xml:space="preserve"><value>Troppi tentativi; attendi un minuto e riprova.</value></data>
|
||||
<data name="Server.Error.SamePassword" xml:space="preserve"><value>Scegli una password diversa da quella attuale.</value></data>
|
||||
@@ -108,6 +109,8 @@
|
||||
<data name="Server.Role.Uploader" xml:space="preserve"><value>Caricatore</value></data>
|
||||
<data name="Server.Role.Viewer" xml:space="preserve"><value>Visualizzatore</value></data>
|
||||
<data name="Server.Service.Description" xml:space="preserve"><value>Server Titano per archivio time-lapse, caricamenti, job e rendering.</value></data>
|
||||
<data name="Server.Service.NotProgramFiles" xml:space="preserve"><value>Titano Server non è in Programmi ({0}), quindi non può funzionare come servizio; installalo per tutti gli utenti e registra il servizio da lì.</value></data>
|
||||
<data name="Server.Service.Writable" xml:space="preserve"><value>Anche utenti non amministratori possono modificare {0}, quindi Titano Server non può funzionare come servizio da lì; reinstallalo per tutti gli utenti e registra di nuovo il servizio.</value></data>
|
||||
<data name="Server.Setting.Aspect" xml:space="preserve"><value>Proporzioni</value></data>
|
||||
<data name="Server.Setting.Auto" xml:space="preserve"><value>auto</value></data>
|
||||
<data name="Server.Setting.Batch" xml:space="preserve"><value>Elenco batch</value></data>
|
||||
|
||||
@@ -3,7 +3,8 @@ namespace Titano.Protocol;
|
||||
/// <summary>
|
||||
/// <c>GET/PUT /api/v1/server/settings</c> (admin): the editable part of the server configuration. Settings named in
|
||||
/// <see cref="Locked"/> come from environment variables and cannot be changed here; <see cref="RestartRequired"/> says
|
||||
/// that saved values (ports, TLS, workers, chunk size) wait for a restart.
|
||||
/// that saved values (ports, TLS, workers, chunk size) wait for a restart. <see cref="ProxyWarning"/> is set in
|
||||
/// responses when TLS mode is proxy and the request did not come through a trusted proxy over HTTPS (ignored when saving).
|
||||
/// </summary>
|
||||
public sealed record ServerSettingsDto(
|
||||
string ServerName,
|
||||
@@ -21,7 +22,8 @@ public sealed record ServerSettingsDto(
|
||||
int TokenLifetimeDays,
|
||||
int UploadRetentionHours,
|
||||
IReadOnlyList<string> Locked,
|
||||
bool RestartRequired);
|
||||
bool RestartRequired,
|
||||
bool ProxyWarning);
|
||||
|
||||
/// <summary>A server log file (<c>GET /api/v1/logs/files</c>).</summary>
|
||||
public sealed record LogFileDto(string Name, long Size, DateTimeOffset Modified);
|
||||
@@ -35,7 +37,10 @@ public sealed record JobCountsDto(int Queued, int Running, int Paused, int DoneT
|
||||
/// <summary>Frames committed by uploads on one UTC day.</summary>
|
||||
public sealed record UploadDayDto(DateOnly Day, long Frames, long Bytes);
|
||||
|
||||
/// <summary><c>GET /api/v1/server/dashboard</c> (admin): everything the dashboard page shows in one call (BRIEF §14.8).</summary>
|
||||
/// <summary>
|
||||
/// <c>GET /api/v1/server/dashboard</c> (admin): everything the dashboard page shows in one call (BRIEF §14.8).
|
||||
/// <see cref="ProxyWarning"/>: TLS mode is proxy and this request did not come through a trusted proxy over HTTPS.
|
||||
/// </summary>
|
||||
public sealed record DashboardDto(
|
||||
string ServerName,
|
||||
string Version,
|
||||
@@ -50,4 +55,5 @@ public sealed record DashboardDto(
|
||||
IReadOnlyList<RenderNodeDto> Nodes,
|
||||
IReadOnlyList<UploadDayDto> Uploads,
|
||||
IReadOnlyList<AuditEntryDto> Activity,
|
||||
IReadOnlyList<JobDto> ActiveJobs);
|
||||
IReadOnlyList<JobDto> ActiveJobs,
|
||||
bool ProxyWarning);
|
||||
@@ -1,12 +1,12 @@
|
||||
// Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs.
|
||||
import { t, plural, applyStrings, culture } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns } from "../ui.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js";
|
||||
import { activityText } from "../audit.js";
|
||||
|
||||
const SCAN_BUTTON = `<button class="btn small" data-scan data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`;
|
||||
|
||||
export async function render(root, { api, setMeta, onEvent }) {
|
||||
export async function render(root, { api, setMeta, actions, onEvent }) {
|
||||
let timer = null;
|
||||
const refresh = () => {
|
||||
clearTimeout(timer);
|
||||
@@ -28,6 +28,8 @@ export async function render(root, { api, setMeta, onEvent }) {
|
||||
const tls = `Admin.Settings.Tls.${d.tlsMode.charAt(0).toUpperCase()}${d.tlsMode.slice(1)}`;
|
||||
setMeta(t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, t(tls),
|
||||
t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")));
|
||||
actions.innerHTML = d.proxyWarning ? PROXY_WARNING : "";
|
||||
applyStrings(actions);
|
||||
const a = d.archive;
|
||||
const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0;
|
||||
const online = d.nodes.filter((n) => n.state !== "offline");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, limits, language, retention. Values fixed by environment
|
||||
// variables are read-only here; ports, TLS, workers, chunk size and job history apply at the next restart.
|
||||
import { t, applyStrings, languages } from "../i18n.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts, PROXY_WARNING } from "../ui.js";
|
||||
|
||||
/** Setting → environment variable that can fix it (BRIEF §14.9). */
|
||||
const VARIABLES = {
|
||||
@@ -46,7 +46,8 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="network-title">
|
||||
<h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
|
||||
<div class="panel-head"><h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
|
||||
${settings.proxyWarning ? PROXY_WARNING : ""}</div>
|
||||
${number("httpPort", settings.httpPort, 'min="1" max="65535"')}
|
||||
${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')}
|
||||
${field("tlsMode", `<select class="input" name="tlsMode" ${lock("tlsMode")}>${["auto", "pem", "proxy"].map((m) =>
|
||||
|
||||
@@ -97,6 +97,9 @@ export function fitColumns(table) {
|
||||
|
||||
window.addEventListener("resize", () => document.querySelectorAll(".table[data-levels]").forEach(fitColumns));
|
||||
|
||||
/** Chip of the Dashboard and Settings: TLS mode is proxy, but this page did not come through a trusted proxy over HTTPS (BRIEF §14.2). */
|
||||
export const PROXY_WARNING = `<span class="chip warn" data-i18n="Admin.Settings.ProxyBypassed" data-i18n-title="Admin.Settings.ProxyBypassed.Tip"></span>`;
|
||||
|
||||
/** An empty state: one sentence and one button (BRIEF §0.2). */
|
||||
export function emptyState(sentenceKey, button = "") {
|
||||
return `<div class="empty"><span data-i18n="${attr(sentenceKey)}"></span>${button}</div>`;
|
||||
|
||||
@@ -3,6 +3,7 @@ using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
@@ -18,7 +19,8 @@ public static class AdminEndpoints
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers);
|
||||
api.MapGet("/server/settings", (ServerSettingsStore store) => Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto))
|
||||
api.MapGet("/server/settings", (HttpContext context, ServerSettingsStore store, ServerOptions options) =>
|
||||
Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto))
|
||||
.Requires(Permissions.ManageArchive);
|
||||
api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive);
|
||||
api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive);
|
||||
@@ -65,11 +67,13 @@ public static class AdminEndpoints
|
||||
[.. nodes.Select(n => Dto.Node(n, names.GetValueOrDefault(n.UserId, string.Empty)))],
|
||||
[.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))],
|
||||
[.. activity.Items.Select(Dto.Audit)],
|
||||
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)]),
|
||||
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)],
|
||||
AdminPanel.BypassesProxy(context, options)),
|
||||
ProtocolJson.Default.DashboardDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, AuditLog audit)
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, ServerOptions options,
|
||||
AuditLog audit)
|
||||
{
|
||||
switch (store.Save(request))
|
||||
{
|
||||
@@ -79,7 +83,7 @@ public static class AdminEndpoints
|
||||
return ApiErrors.BadRequest(context, code, setting, setting);
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
|
||||
return Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto);
|
||||
return Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
/// <summary>The audit log, newest first; <c>action</c> may list several actions separated by commas (<c>login,login_failed</c>).</summary>
|
||||
|
||||
@@ -18,8 +18,18 @@ public static class AuthEndpoints
|
||||
api.MapGet("/auth/me", (Caller caller) => Results.Json(Dto.User(caller.User), ProtocolJson.Default.UserDto)).AllowDuringPasswordChange();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why the <c>Secure</c> session cookie cannot be set for this request, or null when it can (HTTPS, or the machine
|
||||
/// itself). In TLS mode proxy only a trusted proxy makes a request HTTPS, so the refusal names that setting.
|
||||
/// </summary>
|
||||
internal static string? CookieRefusal(HttpContext context, ServerOptions options)
|
||||
{
|
||||
if (SessionCookies.IsSecureTransport(context)) return null;
|
||||
return options.TlsMode == TlsMode.Proxy ? "proxy_untrusted" : "https_required";
|
||||
}
|
||||
|
||||
private static async Task<IResult> LoginAsync(HttpContext context, LoginRequest request, TitanoDatabase db, TokenService tokens, LoginGuard guard,
|
||||
AuditLog audit, TimeProvider time)
|
||||
AuditLog audit, TimeProvider time, ServerOptions options)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (!guard.TryAttempt(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", out var wait)) return TooMany(context, "rate_limited", wait);
|
||||
@@ -27,7 +37,7 @@ public static class AuthEndpoints
|
||||
if (!Accounts.IsValidUsername(account) || string.IsNullOrEmpty(request.Password))
|
||||
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
|
||||
if (guard.IsLocked(account, out wait)) return TooMany(context, "account_locked", wait);
|
||||
if (request.Cookie && !SessionCookies.IsSecureTransport(context)) return ApiErrors.BadRequest(context, "https_required");
|
||||
if (request.Cookie && CookieRefusal(context, options) is { } refusal) return ApiErrors.BadRequest(context, refusal);
|
||||
|
||||
var user = await db.Users.GetByUsernameAsync(account, ct);
|
||||
bool valid;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Data;
|
||||
using Titano.Server.Hosting;
|
||||
|
||||
namespace Titano.Server.Configuration;
|
||||
|
||||
@@ -45,15 +47,29 @@ public sealed class ServerOptions
|
||||
("TITANO_DB_SSLMODE", nameof(DbSslMode), (o, v) => o.DbSslMode = v),
|
||||
("TITANO_HTTP_PORT", nameof(HttpPort), (o, v) => o.HttpPort = Int("TITANO_HTTP_PORT", v)),
|
||||
("TITANO_HTTPS_PORT", nameof(HttpsPort), (o, v) => o.HttpsPort = Int("TITANO_HTTPS_PORT", v)),
|
||||
("TITANO_PUBLIC_HTTP_PORT", nameof(PublicHttpPort), (o, v) => o.PublicHttpPort = Int("TITANO_PUBLIC_HTTP_PORT", v)),
|
||||
("TITANO_PUBLIC_HTTPS_PORT", nameof(PublicHttpsPort), (o, v) => o.PublicHttpsPort = Int("TITANO_PUBLIC_HTTPS_PORT", v)),
|
||||
("TITANO_TLS_MODE", nameof(TlsMode), (o, v) => o.TlsMode = Enum.Parse<TlsMode>(v, ignoreCase: true)),
|
||||
("TITANO_TLS_CERT", nameof(TlsCert), (o, v) => o.TlsCert = v),
|
||||
("TITANO_TLS_KEY", nameof(TlsKey), (o, v) => o.TlsKey = v),
|
||||
("TITANO_TRUSTED_PROXIES", nameof(TrustedProxies), (o, v) => o.TrustedProxies = v),
|
||||
("TITANO_LANG", nameof(Language), (o, v) => o.Language = v),
|
||||
("TITANO_WORKERS", nameof(Workers), (o, v) => o.Workers = Math.Max(1, Int("TITANO_WORKERS", v))),
|
||||
("TITANO_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)),
|
||||
("TITANO_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = Enum.Parse<LogLevel>(v, ignoreCase: true)),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Reverse proxies whose <c>X-Forwarded-*</c> headers count in TLS mode proxy when none are configured: loopback only.
|
||||
/// A home network's machines reach the HTTP port directly from private addresses (also through Docker's port
|
||||
/// publishing, which keeps the client's address), so trusting a private network would let them pick their own
|
||||
/// address again; a proxy in another container or on another machine is listed by its address or network.
|
||||
/// </summary>
|
||||
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128";
|
||||
|
||||
/// <summary>The environment variables the server reads (<c>--help</c> lists them all).</summary>
|
||||
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Prepend("TITANO_DATA_PATH");
|
||||
|
||||
public string ServerName { get; set; } = "Titano Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive";
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data";
|
||||
@@ -72,9 +88,26 @@ public sealed class ServerOptions
|
||||
public string DbSslMode { get; set; } = "prefer";
|
||||
public int HttpPort { get; set; } = 8080;
|
||||
public int HttpsPort { get; set; } = 8443;
|
||||
|
||||
/// <summary>
|
||||
/// Port clients reach the HTTP listener on, when it differs from <see cref="HttpPort"/> (a container port published
|
||||
/// as another host port); advertised by LAN discovery. Null: <see cref="HttpPort"/>.
|
||||
/// </summary>
|
||||
public int? PublicHttpPort { get; set; }
|
||||
|
||||
/// <summary>Port clients reach the HTTPS listener on (admin redirect, LAN discovery). Null: <see cref="HttpsPort"/>.</summary>
|
||||
public int? PublicHttpsPort { get; set; }
|
||||
|
||||
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
|
||||
public string? TlsCert { get; set; }
|
||||
public string? TlsKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Addresses or networks (CIDR), separated by commas or spaces, of the reverse proxies trusted in TLS mode proxy.
|
||||
/// Forwarded headers from any other peer are ignored, so a client that reaches the HTTP port directly cannot choose
|
||||
/// the address the sign-in rate limit and the audit log see.
|
||||
/// </summary>
|
||||
public string TrustedProxies { get; set; } = DefaultTrustedProxies;
|
||||
public string Language { get; set; } = "en";
|
||||
public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2);
|
||||
public bool Discovery { get; set; } = true;
|
||||
@@ -140,7 +173,8 @@ public sealed class ServerOptions
|
||||
{
|
||||
try
|
||||
{
|
||||
options = JsonSerializer.Deserialize(File.ReadAllText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
|
||||
// Its owner is checked first: a file another user planted would choose the archive, database and TLS key.
|
||||
options = JsonSerializer.Deserialize(DataFolderAccess.ReadTrustedText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
@@ -192,12 +226,38 @@ public sealed class ServerOptions
|
||||
// Port 0 asks the OS for a free port (used by the in-process test host).
|
||||
if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535)
|
||||
throw new InvalidOperationException("Ports must be between 0 and 65535.");
|
||||
if (PublicHttpPort is < 1 or > 65535 || PublicHttpsPort is < 1 or > 65535)
|
||||
throw new InvalidOperationException("TITANO_PUBLIC_HTTP_PORT and TITANO_PUBLIC_HTTPS_PORT must be between 1 and 65535.");
|
||||
try
|
||||
{
|
||||
TrustedProxyNetworks();
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new InvalidOperationException($"TITANO_TRUSTED_PROXIES must list IP addresses or networks such as 172.16.0.0/12: {ex.Message}", ex);
|
||||
}
|
||||
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive.");
|
||||
}
|
||||
|
||||
/// <summary>The parsed <see cref="TrustedProxies"/>; a single address is a network of one.</summary>
|
||||
/// <exception cref="FormatException">An entry is neither an IP address nor a network in CIDR notation.</exception>
|
||||
public IReadOnlyList<IPNetwork> TrustedProxyNetworks()
|
||||
{
|
||||
var networks = new List<IPNetwork>();
|
||||
foreach (var entry in TrustedProxies.Split([',', ';', ' ', '\t'], StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (IPNetwork.TryParse(entry, out var network)) networks.Add(network);
|
||||
else if (!entry.Contains('/', StringComparison.Ordinal) && IPAddress.TryParse(entry, out var address)
|
||||
&& (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6 || address.ScopeId == 0))
|
||||
networks.Add(new IPNetwork(address, address.GetAddressBytes().Length * 8));
|
||||
else throw new FormatException($"'{entry}' is neither an address nor a network.");
|
||||
}
|
||||
return networks;
|
||||
}
|
||||
|
||||
/// <summary>TITANO_DB is <c>postgres</c>, <c>sqlite</c> or a complete connection string (<c>Host=…</c> / <c>Data Source=…</c>).</summary>
|
||||
private void ApplyDatabase(string value)
|
||||
{
|
||||
|
||||
@@ -47,14 +47,14 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey || request.Workers != options.Workers
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes || request.JobHistoryDays != options.JobHistoryDays;
|
||||
_saved = request with { ServerName = request.ServerName.Trim(), Locked = [.. options.Locked], RestartRequired = restart };
|
||||
_saved = request with { ServerName = request.ServerName.Trim(), Locked = [.. options.Locked], RestartRequired = restart, ProxyWarning = false };
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Workers, o.Discovery,
|
||||
o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, [.. o.Locked], restartRequired);
|
||||
o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, [.. o.Locked], restartRequired, ProxyWarning: false);
|
||||
|
||||
private static string? Validate(ServerSettingsDto r)
|
||||
{
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
@@ -7,7 +8,9 @@ namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Serves the embedded admin panel at <c>/admin</c>. Requests over plain HTTP from another machine are redirected to
|
||||
/// the HTTPS listener, because the session cookie is <c>Secure</c> (BRIEF §14.2) and would not survive plain HTTP.
|
||||
/// the HTTPS listener, on the port clients reach it on (<see cref="ServerOptions.PublicHttpsPort"/> when a container
|
||||
/// port is published as another host port), because the session cookie is <c>Secure</c> (BRIEF §14.2) and would not
|
||||
/// survive plain HTTP.
|
||||
/// </summary>
|
||||
public static class AdminPanel
|
||||
{
|
||||
@@ -33,14 +36,22 @@ public static class AdminPanel
|
||||
});
|
||||
}
|
||||
|
||||
private static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
|
||||
/// <summary>
|
||||
/// True when TLS mode is proxy but this request did not reach the server through a trusted proxy over HTTPS (BRIEF
|
||||
/// §14.2: the admin warns). The server has no HTTPS listener in that mode, so a request is HTTPS only when a proxy
|
||||
/// listed in <see cref="ServerOptions.TrustedProxies"/> forwarded it as such.
|
||||
/// </summary>
|
||||
public static bool BypassesProxy(HttpContext context, ServerOptions options) =>
|
||||
options.TlsMode == TlsMode.Proxy && !context.Request.IsHttps;
|
||||
|
||||
internal static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
|
||||
{
|
||||
if (context.Request.IsHttps || options.TlsMode == TlsMode.Proxy) return null;
|
||||
if (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote)) return null;
|
||||
foreach (var address in server.Features.Get<IServerAddressesFeature>()?.Addresses ?? [])
|
||||
{
|
||||
if (!address.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var port = address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
|
||||
var port = options.PublicHttpsPort?.ToString(CultureInfo.InvariantCulture) ?? address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
|
||||
return $"https://{context.Request.Host.Host}:{port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -34,8 +34,8 @@ public static class CertificateStore
|
||||
logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter);
|
||||
}
|
||||
var created = CreateSelfSigned(options.ServerName);
|
||||
File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12));
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
// The PKCS#12 export carries the private key without a password: only the server's account may read it.
|
||||
DataFolderAccess.WritePrivateFile(path, created.Export(X509ContentType.Pkcs12));
|
||||
logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created));
|
||||
return created;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Titano.Core.Archiving;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the data folder and its secrets private (BRIEF §14.2): it holds the database, the TLS private key, the
|
||||
/// temporary admin password and <c>server.json</c>. On Windows the folder sits in <c>%ProgramData%</c>, whose ACL lets
|
||||
/// every local user read it and create files in it, so it gets a protected DACL (nothing inherited) that allows only
|
||||
/// SYSTEM, Administrators and the account the server runs as; everything inside inherits that. Those accounts must also
|
||||
/// own the folder and everything in it, and nothing in it may be a link: an owner can always change the ACL back, and
|
||||
/// whoever planted a file chose what it says. Elsewhere the container entrypoint owns <c>/data</c>, and secrets are
|
||||
/// written with mode 0600. An archive folder the server creates on Windows gets the same accounts (see
|
||||
/// <see cref="PrepareArchive"/>).
|
||||
/// </summary>
|
||||
public static class DataFolderAccess
|
||||
{
|
||||
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
private const int GenericAll = 0x10000000;
|
||||
private const int GenericWrite = 0x40000000;
|
||||
|
||||
/// <summary>Rights that let an account replace or alter a file or folder (including the generic forms).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
|
||||
| FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
|
||||
| (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the folder if needed and, on Windows, refuses a folder that holds a link or an entry owned by anyone
|
||||
/// else, then replaces an ACL that grants anyone else access.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// Something in the folder is a link or belongs to another account, or the ACL cannot be read or changed (the account
|
||||
/// is not an administrator).
|
||||
/// </exception>
|
||||
public static void Restrict(string folder)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
RestrictOnWindows(new DirectoryInfo(folder));
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Titano Server cannot check or restrict access to {folder}: {ex.Message} Run it once as an administrator; if someone else changed the folder's access, delete the folder.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a file the server acts on (<c>server.json</c>). On Windows its owner must be SYSTEM, Administrators or the
|
||||
/// server's account, checked on the handle that is read, so a file another user planted (or swapped in) is refused
|
||||
/// before any of its settings is used.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The file belongs to another account.</exception>
|
||||
public static string ReadTrustedText(string path)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return File.ReadAllText(path);
|
||||
return ReadTrustedText(path, AllowedAccounts());
|
||||
}
|
||||
|
||||
/// <summary>Writes a secret that only the server's account (and, on Windows, SYSTEM and Administrators) may read.</summary>
|
||||
public static void WritePrivateFile(string path, ReadOnlySpan<byte> contents)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
WritePrivateFileOnWindows(new FileInfo(path), contents);
|
||||
return;
|
||||
}
|
||||
using (var stream = new FileStream(path, new FileStreamOptions { Mode = FileMode.Create, Access = FileAccess.Write, UnixCreateMode = OwnerOnly }))
|
||||
stream.Write(contents);
|
||||
// A file that already existed keeps its old mode otherwise.
|
||||
File.SetUnixFileMode(path, OwnerOnly);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the archive folder when it is missing, and says whether accounts other than SYSTEM, Administrators and the
|
||||
/// server's own can change it (always false off Windows, where the container entrypoint checks the archive). On
|
||||
/// Windows a folder created here gets a protected ACL: those accounts change it, other local users may only read it;
|
||||
/// a <c>.titano</c> folder (staging, trash) created here is private. Whoever can write where the server moves files
|
||||
/// can put a link in place of a folder and send the server's writes elsewhere; an existing archive is only reported,
|
||||
/// because its ACL is its owner's choice.
|
||||
/// </summary>
|
||||
public static bool PrepareArchive(string root)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
return false;
|
||||
}
|
||||
var folder = new DirectoryInfo(root);
|
||||
if (!folder.Exists)
|
||||
{
|
||||
if (folder.Parent is { } parent) parent.Create();
|
||||
folder.Create(ArchiveFolderSecurity());
|
||||
folder.Refresh();
|
||||
}
|
||||
// Created before the archive engine would create it with the archive's ACL; an existing one is left as it is.
|
||||
var meta = new DirectoryInfo(new ArchivePaths(root).MetaDirectory);
|
||||
if (!meta.Exists) meta.Create(PrivateFolderSecurity());
|
||||
return OthersCanChange(folder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the ACL is protected, its owner is SYSTEM, Administrators or this process's account, and it names no
|
||||
/// other account.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public static bool IsPrivate(FileSystemSecurity security)
|
||||
{
|
||||
if (!security.AreAccessRulesProtected) return false;
|
||||
var allowed = AllowedAccounts();
|
||||
if (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || !allowed.Contains(owner)) return false;
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType == AccessControlType.Allow && !allowed.Contains((SecurityIdentifier)rule.IdentityReference)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first problem with <paramref name="folder"/> or anything inside it, as a sentence for the operator, or null:
|
||||
/// a link (it would carry what the server reads, writes and secures elsewhere) or an owner outside
|
||||
/// <paramref name="owners"/> (who may have written the contents and can always change the ACL back). Links are
|
||||
/// reported, never followed.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static string? FindUntrusted(DirectoryInfo folder, IReadOnlySet<SecurityIdentifier> owners)
|
||||
{
|
||||
var everything = new EnumerationOptions { AttributesToSkip = 0, IgnoreInaccessible = false };
|
||||
var pending = new Stack<DirectoryInfo>();
|
||||
pending.Push(folder);
|
||||
while (pending.TryPop(out var directory))
|
||||
{
|
||||
if (Untrusted(directory, owners) is { } problem) return problem;
|
||||
foreach (var entry in directory.EnumerateFileSystemInfos("*", everything))
|
||||
{
|
||||
if (entry is DirectoryInfo child && !IsLink(child)) pending.Push(child);
|
||||
else if (Untrusted(entry, owners) is { } entryProblem) return entryProblem;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ReadTrustedText(string)"/>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static string ReadTrustedText(string path, IReadOnlySet<SecurityIdentifier> owners)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
if (UntrustedOwner(path, stream.GetAccessControl(), owners) is { } problem) throw new InvalidOperationException(problem);
|
||||
using var reader = new StreamReader(stream);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the owner is outside <paramref name="trusted"/> or an allow entry gives change rights to such an
|
||||
/// account. Entries that only pass to children count too, since new files would inherit them; CREATOR OWNER and
|
||||
/// CREATOR GROUP stand for whoever creates a child, which already takes change rights on the folder.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static bool IsChangeableByOthers(FileSystemSecurity security, IReadOnlySet<SecurityIdentifier> trusted, bool checkOwner)
|
||||
{
|
||||
if (checkOwner && (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || !trusted.Contains(owner))) return true;
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType != AccessControlType.Allow || (rule.FileSystemRights & ChangeRights) == 0) continue;
|
||||
var account = (SecurityIdentifier)rule.IdentityReference;
|
||||
if (trusted.Contains(account) || account.IsWellKnown(WellKnownSidType.CreatorOwnerSid) || account.IsWellKnown(WellKnownSidType.CreatorGroupSid)) continue;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static HashSet<SecurityIdentifier> AllowedAccounts()
|
||||
{
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
var accounts = new HashSet<SecurityIdentifier>
|
||||
{
|
||||
new(WellKnownSidType.LocalSystemSid, null),
|
||||
new(WellKnownSidType.BuiltinAdministratorsSid, null),
|
||||
};
|
||||
if (identity.User is { } user) accounts.Add(user);
|
||||
return accounts;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void RestrictOnWindows(DirectoryInfo folder)
|
||||
{
|
||||
if (!folder.Exists)
|
||||
{
|
||||
if (folder.Parent is { } parent) parent.Create();
|
||||
folder.Create(PrivateFolderSecurity());
|
||||
folder.Refresh();
|
||||
}
|
||||
// Before the ACL is touched: a folder another user created in advance, or a file planted in an older version's
|
||||
// folder, stays theirs whatever the ACL says, and a link would carry the new ACL elsewhere.
|
||||
if (FindUntrusted(folder, AllowedAccounts()) is { } problem) throw new InvalidOperationException(problem);
|
||||
// An older version, or Windows' default inheritance from %ProgramData%, left the folder readable by every user.
|
||||
// Setting the DACL by name also replaces what the files inside inherited.
|
||||
if (!IsPrivate(folder.GetAccessControl())) folder.SetAccessControl(PrivateFolderSecurity());
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static string? Untrusted(FileSystemInfo entry, IReadOnlySet<SecurityIdentifier> owners)
|
||||
{
|
||||
if (IsLink(entry))
|
||||
{
|
||||
return $"{entry.FullName} is a link to {entry.LinkTarget}, and Titano Server follows no links in its data folder. "
|
||||
+ "Delete the link (TITANO_DATA_PATH moves the data folder) and start the server again.";
|
||||
}
|
||||
FileSystemSecurity security = entry is DirectoryInfo directory
|
||||
? directory.GetAccessControl(AccessControlSections.Owner)
|
||||
: ((FileInfo)entry).GetAccessControl(AccessControlSections.Owner);
|
||||
return UntrustedOwner(entry.FullName, security, owners);
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static string? UntrustedOwner(string path, FileSystemSecurity security, IReadOnlySet<SecurityIdentifier> owners)
|
||||
{
|
||||
var owner = security.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier;
|
||||
if (owner is not null && owners.Contains(owner)) return null;
|
||||
return $"{path} belongs to {(owner is null ? "no account" : AccountName(owner))}, not to SYSTEM, Administrators or the account Titano Server "
|
||||
+ "runs as, so it cannot be trusted. Check it, then delete it or make Administrators its owner, and start the server again.";
|
||||
}
|
||||
|
||||
/// <summary>A symbolic link or junction (other reparse points, such as deduplicated files, are ordinary files).</summary>
|
||||
private static bool IsLink(FileSystemInfo entry) => (entry.Attributes & FileAttributes.ReparsePoint) != 0 && entry.LinkTarget is not null;
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static string AccountName(SecurityIdentifier account)
|
||||
{
|
||||
try
|
||||
{
|
||||
return account.Translate(typeof(NTAccount)).Value;
|
||||
}
|
||||
catch (IdentityNotMappedException)
|
||||
{
|
||||
return account.Value;
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool OthersCanChange(DirectoryInfo folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
return IsChangeableByOthers(folder.GetAccessControl(), AllowedAccounts(), checkOwner: true);
|
||||
}
|
||||
catch (NotSupportedException)
|
||||
{
|
||||
// A volume without ACLs (FAT, exFAT): everyone can change everything.
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is UnauthorizedAccessException or IOException or InvalidOperationException)
|
||||
{
|
||||
// The ACL cannot be read (some network shares); the warning would be a guess.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void WritePrivateFileOnWindows(FileInfo file, ReadOnlySpan<byte> contents)
|
||||
{
|
||||
// A file that already exists is replaced, never rewritten in place: it would keep its owner, who could change its
|
||||
// ACL back at any time, and a link would carry the secret elsewhere. The new file is owned by this account.
|
||||
file.Delete();
|
||||
using var stream = file.Create(FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, PrivateFileSecurity());
|
||||
stream.Write(contents);
|
||||
}
|
||||
|
||||
/// <summary>A protected DACL that gives the allowed accounts full control, passed on to everything inside.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static DirectorySecurity PrivateFolderSecurity()
|
||||
{
|
||||
var security = new DirectorySecurity();
|
||||
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
foreach (var account in AllowedAccounts())
|
||||
{
|
||||
security.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
|
||||
}
|
||||
return security;
|
||||
}
|
||||
|
||||
/// <summary>The private DACL, plus read access for every local user (photos and renders, never <c>.titano</c>).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static DirectorySecurity ArchiveFolderSecurity()
|
||||
{
|
||||
var security = PrivateFolderSecurity();
|
||||
security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
|
||||
return security;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static FileSecurity PrivateFileSecurity()
|
||||
{
|
||||
var security = new FileSecurity();
|
||||
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
foreach (var account in AllowedAccounts())
|
||||
security.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow));
|
||||
return security;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,8 @@ namespace Titano.Server.Hosting;
|
||||
/// <summary>
|
||||
/// LAN discovery (BRIEF §14.9, <c>TITANO_DISCOVERY</c>): every few seconds a <see cref="DiscoveryBeacon"/> is broadcast on
|
||||
/// UDP port <see cref="DiscoveryBeacon.Port"/> of every IPv4 network, so clients can offer this server on first run.
|
||||
/// Switching discovery off in the settings stops it without a restart.
|
||||
/// Switching discovery off in the settings stops it without a restart. In a container the broadcasts reach the LAN
|
||||
/// only with host networking; on a bridge network they stay on the bridge.
|
||||
/// </summary>
|
||||
public sealed class DiscoveryBeaconService(ServerOptions options, ServerState state, IServer server, ILogger<DiscoveryBeaconService> logger) : BackgroundService
|
||||
{
|
||||
@@ -51,12 +52,15 @@ public sealed class DiscoveryBeaconService(ServerOptions options, ServerState st
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The beacon for the ports Kestrel actually listens on (HTTPS 0 when TLS is terminated elsewhere).</summary>
|
||||
/// <summary>
|
||||
/// The beacon for the ports clients reach: the public ports when set, else the ports Kestrel actually listens on
|
||||
/// (HTTPS 0 when TLS is terminated elsewhere).
|
||||
/// </summary>
|
||||
public DiscoveryBeacon CreateBeacon() => new(
|
||||
options.ServerName,
|
||||
SystemEndpoints.Version,
|
||||
BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
|
||||
state.TlsFingerprint is null ? 0 : BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
|
||||
options.PublicHttpPort ?? BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
|
||||
state.TlsFingerprint is null ? 0 : options.PublicHttpsPort ?? BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
|
||||
state.TlsFingerprint);
|
||||
|
||||
public async Task SendOnceAsync(UdpClient udp, IEnumerable<IPEndPoint> targets, CancellationToken cancellationToken)
|
||||
|
||||
@@ -36,7 +36,16 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
TITANO_ARCHIVE_PATH TITANO_DATA_PATH TITANO_SERVER_NAME TITANO_ADMIN_USER TITANO_ADMIN_PASSWORD
|
||||
TITANO_DB (postgres | sqlite | connection string) TITANO_DB_HOST TITANO_DB_PORT TITANO_DB_NAME TITANO_DB_USER
|
||||
TITANO_DB_PASSWORD TITANO_DB_SSLMODE TITANO_HTTP_PORT TITANO_HTTPS_PORT TITANO_TLS_MODE (auto | pem | proxy)
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS TITANO_DISCOVERY
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS
|
||||
TITANO_LOG_LEVEL (Trace | Debug | Information | Warning | Error)
|
||||
TITANO_DISCOVERY LAN beacon (true | false); in a container it needs host networking
|
||||
TITANO_PUBLIC_HTTP_PORT, TITANO_PUBLIC_HTTPS_PORT
|
||||
ports clients reach when the container's ports are published as other host ports
|
||||
(admin redirect to HTTPS, LAN beacon)
|
||||
TITANO_TRUSTED_PROXIES proxy mode: addresses or networks (CIDR) whose X-Forwarded-* headers count
|
||||
(default: loopback only; list a proxy in another container or on another machine)
|
||||
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (local time zone)
|
||||
""";
|
||||
|
||||
public static ServerCommandLine Parse(IReadOnlyList<string> args)
|
||||
|
||||
@@ -29,10 +29,11 @@ public static class ServerHost
|
||||
|
||||
public static WebApplication Build(ServerOptions options, string[] args, Action<IServiceCollection>? configureServices = null)
|
||||
{
|
||||
Directory.CreateDirectory(options.DataPath);
|
||||
// Before anything is written there: the folder holds the database, the TLS key and the first admin password.
|
||||
DataFolderAccess.Restrict(options.DataPath);
|
||||
Directory.CreateDirectory(options.LogPath);
|
||||
Directory.CreateDirectory(options.UploadsPath);
|
||||
Directory.CreateDirectory(options.ArchivePath);
|
||||
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
|
||||
builder.Logging.ClearProviders();
|
||||
@@ -81,6 +82,12 @@ public static class ServerHost
|
||||
app.Logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · {Database} · TLS {Tls}{Fingerprint}",
|
||||
SystemEndpoints.Version, options.ArchivePath, options.DataPath, state.Database, options.TlsMode,
|
||||
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
||||
if (archiveOpenToOthers)
|
||||
{
|
||||
app.Logger.LogWarning("Accounts other than SYSTEM, Administrators and the one Titano Server runs as can change the archive {Archive}: "
|
||||
+ "they could put a link in place of a folder and redirect the files the server moves. Let only those accounts change it (others may read it).",
|
||||
options.ArchivePath);
|
||||
}
|
||||
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Titano Server stopping"));
|
||||
app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult());
|
||||
return app;
|
||||
@@ -105,11 +112,15 @@ public static class ServerHost
|
||||
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
|
||||
if (options.TlsMode == TlsMode.Proxy)
|
||||
{
|
||||
// Only the configured proxies may say who the client is: a client that reaches the HTTP port directly would
|
||||
// otherwise pick its own address for the sign-in rate limit and the audit log, and claim HTTPS.
|
||||
var trusted = options.TrustedProxyNetworks();
|
||||
services.Configure<ForwardedHeadersOptions>(f =>
|
||||
{
|
||||
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
f.KnownIPNetworks.Clear();
|
||||
f.KnownProxies.Clear();
|
||||
foreach (var network in trusted) f.KnownIPNetworks.Add(network);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.Principal;
|
||||
using Titano.Core.Localization;
|
||||
using static Titano.Server.Hosting.Windows.ServiceNative;
|
||||
|
||||
@@ -9,15 +10,23 @@ namespace Titano.Server.Hosting.Windows;
|
||||
/// <summary>
|
||||
/// <c>--install-service</c> / <c>--uninstall-service</c>: registers the server with the Service Control Manager
|
||||
/// (automatic start, LocalSystem, command line <c>"…\Titano.Server.exe" --service</c>) or stops and removes it.
|
||||
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>.
|
||||
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>. A LocalSystem service runs whatever
|
||||
/// sits at its image path, so it is registered only from a copy under Program Files that nobody but SYSTEM,
|
||||
/// Administrators and TrustedInstaller can change: a per-user install or a zip unpacked elsewhere would hand SYSTEM to
|
||||
/// any program of that user. Otherwise <see cref="Install"/> refuses with <see cref="InvalidOperationException"/>.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public static unsafe class ServiceInstaller
|
||||
{
|
||||
private const string DisplayName = "Titano Server";
|
||||
|
||||
/// <summary>TrustedInstaller, the owner of Windows' own files under Program Files.</summary>
|
||||
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
|
||||
|
||||
/// <exception cref="InvalidOperationException">This copy is not in a folder that only administrators can change.</exception>
|
||||
public static void Install()
|
||||
{
|
||||
if (UnsafeLocation() is { } problem) throw new InvalidOperationException(problem);
|
||||
var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService);
|
||||
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
|
||||
try
|
||||
@@ -71,6 +80,73 @@ public static unsafe class ServiceInstaller
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when
|
||||
/// run by <c>dotnet</c>, the host's folder) must be inside Program Files and changeable only by administrators.
|
||||
/// </summary>
|
||||
internal static string? UnsafeLocation()
|
||||
{
|
||||
var program = Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory);
|
||||
if (!IsUnderProgramFiles(program)) return Loc.L("Server.Service.NotProgramFiles", program);
|
||||
if (FindChangeable(new DirectoryInfo(program), recursive: true) is { } open) return Loc.L("Server.Service.Writable", open);
|
||||
// Under dotnet the host runs as SYSTEM too; its folder is checked without the thousands of framework files below it.
|
||||
if (Environment.ProcessPath is { } process && Path.GetDirectoryName(process) is { } host
|
||||
&& !string.Equals(Path.TrimEndingDirectorySeparator(host), program, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!IsUnderProgramFiles(host)) return Loc.L("Server.Service.NotProgramFiles", host);
|
||||
if (FindChangeable(new DirectoryInfo(host), recursive: false) is { } hostOpen) return Loc.L("Server.Service.Writable", hostOpen);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>True for a path inside <c>%ProgramFiles%</c> or <c>%ProgramFiles(x86)%</c> (not the folder itself).</summary>
|
||||
internal static bool IsUnderProgramFiles(string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 })
|
||||
{
|
||||
var root = Environment.GetFolderPath(folder);
|
||||
if (root.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first of the folder, its files and (when recursive) its subfolders whose ACL lets an account other than
|
||||
/// SYSTEM, Administrators, TrustedInstaller or the registering administrator change it; null when there is none.
|
||||
/// </summary>
|
||||
internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts());
|
||||
|
||||
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> trusted)
|
||||
{
|
||||
if (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName;
|
||||
foreach (var file in folder.EnumerateFiles())
|
||||
{
|
||||
if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) return file.FullName;
|
||||
}
|
||||
if (!recursive) return null;
|
||||
foreach (var child in folder.EnumerateDirectories())
|
||||
{
|
||||
if (FindChangeable(child, recursive: true, trusted) is { } path) return path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static HashSet<SecurityIdentifier> TrustedAccounts()
|
||||
{
|
||||
var trusted = new HashSet<SecurityIdentifier>
|
||||
{
|
||||
new(WellKnownSidType.LocalSystemSid, null),
|
||||
new(WellKnownSidType.BuiltinAdministratorsSid, null),
|
||||
TrustedInstaller,
|
||||
};
|
||||
// Registering needs an elevated prompt, so the account doing it is an administrator; setups often name it.
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
if (identity.User is { } user && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) trusted.Add(user);
|
||||
return trusted;
|
||||
}
|
||||
|
||||
/// <summary>The service's command line: this executable (or <c>dotnet</c> plus this assembly) with <c>--service</c>.</summary>
|
||||
private static string CommandLine()
|
||||
{
|
||||
|
||||
@@ -50,8 +50,9 @@ static int ServiceAction(Action action, string done)
|
||||
Console.WriteLine(done);
|
||||
return 0;
|
||||
}
|
||||
catch (Win32Exception ex)
|
||||
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
|
||||
{
|
||||
// Win32: the Service Control Manager's reason; InvalidOperation: a folder the service must not run from.
|
||||
Console.Error.WriteLine(ex.Message);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
using System.Text;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
|
||||
namespace Titano.Server.Security;
|
||||
|
||||
/// <summary>
|
||||
/// First-run administrator (BRIEF §14.9): when no admin account exists, one is created from
|
||||
/// <c>TITANO_ADMIN_USER</c>/<c>TITANO_ADMIN_PASSWORD</c> and must change its password at first sign-in. Without a
|
||||
/// configured password a temporary one is generated and written to <c>/data/initial-admin-password.txt</c> (owner-only),
|
||||
/// never to the log; the file is removed once an administrator changes their password.
|
||||
/// configured password a temporary one is generated and written to <c>/data/initial-admin-password.txt</c> (owner-only;
|
||||
/// on Windows readable by the server's account and Administrators), never to the log; the file is removed once an
|
||||
/// administrator changes their password.
|
||||
/// </summary>
|
||||
public static class AdminBootstrap
|
||||
{
|
||||
@@ -37,8 +40,7 @@ public static class AdminBootstrap
|
||||
{
|
||||
password = TemporaryPassword.Generate();
|
||||
passwordFile = Path.Combine(options.DataPath, PasswordFileName);
|
||||
await File.WriteAllTextAsync(passwordFile, password + Environment.NewLine, cancellationToken).ConfigureAwait(false);
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(passwordFile, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
DataFolderAccess.WritePrivateFile(passwordFile, Encoding.UTF8.GetBytes(password + Environment.NewLine));
|
||||
}
|
||||
|
||||
var admin = new User
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The data folder and its secrets are private (BRIEF §14.2): mode 0600 off Windows; on Windows a protected ACL that no
|
||||
/// ordinary user appears in, where %ProgramData% would otherwise let every local user read the folder, with owners the
|
||||
/// server trusts and no links. On Windows a new archive folder lets other users only read it.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class DataFolderAccessTests(TestContext context)
|
||||
{
|
||||
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
|
||||
[Test]
|
||||
public async Task TheTlsKeyAndTheFirstAdminPasswordAreReadableOnlyByTheServer()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.AdminPassword = null);
|
||||
foreach (var file in new[] { Path.Combine(server.Options.TlsPath, "server.pfx"), Path.Combine(server.Options.DataPath, "initial-admin-password.txt") })
|
||||
{
|
||||
Assert.FileExists(file);
|
||||
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()), file);
|
||||
else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file));
|
||||
}
|
||||
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(server.Options.DataPath).GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARewrittenSecretLosesTheAccessItHad()
|
||||
{
|
||||
var file = Path.Combine(context.CreateTempDirectory("secret"), "server.pfx");
|
||||
File.WriteAllBytes(file, [1]);
|
||||
if (OperatingSystem.IsWindows()) GrantUsersRead(new FileInfo(file));
|
||||
else File.SetUnixFileMode(file, OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
|
||||
|
||||
DataFolderAccess.WritePrivateFile(file, [1, 2, 3]);
|
||||
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(file));
|
||||
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()));
|
||||
else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AFolderEveryUserCouldReadBecomesPrivateWithItsFiles()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("programdata"));
|
||||
// What %ProgramData% hands down to a new folder: every local user may read it and create files in it.
|
||||
var open = folder.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.ReadAndExecute | FileSystemRights.CreateFiles,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
|
||||
folder.SetAccessControl(open);
|
||||
var database = new FileInfo(Path.Combine(folder.FullName, "titano.db"));
|
||||
File.WriteAllText(database.FullName, "rows");
|
||||
Assert.True(NamesUsers(database.GetAccessControl()), "the file inherited the users' entry");
|
||||
|
||||
DataFolderAccess.Restrict(folder.FullName);
|
||||
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
|
||||
Assert.False(NamesUsers(folder.GetAccessControl()));
|
||||
Assert.False(NamesUsers(database.GetAccessControl()), "the file still lets every user read it");
|
||||
Assert.Equal("rows", File.ReadAllText(database.FullName));
|
||||
|
||||
// Once private, a later start leaves it as it is.
|
||||
DataFolderAccess.Restrict(folder.FullName);
|
||||
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ANewDataFolderIsCreatedPrivate()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("new"), "Titano Server"));
|
||||
DataFolderAccess.Restrict(folder.FullName);
|
||||
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
|
||||
var settings = new FileInfo(Path.Combine(folder.FullName, "server.json"));
|
||||
File.WriteAllText(settings.FullName, "{}");
|
||||
Assert.False(NamesUsers(settings.GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ASecretAnotherAccountOwnedIsReplacedByOneTheServerOwns()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = context.CreateTempDirectory("planted");
|
||||
var own = OwnerOf(NewFile(Path.Combine(folder, "probe.txt")));
|
||||
// Planted before the first start: whoever owns it keeps the right to change its ACL, whatever the server sets.
|
||||
var secret = NewFile(Path.Combine(folder, "initial-admin-password.txt"));
|
||||
if (!TrySetOwner(secret, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
|
||||
GrantUsersRead(secret);
|
||||
|
||||
DataFolderAccess.WritePrivateFile(secret.FullName, [1, 2, 3]);
|
||||
secret.Refresh();
|
||||
Assert.Equal(own, OwnerOf(secret));
|
||||
Assert.True(DataFolderAccess.IsPrivate(secret.GetAccessControl()));
|
||||
Assert.False(NamesUsers(secret.GetAccessControl()));
|
||||
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(secret.FullName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnythingAnotherAccountOwnsIsFound()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("squatted"));
|
||||
var key = NewFile(Path.Combine(folder.CreateSubdirectory("tls").FullName, "server.pfx"));
|
||||
var own = OwnerOf(key);
|
||||
Assert.Null(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own }));
|
||||
// A folder someone else created before the first start is reported before anything inside it.
|
||||
Assert.Contains(folder.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { LocalSystem })));
|
||||
|
||||
if (!TrySetOwner(key, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
|
||||
Assert.Contains(key.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own })));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ALinkInTheDataFolderStopsTheServerBeforeTheAclChanges()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("linked"));
|
||||
var link = Path.Combine(folder.FullName, "logs");
|
||||
try
|
||||
{
|
||||
Directory.CreateSymbolicLink(link, context.CreateTempDirectory("elsewhere"));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Assert.Inconclusive("creating a symbolic link needs an elevated administrator or developer mode");
|
||||
}
|
||||
|
||||
var refused = Assert.Throws<InvalidOperationException>(() => DataFolderAccess.Restrict(folder.FullName));
|
||||
Assert.Contains(link, refused.Message);
|
||||
// The ACL change would have followed the link; it never started.
|
||||
Assert.False(folder.GetAccessControl().AreAccessRulesProtected);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void SettingsAnotherAccountOwnsAreNotRead()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var settings = NewFile(Path.Combine(context.CreateTempDirectory("settings"), "server.json"), """{ "ArchivePath": "D:\\Elsewhere" }""");
|
||||
Assert.Contains("Elsewhere", DataFolderAccess.ReadTrustedText(settings.FullName));
|
||||
// As if another account had planted it: the owner is not among those the server trusts.
|
||||
InvalidOperationException? refused = null;
|
||||
try
|
||||
{
|
||||
DataFolderAccess.ReadTrustedText(settings.FullName, new HashSet<SecurityIdentifier> { LocalSystem });
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
refused = ex;
|
||||
}
|
||||
Assert.Contains(settings.FullName, Assert.NotNull(refused).Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AMissingArchiveFolderIsCreated()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("archive"), "TitanoArchive");
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root));
|
||||
Assert.True(Directory.Exists(root));
|
||||
// An existing folder is left as it is.
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ANewArchiveIsReadableByUsersButOnlyTheServerChangesIt()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
// Under C:\ a new folder would inherit "Authenticated Users: modify" and every local user could plant links
|
||||
// where the service moves uploads.
|
||||
var root = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("archive"), "TitanoArchive"));
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root.FullName));
|
||||
var security = root.GetAccessControl();
|
||||
Assert.True(security.AreAccessRulesProtected);
|
||||
Assert.Equal(FileSystemRights.ReadAndExecute, RightsOf(security, Users) & FileSystemRights.ReadAndExecute);
|
||||
Assert.Equal((FileSystemRights)0, RightsOf(security, Users) & (FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.ChangePermissions));
|
||||
|
||||
// Staging and trash are the server's alone.
|
||||
var meta = new DirectoryInfo(Path.Combine(root.FullName, ".titano"));
|
||||
Assert.True(DataFolderAccess.IsPrivate(meta.GetAccessControl()));
|
||||
Assert.False(NamesUsers(meta.CreateSubdirectory("staging").GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnArchiveOtherUsersCanChangeIsReportedButLeftAsItIs()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var root = new DirectoryInfo(context.CreateTempDirectory("shared"));
|
||||
DataFolderAccess.PrepareArchive(root.FullName);
|
||||
var open = root.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Modify,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
|
||||
root.SetAccessControl(open);
|
||||
|
||||
Assert.True(DataFolderAccess.PrepareArchive(root.FullName));
|
||||
Assert.Equal(FileSystemRights.Modify, RightsOf(root.GetAccessControl(), Users) & FileSystemRights.Modify);
|
||||
// The .titano folder the server added at the first start stays its own.
|
||||
Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(Path.Combine(root.FullName, ".titano")).GetAccessControl()));
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier Users => new(WellKnownSidType.BuiltinUsersSid, null);
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier LocalSystem => new(WellKnownSidType.LocalSystemSid, null);
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier Administrators => new(WellKnownSidType.BuiltinAdministratorsSid, null);
|
||||
|
||||
private static FileInfo NewFile(string path, string contents = "x")
|
||||
{
|
||||
File.WriteAllText(path, contents);
|
||||
return new FileInfo(path);
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier OwnerOf(FileInfo file) => (SecurityIdentifier)file.GetAccessControl().GetOwner(typeof(SecurityIdentifier))!;
|
||||
|
||||
/// <summary>An owner this process may give a file that its new files do not get: its own account or Administrators.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier OtherOwner(SecurityIdentifier own)
|
||||
{
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
return own == Administrators ? identity.User! : Administrators;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool TrySetOwner(FileInfo file, SecurityIdentifier owner)
|
||||
{
|
||||
var security = new FileSecurity();
|
||||
security.SetOwner(owner);
|
||||
try
|
||||
{
|
||||
file.SetAccessControl(security);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The rights allow entries give <paramref name="account"/>.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static FileSystemRights RightsOf(FileSystemSecurity security, SecurityIdentifier account)
|
||||
{
|
||||
FileSystemRights rights = 0;
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType == AccessControlType.Allow && rule.IdentityReference.Equals(account)) rights |= rule.FileSystemRights;
|
||||
}
|
||||
return rights;
|
||||
}
|
||||
|
||||
/// <summary>True when Users, Authenticated Users or Everyone have any allow entry.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool NamesUsers(FileSystemSecurity security)
|
||||
{
|
||||
SecurityIdentifier[] ordinary = [Users, new(WellKnownSidType.AuthenticatedUserSid, null), new(WellKnownSidType.WorldSid, null)];
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType == AccessControlType.Allow && ordinary.Contains((SecurityIdentifier)rule.IdentityReference)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void GrantUsersRead(FileInfo file)
|
||||
{
|
||||
var security = file.GetAccessControl();
|
||||
security.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Read, AccessControlType.Allow));
|
||||
file.SetAccessControl(security);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,19 @@ public sealed class DiscoveryTests(TestContext context)
|
||||
Assert.Equal((await info.ReadAsync(ProtocolJson.Default.ServerInfo)).TlsFingerprint, beacon.TlsFingerprint);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheBeaconAdvertisesThePortsClientsReach()
|
||||
{
|
||||
// Container ports published as other host ports: a client on the LAN must use the host's.
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.PublicHttpPort = 18080;
|
||||
o.PublicHttpsPort = 18443;
|
||||
});
|
||||
var beacon = server.Services.GetRequiredService<DiscoveryBeaconService>().CreateBeacon();
|
||||
Assert.Equal((18080, 18443), (beacon.HttpPort, beacon.HttpsPort));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForeignDatagramsAreIgnored()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>TLS mode proxy (BRIEF §14.2): forwarded headers count only from trusted proxies, and the admin warns otherwise.</summary>
|
||||
[Category("server")]
|
||||
public sealed class ProxyModeTests(TestContext context)
|
||||
{
|
||||
/// <summary>A documentation network (RFC 5737) the test client never connects from.</summary>
|
||||
private const string ElsewhereOnly = "192.0.2.0/24";
|
||||
|
||||
[Test]
|
||||
public async Task AClientOutsideTheTrustedProxiesCannotChooseItsAddress()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = ElsewhereOnly;
|
||||
o.LoginAttemptsPerMinute = 5;
|
||||
});
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
|
||||
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
||||
}
|
||||
// A new X-Forwarded-For per attempt does not buy a new budget: the limit stays on the real address.
|
||||
using var limited = await LoginAsync(server, "admin", "203.0.113.99");
|
||||
await limited.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited");
|
||||
|
||||
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
|
||||
Assert.Count(5, audit.Items);
|
||||
Assert.True(audit.Items.All(e => IsLoopback(e.RemoteAddress)), string.Join(", ", audit.Items.Select(e => e.RemoteAddress)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATrustedProxyReportsTheClientAddress()
|
||||
{
|
||||
// The default trusts loopback, where a proxy on the same machine (and this test) connects from.
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.LoginAttemptsPerMinute = 5;
|
||||
});
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
|
||||
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
||||
}
|
||||
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
|
||||
Assert.Contains("203.0.113.8", audit.Items.Select(e => e.RemoteAddress));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ByDefaultAMachineOfTheHomeNetworkIsNoProxy()
|
||||
{
|
||||
// The machines of a home network reach the HTTP port directly from private addresses, also through Docker's
|
||||
// port publishing (which keeps the client's address): none of them may choose its own address.
|
||||
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
|
||||
foreach (var peer in new[] { "192.168.1.50", "10.0.0.7", "172.17.0.1", "fd00::7" })
|
||||
Assert.Equal((peer, false), await ForwardAsync(server, peer));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "127.0.0.1"));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::ffff:127.0.0.1"));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::1"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyNetworkCountsOnceListed()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = "172.18.0.0/16";
|
||||
});
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "172.18.0.5"));
|
||||
Assert.Equal(("192.168.1.50", false), await ForwardAsync(server, "192.168.1.50"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnAdminSignInThroughAnUntrustedProxyNamesTheSetting()
|
||||
{
|
||||
// The warning chip needs a session first: the sign-in refusal itself points at TITANO_TRUSTED_PROXIES.
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = IPAddress.Parse("172.18.0.5");
|
||||
request.Request.Scheme = "http";
|
||||
Assert.Equal("proxy_untrusted", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
Assert.Equal("https_required", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Auto }));
|
||||
Assert.Contains("TITANO_TRUSTED_PROXIES", Loc.L("Server.Error.ProxyUntrusted"));
|
||||
|
||||
request.Request.Scheme = "https";
|
||||
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
request.Request.Scheme = "http";
|
||||
request.Connection.RemoteIpAddress = IPAddress.Loopback;
|
||||
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheAdminWarnsWhenAPageDidNotComeThroughATrustedProxyOverHttps()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
|
||||
var admin = await server.AdminAsync();
|
||||
Assert.True((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning, "plain HTTP to the server's own port");
|
||||
Assert.False((await DashboardAsync(admin, "https")).ProxyWarning, "HTTPS through a trusted proxy");
|
||||
Assert.True((await DashboardAsync(admin, "http")).ProxyWarning, "plain HTTP through the proxy");
|
||||
Assert.True((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
Assert.False((await SettingsAsync(admin, "https")).ProxyWarning);
|
||||
|
||||
await using var untrusted = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = ElsewhereOnly;
|
||||
});
|
||||
var other = await untrusted.AdminAsync();
|
||||
Assert.True((await DashboardAsync(other, "https")).ProxyWarning, "a claim of HTTPS from a peer that is no trusted proxy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OtherTlsModesNeverWarn()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var admin = await server.AdminAsync();
|
||||
Assert.False((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
Assert.False((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the server's own forwarded-headers step on a request from <paramref name="peer"/> that claims to forward a
|
||||
/// client at 203.0.113.7 over HTTPS: the address and scheme the rest of the server then sees.
|
||||
/// </summary>
|
||||
private static async Task<(string? Address, bool Https)> ForwardAsync(TestServer server, string peer)
|
||||
{
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = IPAddress.Parse(peer);
|
||||
request.Request.Scheme = "http";
|
||||
request.Request.Headers["X-Forwarded-For"] = "203.0.113.7";
|
||||
request.Request.Headers["X-Forwarded-Proto"] = "https";
|
||||
var forwarded = new ForwardedHeadersMiddleware(_ => Task.CompletedTask, NullLoggerFactory.Instance,
|
||||
server.Services.GetRequiredService<IOptions<ForwardedHeadersOptions>>());
|
||||
await forwarded.Invoke(request);
|
||||
var address = request.Connection.RemoteIpAddress;
|
||||
return ((address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString(), request.Request.IsHttps);
|
||||
}
|
||||
|
||||
private static bool IsLoopback(string? address) =>
|
||||
IPAddress.TryParse(address, out var ip) && IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip);
|
||||
|
||||
private static async Task<HttpResponseMessage> LoginAsync(TestServer server, string username, string forwardedFor)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/login")
|
||||
{
|
||||
Content = JsonContent.Create(new LoginRequest(username, "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest),
|
||||
};
|
||||
request.Headers.Add("X-Forwarded-For", forwardedFor);
|
||||
return await server.Client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<DashboardDto> DashboardAsync(HttpClient admin, string? forwardedProto)
|
||||
{
|
||||
using var response = await SendAsync(admin, "/api/v1/server/dashboard", forwardedProto);
|
||||
return await response.ReadAsync(ProtocolJson.Default.DashboardDto);
|
||||
}
|
||||
|
||||
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin, string? forwardedProto)
|
||||
{
|
||||
using var response = await SendAsync(admin, "/api/v1/server/settings", forwardedProto);
|
||||
return await response.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> SendAsync(HttpClient client, string path, string? forwardedProto)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
||||
if (forwardedProto is not null) request.Headers.Add("X-Forwarded-Proto", forwardedProto);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Titano.Data;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
@@ -72,4 +74,59 @@ public sealed class StartupTests(TestContext context)
|
||||
Assert.SequenceEqual(["Database", "HttpPort", "Discovery"], options.Locked);
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres", ["TITANO_WORKERS"] = "many" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TrustedProxiesAreAddressesOrNetworks()
|
||||
{
|
||||
var root = context.CreateTempDirectory("proxies");
|
||||
// Loopback only: machines of the home network reach the HTTP port directly from private addresses.
|
||||
var defaults = ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres" }).TrustedProxyNetworks();
|
||||
foreach (var address in new[] { "127.0.0.1", "127.0.0.53", "::1" })
|
||||
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
|
||||
foreach (var address in new[] { "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "203.0.113.5" })
|
||||
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
|
||||
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_TRUSTED_PROXIES"] = "10.1.2.3, 2001:db8::/32;172.20.0.5/16",
|
||||
});
|
||||
Assert.Contains("TrustedProxies", options.Locked);
|
||||
Assert.SequenceEqual(["10.1.2.3/32", "2001:db8::/32", "172.20.0.0/16"], options.TrustedProxyNetworks().Select(n => n.ToString()));
|
||||
foreach (var invalid in new[] { "proxy.lan", "10.0.0.0/33", "fe80::1%2" })
|
||||
{
|
||||
var error = Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_TRUSTED_PROXIES"] = "127.0.0.1," + invalid,
|
||||
}));
|
||||
Assert.Contains(invalid, error.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PublicPortsComeFromTheEnvironment()
|
||||
{
|
||||
var root = context.CreateTempDirectory("public");
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_PUBLIC_HTTP_PORT"] = "18080",
|
||||
["TITANO_PUBLIC_HTTPS_PORT"] = "18443",
|
||||
});
|
||||
Assert.Equal((18080, 18443), (options.PublicHttpPort, options.PublicHttpsPort));
|
||||
Assert.Null(ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres" }).PublicHttpsPort);
|
||||
foreach (var invalid in new[] { "0", "70000", "https" })
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres", ["TITANO_PUBLIC_HTTPS_PORT"] = invalid }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HelpListsEveryVariable()
|
||||
{
|
||||
foreach (var variable in ServerOptions.EnvironmentVariables.Concat(["PUID", "PGID", "TZ"]))
|
||||
Assert.True(Regex.IsMatch(ServerCommandLine.Usage, $@"\b{variable}\b"), variable);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,11 @@ using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
@@ -89,6 +93,31 @@ public sealed class SystemEndpointTests(TestContext context)
|
||||
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
|
||||
{
|
||||
// The container listens on 8443, published on the host as 18443 (BRIEF §19.6: the template's ports are editable).
|
||||
await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 18443);
|
||||
var kestrel = server.Services.GetRequiredService<IServer>();
|
||||
var request = AdminRequest(IPAddress.Parse("10.0.0.7"));
|
||||
Assert.Equal("https://10.0.0.5:18443/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
|
||||
|
||||
server.Options.PublicHttpsPort = null;
|
||||
Assert.Equal($"https://10.0.0.5:{Assert.NotNull(server.HttpsBase).Port}/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
|
||||
Assert.Null(AdminPanel.HttpsLocation(AdminRequest(IPAddress.Loopback), server.Options, kestrel));
|
||||
}
|
||||
|
||||
private static DefaultHttpContext AdminRequest(IPAddress from)
|
||||
{
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = from;
|
||||
request.Request.Scheme = "http";
|
||||
request.Request.Host = new HostString("10.0.0.5", 18080);
|
||||
request.Request.Path = "/admin/";
|
||||
request.Request.QueryString = new QueryString("?page=jobs");
|
||||
return request;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AdminPanelRunsUnderAStrictPolicyAndIsNeverFramed()
|
||||
{
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Server.Hosting.Windows;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
|
||||
public sealed class WindowsServiceTests
|
||||
public sealed class WindowsServiceTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void CommandSwitchesAreParsedAndTheRestPassedOn()
|
||||
@@ -39,6 +41,52 @@ public sealed class WindowsServiceTests
|
||||
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Titano", "Titano.Server.exe")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Titano"));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Titano")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Titano")));
|
||||
// The test build is not under Program Files: registering it is refused, naming the folder.
|
||||
Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnyFileOrdinaryUsersCanChangeIsFound()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
|
||||
File.WriteAllBytes(Path.Combine(folder.FullName, "Titano.Server.exe"), [1]);
|
||||
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Titano.Core.resources.dll"));
|
||||
File.WriteAllBytes(satellite.FullName, [1]);
|
||||
|
||||
// Like Program Files: administrators may change the folder, users only read it.
|
||||
var locked = new DirectorySecurity();
|
||||
locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
|
||||
foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
|
||||
locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
|
||||
locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
|
||||
PropagationFlags.None, AccessControlType.Allow));
|
||||
folder.SetAccessControl(locked);
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
|
||||
// One satellite assembly users may replace is enough: the service would load it as SYSTEM.
|
||||
var open = satellite.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
|
||||
satellite.SetAccessControl(open);
|
||||
Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheDispatcherDeclinesAConsoleProcess()
|
||||
|
||||
Reference in new issue
Block a user