- Rust 99%
- Nix 0.6%
- Dockerfile 0.4%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .forgejo/workflows | ||
| docker | ||
| fpush | ||
| fpush-apns | ||
| fpush-demopush | ||
| fpush-fcm | ||
| fpush-push | ||
| fpush-ratelimit | ||
| fpush-tokenblocker | ||
| fpush-traits | ||
| fpush-ubports | ||
| fpush-unifiedpush | ||
| .dockerignore | ||
| .envrc | ||
| .gitignore | ||
| Cargo.lock | ||
| Cargo.toml | ||
| flake.lock | ||
| flake.nix | ||
| LICENSE | ||
| README.md | ||
| SECURITY.md | ||
Fpush
fpush is a scalable push server for XMPP implemetingXEP-0357.
fpush can be connected to any XMPP server as a XMPP component using XEP-0114.
Table of contents
- Features
- Usage
- XMPP API
- Configuration
- Structure
- Clustering
- Compilation
- Compilation Flags
- Expandability
- Systemd
Features
- Supported push platforms
- Apple APNS
- Google FCM
- UBPorts
- UnifiedPush
- Multi app / platform support on a single XMPP domain/JID
- Configurable token ratelimiting, and per-destination ratelimiting for client-supplied endpoints
Usage
./fpush settings.json
XMPP API
This appserver implements XEP-0357 commands for sending actual push notifications.
fpush does not require devices to register for push before usage like other appserver implementations.
fpush expects each push IQ to include the push token of the device to be woken up, as well as the info to which push module the token applies.
Hence, push messages can be enabled by a client at their XMPP server as follows:
<iq type='set' id='x43'>
<enable xmlns='urn:xmpp:push:0' jid='###pushServerComponentJid###' node='###DevicePushToken###'>
<x xmlns='jabber:x:data' type='submit'>
<field var='FORM_TYPE'><value>http://jabber.org/protocol/pubsub#publish-options</value></field>
<field var='pushModule'><value>##pushModuleName###</value></field>
</x>
</enable>
</iq>
If the pushModule identifier is missing in the publish-options, fpush will instead selected the default push module as configured.
Configuration
{
"component": {
"componentHostname": "<ComponentJid>",
"componentKey": "ARandomComponentKeySetInsideTheXMPPServer",
"serverHostname": "<XMPP-Server>",
"serverPort": <XMPP-Server Component Port>
},
"pushModules": { // map of configured push modules
"monalProdiOS": { // push module identifier that is later set inside the push iqs as "pushModule"
"type": "apple", // push module type
"is_default_module": true, // Use this push module in case no pushModule was defined in a push iq msg
"apns": {
"certFilePath": "<Path to p12 file>",
"certPassword": "<cert password>",
"topic": "<app bundle id>"
},
"ratelimit": {
"ratelimitTime": "20s", // minimal duration between two pushes
"ratelimitCleanupInterval": "300s", // time how long old and unseen tokens should be keept inside the ratelimit cache before removal
"enabled": true // optionally disable ratelimit. Not advised for apple apns
}
},
"someAndroidApp": {
"type": "google",
"is_default_module": false,
"fcm": {
"fcmSecretPath": "<Path to json from google>"
}
},
"unifiedPushClients": {
"type": "unifiedpush",
"is_default_module": false,
"unifiedpush": {
"allowedEndpoints": ["updates.push.services.mozilla.com", "*.ntfy.sh"],
"ttl": 900,
"urgency": "normal",
"vapidPrivateKeyPath": "<Path to a PEM P-256 private key>",
"vapidContactEmail": "admin@example.org",
"domainRatelimit": { // per-destination budget, see below
"burst": 200,
"refillPerSecond": 50,
"enabled": true
}
}
},
},
"timeout": {
"xmppconnectionError": "20s" // time to wait after XMPP component connection failed before reconnecting
}
}
The configuration file consists of three sections.
XMPP component settings (component) the push module configurations (pushModules) and a timeout config for the xmpp connection (timeout).
component
This section describes all config parameters for the XMPP component connection to the XMPP server handling all S2S connections.
componentHostname
JID of the pushserver. Must match the component JID configured on the XMPP server.
componentKey
The component handshake element as configured on the XMPP server
serverHostname
Hostname or IP address of the XMPP component endpoint (Usually the XMPP server that handles all S2S connections)
serverPort
Port of the XMPP component endpoint configured on the XMPP server.
pushModules
Map of all push modules that should be loaded on start.
Each push module is identified by the key specified in the map.
This identifier is later used by clients to specifiy which of the configured push modules should be selected when an XMPP IQ is received by fpush.
Each push module consists of a type element.
Currently apple, google, ubports and unifiedpush are supported, subject
to the features the binary was compiled with.
is_default_module
If set to true, this push modules is used if an XMPP IQ was received that does not include any push module identifier. Only one push module can be configured as the default module.
ratelimit
Ratelimits for push tokens can be configured per push module.
enabled
Enable or disable ratelimiting for tokens It is not advised to disable the ratelimiting
ratelimitTime
Minimal time between pushes for each push token.
If two push IQs are received for the same token within less time, the latter one is queued.
If more push request arrive for a token, while one push request is already queued, all further requests are ignored and an wait IQ is replied until the configured ratelimitTime is over.
minTokenLength / maxTokenLength
Push tokens outside this length range are dropped. Defaults are 16 and 1200,
wide enough for both fixed-length device tokens and UnifiedPush endpoint URLs
with encryption keys appended.
ratelimitCleanupInterval
fpush caches the last timestamp when an push messages was sent for an token per push module to implement the ratelimit.
This cache is cleaned every 300 seconds.
On each cleaning run, tokens that were send more than ratelimitCleanupInterval ago are removed to free up memory space.
apns
This section describes all apns related push options.
`certFilePath``
Path to the p12 certificate that should be used to connect to the APNS API.
certPassword
Passwort of the p12 certificate.
topic
Bundle ID of the main app.
environment
APNS environment to use. Supports production and sandbox. Default: production
fcm
This section describes all fcm related push options.
fcmSecretPath
Path to the fcm json file created by google.
unifiedpush
This section describes all UnifiedPush related push options.
The push token for this module is not opaque data. It is the UnifiedPush
endpoint URL the client got from its distributor, and it decides where fpush
sends the HTTP request. Clients register it as the XEP-0357 push node:
<enable xmlns='urn:xmpp:push:0' jid='###pushServerComponentJid###'
node='https://ntfy.sh/UPabc123?up=1'>
To get an encrypted payload, a client appends its RFC 8291 key material to the
node, separated by |:
<endpoint>|<p256dh>|<auth>
<enable xmlns='urn:xmpp:push:0' jid='###pushServerComponentJid###'
node='https://updates.push.services.mozilla.com/wpush/v2/gAAA|BNcRd...|k9Fz...'>
p256dh is the subscription's uncompressed P-256 public key, auth its 16 byte
auth secret. Both are base64, padded or unpadded, URL-safe or standard alphabet.
Both must be given together. | cannot appear unescaped in a URL, so it cannot
collide with the endpoint.
With both keys present, fpush encrypts the body with aes128gcm per RFC 8291
and sends Content-Encoding: aes128gcm. With a bare endpoint it sends the body
as-is.
The client picks the destination, so this module can be aimed at hosts the
operator never chose. It only accepts https, does not follow redirects,
refuses addresses that are not globally reachable, and limits how much traffic
one destination can receive. See additionalBlockedIpRanges and
domainRatelimit.
A full endpoint URL is enough to push to that device, so it is never logged.
Lines about requests fpush refuses show the scheme and host, so the target
of abuse can be identified: a failed discovery probe, an allowlist miss, a
blocked address, a ratelimit refusal, or a full tracking table. Everything
else, including errors returned by a push server, shows a keyed pseudonym of
the host in the form <word-word-word-word>. Host and JID pseudonyms are keyed
with a random secret made at startup and never stored, so nobody, the operator
included, can map a pseudonym back to a host or account. Pseudonyms change on
restart. JIDs are logged in plaintext (bare, without the token) only when a
UnifiedPush challenge request is rate-limited or rejected, or when an account
pushes to more than 5 distinct tokens or sends more than 6000 pushes within an
hour. That per-account count is held in memory only, as token digests, and is
dropped when its hour ends.
Endpoint validation
Any federated server can name any URL as a push token, so fpush checks that an
endpoint belongs to a real client before it keeps sending there. This follows
the UnifiedPush guidance for application servers, which exists to stop a push
server being used for DoS amplification.
The first push to an unknown endpoint carries a challenge instead of the wake-up:
{"message":{"type":"registration-challenge","challenge":"<22 chars>"}}
The client sends the value back in the challenge field of the
urn:agnos:fpush:validate-unifiedpush:0 ad-hoc command. After that the endpoint
gets normal wake-ups. Before that its pushes are suppressed, so a client that
does not implement this command will not receive pushes.
urn:agnos:fpush:request-unifiedpush-challenge:0 requests a new challenge, at
most once per five minutes per endpoint.
A challenge is valid for 60 seconds. A confirmed endpoint is kept for 30 days of disuse. The challenge is encrypted when the token carries keys and sent in the clear when it does not.
allowedEndpoints
List of host globs this module may deliver to, for example
["updates.push.services.mozilla.com", "*.ntfy.sh"]. Matching is anchored, so
*.ntfy.sh does not accept ntfy.sh.evil.com.
Defaults to an empty list, which permits any public host. The address restrictions apply either way. Set this if you know which push servers your users rely on.
With probeUnlistedEndpoints the list no longer excludes anything. It names
the hosts trusted without a discovery probe instead.
probeUnlistedEndpoints
Accepts hosts outside allowedEndpoints that answer UnifiedPush discovery.
Default: false.
Before the first challenge to an unlisted host, fpush sends a GET to the
endpoint URL, query included, and requires {"unifiedpush":{"version":1}} in
reply, as the UnifiedPush server spec defines. A pass is cached for 24 hours
and a failure for 10 minutes. A host that does not pass is refused without
retiring the token.
This lets users bring any self-hosted ntfy, NextPush or other UnifiedPush
server, while a URL pointing at an unrelated host never receives a challenge.
Mozilla's autopush (updates.push.services.mozilla.com, used by Sunup) does not
answer discovery, so list it in allowedEndpoints to keep supporting it.
"allowedEndpoints": ["ntfy.sh", "updates.push.services.mozilla.com"],
"probeUnlistedEndpoints": true
ttl
How long the push server should retain an undelivered message, in seconds.
Default: 900.
urgency
RFC 8030 urgency: very-low, low, normal or high. Default: normal.
topic
Optional RFC 8030 topic. A push server may use it to collapse undelivered wake-ups for the same device instead of queueing all of them. Unset by default.
body
Request body. Defaults to the same wake-up payload the ubports module
delivers:
{"message":{"type":"xmpp-wake"}}
Set it to a literal string to send something else, or to null for a
payloadless push.
How it is sent depends on the token:
- Token with
p256dhandauth: encrypted withaes128gcmper RFC 8291. Web Push servers such as Mozilla'supdates.push.services.mozilla.comcheckContent-Encodingon any body and accept only this. - Bare endpoint token: sent as-is. Push servers that relay bodies verbatim (ntfy, NextPush and other UnifiedPush v2 era distributors) pass it to the client unchanged.
null sends no body at all. RFC 8030 allows this and it skips encryption even
for a token with keys, but it is not a reliable wake-up. UnifiedPush requires a
push message to be 1 to 4096 bytes, so a distributor may drop a zero byte one,
and ntfy replaces an empty body with its own default text (triggered).
UnifiedPush also requires payloads to be encrypted, whether or not they carry anything sensitive, and a conformant client drops anything else. Keys in the token are the only option a current distributor is sure to accept. The plaintext and payloadless paths are for v2 era apps that never implemented encryption.
A custom body must leave room for encryption. The 4096 byte limit allows 3993
bytes of cleartext. fpush warns at startup if the configured body is longer.
contentType
Content-Type sent with an unencrypted body. Default: application/json.
Ignored when body is null and when the token carries keys, since an
encrypted payload is always sent as application/octet-stream.
requestTimeout
Timeout for a single push request. Default: 10s.
vapidPrivateKeyPath
Path to a PEM-encoded P-256 private key, used to sign requests with VAPID (RFC 8292). Unset by default, which is usually fine, as most distributors do not ask for it. A missing or unparsable key file stops startup instead of silently disabling signing.
VAPID is needed when the subscription was created with an application server
key. A push server given that key at subscription time rejects requests signed
with any other key, and unsigned requests. The client and fpush then have to
use the same keypair.
Generate a key with:
openssl ecparam -genkey -name prime256v1 -noout -out vapid.pem
Clients register the matching public key as their application server key.
fpush logs it at startup in the base64url form clients expect:
INFO fpush_unifiedpush::push] unifiedpush: VAPID public key (register this as
the application server key): BMexr6f8aAiEWxVGOd-4NK-Vk-2l...
vapidContactEmail
Address published in the VAPID sub claim so push server operators can reach
you. Only used when vapidPrivateKeyPath is set.
caCertPath
Path to a PEM certificate bundle to trust in addition to the built-in root certificates, for a self-hosted push server behind a private CA. Unset by default. It adds to the trust store instead of replacing it and does not relax certificate verification. An endpoint with an untrusted certificate is still refused.
additionalBlockedIpRanges
Extra CIDR ranges to refuse. These are added to the built-in list, not a replacement for it. Use it for globally routable address space that is only reachable inside your own network:
"additionalBlockedIpRanges": ["<your own public prefix routed internally>"]
Private space does not need an entry. RFC 1918, loopback, CGNAT, link-local including cloud metadata, the TEST-NETs, benchmarking, multicast and reserved space are all refused by default.
The UnifiedPush guidance is to refuse any endpoint that does not resolve to a
globally reachable address. For IPv6 that is applied directly: only 2000::/3,
the range IANA assigns for global unicast, is accepted. IPv4 has no single
equivalent prefix, so its non-global space is listed out from the IANA
Special-Purpose Address Registry.
6to4 (2002::/16) and NAT64 (64:ff9b::/96) are refused even though they are
globally routable, because both embed an IPv4 address that can point inward.
2002:7f00:0001:: is 127.0.0.1. The embedded address is decoded and checked
by the same rules.
Built-in ranges cannot be removed. Use allowPrivateIps to reach a private
address. The older blockedIpRanges key replaced the built-in list instead of
extending it, and a config still using that name is rejected at startup.
domainRatelimit
Budget per destination host, as a token bucket:
"domainRatelimit": {
"burst": 200, // requests one host may absorb at once
"refillPerSecond": 50, // rate that allowance is earned back at
"enabled": true
}
The ratelimit section above counts per push token, which does not bound this
module. The sender writes the token, so https://victim/1 and
https://victim/2 count separately while pointing at one host. This limit
counts per host instead.
Requests over budget are refused, not queued, and the token is not penalised for it, since one destination is shared by every device using that provider.
Hosts are counted by registrable domain, so a.example.org and
b.example.org share one budget and wildcard DNS buys no extra allowance.
Hosting suffixes on the Public Suffix List, such as github.io, keep their
tenants apart. IPv6 literals are counted per /64. Matching ignores case and
the port.
The defaults are high, because a refused request is a lost notification. 50/s
sustained covers a few thousand devices on one provider. Lower it if you know
which push servers your users use.
This budget covers delivery to endpoints that have already validated. Validation
challenges draw on challengeRatelimit instead.
challengeRatelimit
Budget per destination host for validation challenges, in the same form as
domainRatelimit. Default: burst 50, 5/s.
Held tighter than delivery because abuse can only ever appear here. Whoever
names someone else's URL as a push token cannot read what arrives there, so they
can never confirm the challenge and their traffic never reaches the delivery
path. A real endpoint passes through once and then uses domainRatelimit.
Note that validation state is held in memory, so a restart makes every endpoint re-validate. On a large deployment concentrated on one provider that takes a while at the default rate. Raise it if pushes are slow to resume after a restart.
globalRatelimit
One budget shared by every destination for delivery, in the same form as
domainRatelimit. Default: burst 500, 200/s.
The per-host budgets do not bound a spray across many different hosts, so this caps total outbound work regardless of how many destinations are involved. It is a backstop rather than a fairness mechanism, set well above what any real deployment sends. Lower it to match your user count if you want a tighter bound.
challengeGlobalRatelimit
One budget shared by every destination for challenges and discovery probes, in
the same form as domainRatelimit. Default: burst 50, 10/s.
Kept apart from globalRatelimit so a spray of challenges, which any sender can
trigger, cannot starve delivery to endpoints that have already validated.
probeRatelimit
Budget per destination for discovery probes, counted like domainRatelimit.
Default: burst 5, 0.1/s. Only spent on hosts without a cached verdict.
allowPrivateIps
Disables all address restrictions, including the IPv6 global unicast requirement. Intended for testing against a push server on localhost. Leaving it enabled in production lets any federated XMPP server drive requests into your internal network.
timeout
xmppconnectionError
Time to wait after XMPP component connection failed before reconnecting
Structure
Fpush connects to a single XMPP server, that handles all S2S connections, as a XMPP component using an unencrypted connection.
We thus recommend to either place fpush on the same system as the XMPP server or securing the connection between the systems using IPsec or wireguard.
If the XMPP server is unreachable fpush will automatically try to reconnect after the configured time.
Clustering
fpush can be clustered by simply running multiple servers on the same XMPP domain.
Using SRV records S2S traffic can be steered between the servers.
fpush currently does not exchange ratelimit information betweeen cluster nodes.
Instead each node manages its own independent ratelimit.
Hence, devices that are registered on more than on XMPP server may, receive push notifications via more than one cluster more frequent than expected.
Compilation
fpush is written in Rust. (https://www.rust-lang.org/tools/install)
Debug build
cargo build
Release build
cargo build --release
Compilation Flags
fpush supports several features that can be activated while building using the --features <Flag1>,<Flag2> flag.
Default features
Currently the following features are enabled by default.
enable_ubports_supportenable_unifiedpush_support
These are features of the fpush-push crate rather than of the fpush binary, so
select them from the workspace root or with -p fpush-push:
cargo build --features enable_ubports_support
cargo build -p fpush --features <Flag> does not work, because fpush declares no
features of its own.
enable_unifiedpush_support cannot currently be switched off. The XMPP layer calls the
UnifiedPush ad-hoc command handlers without gating them, so a build without it does not
compile.
Logging
release_max_level_warn
Remove all log messages lower than "WARN" from binary to increase speed.
release_max_level_info
Remove all log messages lower than "INFO" from binary to increase speed.
Push module support
Push modules support for different push vendors can be enabled during compilation. For improved performance it is adviced to only enable/compile the needed push modules types.
The fcm, apns and demo modules below are not currently available: their crates are
not workspace members, so asking for their features is an error.
enable_fcm_support
Enable google fcm support for android devices.
enable_apns_support
Enable apple apns support for iOS, iPadOS and macOS devices.
enable_demo_support
Enable a simple demo push endpoint used during development.
enable_ubports_support
Enable UBPorts push support, delivering wake-ups through the UBPorts push service.
enable_unifiedpush_support
Enable UnifiedPush support, delivering wake-ups to endpoint URLs supplied by
clients. See the unifiedpush configuration section for the restrictions that
apply to those endpoints.
random_delay_before_push
Improve ratelimit acurracy by waiting a random delay before handling each push message.
For each incomming push event fpush spawns a new tokio thread. Within each thread fpush checks if the supplied token is blocked or if the token is ratelimited. After a push message was sent for a token, fpush ratelimits the token (if configured) for a configured time to reduce the battery consumption of the remote device. Due to the multi thread design, two directly consecutive push events for the same token may not be correctly ratelimited. Hence, adding a random async delay helps to improve the accuracy while keeping memory and cpu consumption low.
Expandability
Fpush can easily be expanded to support further push platforms by creating a new crate implementing the PushTrait.
Systemd
We recommend running fpush as a seperate user without root permissions.
[Unit]
Description=Fpush
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=10
User=fpush
Group=fpush
LimitNOFILE=131072
WorkingDirectory=/opt/fpush/
Environment=RUST_LOG=info
ExecStart=/opt/fpush/fpush settings.json
[Install]
WantedBy=multi-user.target