Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ Die Dokumentation ist nach Themen in Unterordner `docs/` aufgeteilt:
2. Keycloak-Provider bauen: `./gradlew :keycloak-provider:keycloakProviderJar`
3. Stack starten: `docker-compose up -d`
4. Proxy lokal starten (Profil `local`)
5. Im IDP https://idp.element.traefik.me/admin mit (`admin`/ `admin`) einloggen und im `pgk` Realm neue User anlegen.
5. Unter https://element.traefik.me mit diesen Usern anmelden und loslegen.
5. Im IDP https://idp.traefik.me/admin mit (`admin`/ `admin`) einloggen und im `pgk` Realm neue User anlegen.
6. Unter https://element.traefik.me mit diesen Usern anmelden und loslegen.

Ausführliche Schritte: [docs/setup.md](docs/setup.md).

Expand Down
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

plugins {
id("org.springframework.boot") version "4.1.0"
id("org.springframework.boot") version "4.1.2"
id("io.spring.dependency-management") version "1.1.7"
kotlin("jvm") version "2.3.10"
kotlin("plugin.spring") version "2.3.10"
Expand Down
5 changes: 5 additions & 0 deletions config/squid/conf/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM ubuntu/squid:latest

RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends python3 \
&& rm -rf /var/lib/apt/lists/* \
105 changes: 105 additions & 0 deletions config/squid/conf/matrix_origin_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""
Squid external ACL helper: allow only if the Matrix federation
Authorization header's origin= is in a dstdomain-style whitelist.
The whitelist is read once at startup; Squid restarts helpers on reconfigure.

Input (per line): <url-escaped Authorization header value, or "-">
Output (per line): OK|ERR log=<reason>
"""


# Copyright 2026 MA 01 - Wien Digital
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import sys
from urllib.parse import unquote

WHITELIST = "/etc/squid/dynamic/whitelist.txt"

SCHEME = re.compile(r"^\s*X-Matrix\s+(.*)$", re.I | re.S)
PARAM = re.compile(r'([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*("(?:[^"\\]|\\.)*"|[^,\s"]*)')
HOST_OK = re.compile(r"^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$")


def load_whitelist(path):
"""dstdomain semantics: 'example.org' = exact, '.example.org' = domain + subdomains."""
exact, suffix = set(), set()
try:
with open(path, encoding="utf-8") as f:
for line in f:
entry = line.split("#", 1)[0].strip().lower().rstrip(".")
if not entry:
continue
if entry.startswith("."):
suffix.add(entry[1:])
else:
exact.add(entry)
except OSError as e:
# Fail closed: empty list denies everything, but say why
print(f"whitelist unreadable: {e}", file=sys.stderr, flush=True)
print(f"whitelist loaded: {len(exact)} exact, {len(suffix)} suffix entries",
file=sys.stderr, flush=True)
return exact, suffix


def allows(host, exact, suffix):
if host in exact or host in suffix:
return True
labels = host.split(".")
return any(".".join(labels[i:]) in suffix for i in range(1, len(labels)))


def extract_origin(header):
"""Return (origin_host, None) or (None, reason)."""
if not header or header == "-":
return None, "no-auth-header"
m = SCHEME.match(header)
if not m:
return None, "not-x-matrix"
origins = [v for k, v in PARAM.findall(m.group(1)) if k.lower() == "origin"]
if len(origins) != 1: # none, or duplicated/smuggled
return None, "origin-count-%d" % len(origins)
origin = origins[0].strip('"').strip().lower()
if origin.startswith("["):
return None, "ip-literal"
host, sep, port = origin.rpartition(":")
if sep and port.isdigit():
origin = host
origin = origin.rstrip(".")
if not HOST_OK.match(origin):
return None, "bad-origin"
return origin, None


def main():
exact, suffix = load_whitelist(WHITELIST)
for line in sys.stdin:
try:
origin, err = extract_origin(unquote(line.rstrip("\r\n")))
if err:
reply = "ERR log=%s" % err
elif allows(origin, exact, suffix):
reply = "OK log=allowed:%s" % origin
else:
reply = "ERR log=denied:%s" % origin
except Exception as e: # always fail closed
print(f"helper error: {e!r}", file=sys.stderr, flush=True)
reply = "ERR log=helper-error"
print(reply, flush=True)


if __name__ == "__main__":
main()
32 changes: 28 additions & 4 deletions config/squid/conf/squid.conf
Original file line number Diff line number Diff line change
@@ -1,16 +1,40 @@
acl inbound_whitelist dst 172.16.0.0/12
# ---------- ACLs ----------
acl outbound_whitelist dstdomain "/etc/squid/dynamic/whitelist.txt"
acl federation_ports port 8448 443
acl CONNECT method CONNECT

http_access deny !inbound_whitelist
# Reverse-proxy ACLs
acl reverse_port localport 3129
acl matrix-inbound dstdomain matrix.traefik.me
# Inbound federation origin check
external_acl_type matrix_origin ttl=0 negative_ttl=0 children-max=5 children-startup=1 %>ha{Authorization} /usr/local/bin/matrix_origin_helper.py
acl fed_origin_ok external matrix_origin
# Unauthenticated endpoints remote servers must be able to reach
acl fed_public_paths urlpath_regex -i ^/_matrix/key/v2/server(/|$) ^/_matrix/federation/v1/version$

# ---------- Ports ----------
# Forward proxy (outbound CONNECT), unchanged
http_port 3128
# Reverse proxy / accelerator for Traefik -> Matrix
http_port 3129 accel vhost defaultsite=matrix.traefik.me

# ---------- Origin server ----------
cache_peer matrix parent 8448 0 no-query originserver name=matrix login=PASSTHRU

cache_peer_access matrix allow reverse_port matrix-inbound
cache_peer_access matrix deny all
never_direct allow matrix-inbound

# ---------- Access rules ----------
http_access allow reverse_port matrix-inbound fed_public_paths
http_access allow reverse_port matrix-inbound fed_origin_ok

http_access allow CONNECT outbound_whitelist federation_ports
http_access deny all

http_port 3128
cache deny all

acl denied http_status 403
logformat pgk timestamp=%tl actor=%>a action=%rm "%rm %ru HTTP/%rv" %>Hs %<st
access_log stdio:/dev/stdout pgk denied
cache_log /dev/null
cache_log /dev/null
16 changes: 13 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ services:
extra_hosts:
- "partner.traefik.me:host-gateway"
networks:
- messaging-net
messaging-net:
aliases:
- matrix.traefik.me

# Matrix initialization - generate signing key, build CA bundle and set permissions
matrix-init:
Expand Down Expand Up @@ -455,7 +457,6 @@ services:
messaging-net:
aliases:
- idp.traefik.me
- matrix.traefik.me
- element.traefik.me
- partner.traefik.me
partner-net:
Expand All @@ -466,16 +467,22 @@ services:
- matrix.traefik.me

egress-proxy:
image: ubuntu/squid:latest
build:
context: ./config/squid/conf
dockerfile: Dockerfile
container_name: egress-proxy
restart: unless-stopped
entrypoint: [ "/bin/sh", "-c" ]
depends_on:
matrix:
condition: service_healthy
command:
- |
rm -f /run/squid.pid
mkdir -p /etc/squid/dynamic
touch /etc/squid/dynamic/whitelist.txt
chmod 666 /dev/stdout /dev/stderr
chmod 550 /usr/local/bin/matrix_origin_helper.py
echo "[$(date)] Starting Squid..."
squid -f /etc/squid/squid.conf -NYC &
SQUID_PID=$$!
Expand All @@ -492,11 +499,14 @@ services:
done
volumes:
- ./config/squid/conf/squid.conf:/etc/squid/squid.conf:ro
- ./config/squid/conf/matrix_origin_helper.py:/usr/local/bin/matrix_origin_helper.py:ro
- ./config/squid/whitelist/:/etc/squid/dynamic
extra_hosts:
- "partner.traefik.me:host-gateway"
networks:
- messaging-net
labels:
- traefik.enable=true

networks:
messaging-net:
Expand Down
7 changes: 6 additions & 1 deletion dynamic.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ http:
rule: "Host(`matrix.traefik.me`)"
entrypoints: [federation]
tls: true
service: matrix-synapse
service: egress-proxy
# Federation to partner.traefik.me - the first hop goes to the proxy for the policy check,
# forwarded copies go straight to the partner Synapse (directly, not through Traefik). The
# legacy v1 invite endpoint is disabled by the proxy (403) and never reaches Synapse.
Expand Down Expand Up @@ -66,6 +66,11 @@ http:
loadBalancer:
servers:
- url: "http://matrix-partner:8008"
egress-proxy:
loadBalancer:
passHostHeader: true
servers:
- url: "http://egress-proxy:3129"

tls:
certificates:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class InvitationController(
return when (val evaluation = invitationControlService.evaluateInvitation(body)) {
is InvitationEvaluation.Allowed -> {
val upstream = invitationForwardPort.forwardInvite(
roomId, eventId, request.requestURI, authorization, body
roomId, eventId, request.requestURI, request.serverName, request.requestURL.toString(), authorization, body
)
ResponseEntity.status(upstream.statusCode).contentType(MediaType.APPLICATION_JSON).body(upstream.body)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 2026 MA 01 - Wien Digital
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.cloudflight.pgk.proxy.invitation.adapter.outbound

import org.springframework.context.annotation.Primary
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Component

interface OutgoingUrlMapper {
fun mapToOutgoingUrl(url: String): String
}

@Component
@Profile("local")
@Primary
internal class LocalOutgoingUrlMapper : OutgoingUrlMapper {
// override the http in the local dev setup because the PGK proxy runs outside the docker network
// but the matrix servers assume the federation is routed internally
override fun mapToOutgoingUrl(url: String): String = url.replaceFirst("http", "https")
}

@Component
internal class DefaultOutgoingUrlMapper : OutgoingUrlMapper {
override fun mapToOutgoingUrl(url: String): String = url
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,11 @@
package io.cloudflight.pgk.proxy.invitation.adapter.outbound

import io.cloudflight.pgk.proxy.config.ProxyProperties
import io.cloudflight.pgk.proxy.invitation.mapper.InvitationRequestMapper
import io.cloudflight.pgk.proxy.invitation.port.InvitationForwardPort
import io.cloudflight.pgk.proxy.shared.events.InvitationForwardFailedEvent
import io.cloudflight.pgk.proxy.shared.events.InvitationForwardedEvent
import org.springframework.context.ApplicationEventPublisher
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Component
Expand All @@ -47,25 +45,23 @@ import java.net.URI
class SynapseInvitationForwardAdapter(
private val restClient: RestClient,
private val applicationEvents: ApplicationEventPublisher,
private val requestMapper: InvitationRequestMapper,
private val outgoingUrlMapper: OutgoingUrlMapper,
private val properties: ProxyProperties
) : InvitationForwardPort {

override fun forwardInvite(
roomId: String,
eventId: String,
originalUri: String,
originalServerName: String,
originalUrl: String,
authorization: String?,
body: String,
): ResponseEntity<String> {
val destination = try {
requestMapper.fromPdu(body).recipient.domain
val destination = if (isInboundRequest(originalServerName)) {
buildDestination(originalUri)
} catch (e: IllegalArgumentException) {
applicationEvents.publishEvent(
InvitationForwardFailedEvent(roomId, eventId, "unknown", "invite PDU has no recipient")
)
return ResponseEntity.status(HttpStatus.BAD_GATEWAY).build()
} else {
outgoingUrlMapper.mapToOutgoingUrl(originalUrl)
}
return try {
val request = restClient.put()
Expand Down Expand Up @@ -96,6 +92,9 @@ class SynapseInvitationForwardAdapter(
}
}

private fun isInboundRequest(originalServerName: String): Boolean =
originalServerName == properties.federation.matrixDomain

private fun buildDestination(originalUri: String): String =
properties.federation.forwardBaseUrl.trimEnd('/') + originalUri
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ interface InvitationForwardPort {
roomId: String,
eventId: String,
originalUri: String,
originalServerName: String,
originalUrl: String,
authorization: String?,
body: String,
): ResponseEntity<String>
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/application-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ pgk:
fhir:
base-url: http://localhost:8081/fhir
federation:
forward-base-url: http://localhost:18009
forward-base-url: http://localhost:18008
Loading
Loading