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
26 changes: 26 additions & 0 deletions .github/workflows/backend-ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,29 @@ jobs:

- name: Run test suite
run: composer run-script --timeout=600 test

varnish-vcl-tests:
Comment thread
konradoboza marked this conversation as resolved.
Resolved
name: Varnish VCL tests
runs-on: "ubuntu-26.04"
timeout-minutes: 20

steps:
- uses: actions/checkout@v7

# Builds varnish-modules from source, as the xkey vmod is not packaged for Varnish 6.0LTS.
- name: Build varnishtest image
run: docker build -t ibexa-varnishtest:6.0 tests/varnish

- name: Run varnishtest suite
env:
IMAGE: ibexa-varnishtest:6.0
run: tests/varnish/run.sh

- name: Build Varnish 9 varnishtest image
run: docker build -t ibexa-varnishtest:9 -f tests/varnish/Dockerfile-9 tests/varnish

- name: Run varnishtest suite against varnish9.vcl
env:
IMAGE: ibexa-varnishtest:9
VCL: resources/upsun/common/5.0/.platform/varnish9.vcl
run: tests/varnish/run.sh
23 changes: 22 additions & 1 deletion resources/upsun/common/5.0/.platform/varnish.vcl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//import std;
import xkey;

// Includes not available on Platform.sh, so inlining parameters.vlc:
// Includes not available on Platform.sh, so inlining parameters.vcl:
acl invalidators {
"127.0.0.1";
"192.168.0.0"/16;
Expand All @@ -32,6 +32,27 @@ sub vcl_recv {
// Add a Surrogate-Capability header to announce ESI support.
set req.http.Surrogate-Capability = "abc=ESI/1.0";

// Stop clients from injecting reverse proxy headers, as the application trusts them once
// framework.trusted_proxies is configured.
//
// The Ibexa Cloud router is authoritative for X-Forwarded-Proto, X-Client-IP and Client-Cdn,
// and discards the values a client sends for them, so those are kept as is.
// See https://fixed.docs.upsun.com/development/headers.html
//
// The headers below are not filtered by the router, so strip them here:
unset req.http.Forwarded;
unset req.http.X-Forwarded-Host;
unset req.http.X-Forwarded-Prefix;

// X-Forwarded-For is only appended to by the router, so any leading entry is what the client
// sent. X-Client-IP is always set by the router, and holds the end-user IP also when the
// request came in via a CDN, so use that as the only value.
if (req.http.X-Client-IP) {
set req.http.X-Forwarded-For = req.http.X-Client-IP;
} else {
unset req.http.X-Forwarded-For;
}

// Ensure that the Symfony Router generates URLs correctly with Varnish
if (req.http.X-Forwarded-Proto == "https" ) {
set req.http.X-Forwarded-Port = "443";
Expand Down
21 changes: 21 additions & 0 deletions resources/upsun/common/5.0/.platform/varnish9.vcl
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,27 @@ sub vcl_recv {
// Add a Surrogate-Capability header to announce ESI support.
set req.http.Surrogate-Capability = "abc=ESI/1.0";

// Stop clients from injecting reverse proxy headers, as the application trusts them once
// framework.trusted_proxies is configured.
//
// The Ibexa Cloud router is authoritative for X-Forwarded-Proto, X-Client-IP and Client-Cdn,
// and discards the values a client sends for them, so those are kept as is.
// See https://fixed.docs.upsun.com/development/headers.html
//
// The headers below are not filtered by the router, so strip them here:
unset req.http.Forwarded;
unset req.http.X-Forwarded-Host;
unset req.http.X-Forwarded-Prefix;

// X-Forwarded-For is only appended to by the router, so any leading entry is what the client
// sent. X-Client-IP is always set by the router, and holds the end-user IP also when the
// request came in via a CDN, so use that as the only value.
if (req.http.X-Client-IP) {
set req.http.X-Forwarded-For = req.http.X-Client-IP;
} else {
unset req.http.X-Forwarded-For;
}

// Ensure that the Symfony Router generates URLs correctly with Varnish
if (req.http.X-Forwarded-Proto == "https" ) {
set req.http.X-Forwarded-Port = "443";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,46 +15,27 @@

final class TrustedHeaderClientIpEventSubscriber implements EventSubscriberInterface
{
private const string PLATFORM_SH_TRUSTED_HEADER_CLIENT_IP = 'X-Client-IP';

public function __construct(
private readonly ?string $trustedHeaderName
) {}

public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', PHP_INT_MAX - 1],
KernelEvents::REQUEST => ['onKernelRequest', PHP_INT_MAX],
];
}

public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();

$trustedProxies = Request::getTrustedProxies();
$trustedHeaderSet = Request::getTrustedHeaderSet();

$trustedHeaderName = $this->trustedHeaderName;
if (null === $trustedHeaderName && $this->isUpsunProxy($request)) {
$trustedHeaderName = self::PLATFORM_SH_TRUSTED_HEADER_CLIENT_IP;
}

if (null === $trustedHeaderName) {
// -1 means framework.trusted_proxies is not configured; passing it on would trust every forwarded header
if ($trustedHeaderSet === -1) {
return;
}

$trustedClientIp = $request->headers->get($trustedHeaderName);

if (null !== $trustedClientIp) {
if ($trustedHeaderSet !== -1) {
$trustedHeaderSet |= Request::HEADER_X_FORWARDED_FOR;
}
$request->headers->set('X_FORWARDED_FOR', $trustedClientIp);
if ($this->isUpsunProxy($request) && $request->headers->get('Client-Cdn') === 'fastly') {
/** @var int<0, 63> $trustedHeaderSet */
Request::setTrustedProxies(['REMOTE_ADDR'], $trustedHeaderSet);
}

/** @var int<0, 63> $trustedHeaderSet */
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet);
}

private function isUpsunProxy(Request $request): bool
Expand Down
6 changes: 6 additions & 0 deletions src/bundle/Resources/config/services/event_subscribers.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
services:
_defaults:
autowire: true
autoconfigure: true

Ibexa\Bundle\Cloud\EventSubscriber\TrustedHeaderClientIpEventSubscriber: ~
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
<?php

/**
* @copyright Copyright (C) Ibexa AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);

namespace Ibexa\Tests\Bundle\Cloud\EventSubscriber;

use Ibexa\Bundle\Cloud\EventSubscriber\TrustedHeaderClientIpEventSubscriber;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;

/**
* @covers \Ibexa\Bundle\Cloud\EventSubscriber\TrustedHeaderClientIpEventSubscriber
*/
final class TrustedHeaderClientIpEventSubscriberTest extends TestCase
{
private const string REAL_CLIENT_IP = '98.76.123.234';

// framework.trusted_headers default
private const int TRUSTED_HEADER_SET = Request::HEADER_X_FORWARDED_FOR
| Request::HEADER_X_FORWARDED_PORT
| Request::HEADER_X_FORWARDED_PROTO;

/** @var string[] */
private array $originalTrustedProxies;

private int $originalTrustedHeaderSet;

private mixed $originalRemoteAddr;

protected function setUp(): void
{
parent::setUp();

$this->originalTrustedProxies = Request::getTrustedProxies();
$this->originalTrustedHeaderSet = Request::getTrustedHeaderSet();
$this->originalRemoteAddr = $_SERVER['REMOTE_ADDR'] ?? null;

// Request::setTrustedProxies() resolves 'REMOTE_ADDR' from $_SERVER, not from the request
$_SERVER['REMOTE_ADDR'] = self::REAL_CLIENT_IP;
Request::setTrustedProxies([], self::TRUSTED_HEADER_SET);
}

protected function tearDown(): void
{
$_SERVER['REMOTE_ADDR'] = $this->originalRemoteAddr;

/** @var int<0, 63> $trustedHeaderSet */
$trustedHeaderSet = $this->originalTrustedHeaderSet;
Request::setTrustedProxies($this->originalTrustedProxies, $trustedHeaderSet);

parent::tearDown();
}

/**
* @return iterable<string, array{bool, array<string, string>, array<string, mixed>}>
*/
public static function getTrustedHeaderEventSubscriberTestData(): iterable
{
yield 'request from random client received outside Ibexa Cloud' => [
false,
[],
[],
];

yield 'request from random client, forging Client-Cdn, received outside Ibexa Cloud' => [
false,
['Client-Cdn' => 'fastly'],
[],
];

yield 'request from random client received on Ibexa Cloud' => [
false,
[],
['PLATFORM_RELATIONSHIPS' => true],
];

yield 'request via Fastly received on Ibexa Cloud' => [
true,
['Client-Cdn' => 'fastly'],
['PLATFORM_RELATIONSHIPS' => true],
];
}

/**
* @dataProvider getTrustedHeaderEventSubscriberTestData
*
* @param array<string, string> $headers
* @param array<string, mixed> $server
*/
public function testTrustedHeaderEventSubscriberWithTrustedProxy(
bool $isFromTrustedProxy,
array $headers,
array $server
): void {
$request = $this->dispatchRequestEvent($headers, $server);

self::assertSame($isFromTrustedProxy, $request->isFromTrustedProxy());
self::assertSame(self::TRUSTED_HEADER_SET, Request::getTrustedHeaderSet());
}

public function testTrustedHeaderEventSubscriberWithoutTrustedProxiesConfigured(): void
{
// framework.trusted_proxies not configured, so Symfony never sets a trusted header set
// @phpstan-ignore argument.type
Request::setTrustedProxies([], -1);

$request = $this->dispatchRequestEvent(
[
'Client-Cdn' => 'fastly',
'X-Forwarded-Host' => 'forged.example.com',
],
['PLATFORM_RELATIONSHIPS' => true]
);

self::assertFalse($request->isFromTrustedProxy());
self::assertSame('localhost', $request->getHost());
}

/**
* @param array<string, string> $headers
* @param array<string, mixed> $server
*/
private function dispatchRequestEvent(
array $headers,
array $server
): Request {
$eventDispatcher = new EventDispatcher();
$eventDispatcher->addSubscriber(new TrustedHeaderClientIpEventSubscriber());

$request = Request::create('/', Request::METHOD_GET, [], [], [], array_merge(
$server,
['REMOTE_ADDR' => self::REAL_CLIENT_IP],
));
$request->headers->add($headers);

$event = $eventDispatcher->dispatch(new RequestEvent(
$this->createMock(KernelInterface::class),
$request,
HttpKernelInterface::MAIN_REQUEST
), KernelEvents::REQUEST);

return $event->getRequest();
}
}
45 changes: 45 additions & 0 deletions tests/varnish/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Image for running the varnishtest suite in tests/varnish/.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@micszo
I need to include new Dockerfile for varnish here ( and in post-install too) which is almost carbon copy of https://github.com/ibexa/docker/blob/v4.6.31/docker/Dockerfile-varnish

I suggest we change the structure of the varnish image in order to make it more general and re-usable. However, that would imply a BC break so not sure if we can do it before 6.0, or if this docker files are "supported" and BC guaranteed .

What I suggest is: In ibexa/docker we could:

  • Remove the COPY lines of default.vcl and parameters.vcl - So this is not part of the image itself
  • Change so that varnish.yml contain the basic common configuration needed for varnish container
  • Change so that varnish.yml uses image: instead of build:
  • change varnish7.yml ( and in near future varnish9,yml) so that they are overlays for varnish.yml, only containing version specific information ( including volumes to mount the vcls an referencing varnish7 image )
  • We add job in docker to push images to ghcr.io, as we already do for PHP images.
  • CI in ibexa/cloud and ibeax/post-install can then create varnish container without duplicated dockerfile

It is a lot of things to do for just removing some duplicated code though ( but keep in mind that it is not only here in ibexa/cloud and ibeax/post-install we get rid of duplicated code). The Dockerfile-varnish* and varnish*.yml files in ibexa/docker also contains a lot of duplicated code

BC breaks are:

  • varnish.yml will use volumes to load vcl files.
  • varnish.yml will use image: instead of build
    If varnish files doc/docker are used as-is, no problem. However, this might break local workflows and customizations.

#
# Mirrors doc/docker/Dockerfile-varnish from ibexa/docker. It has to be Varnish 6.0LTS specifically:
# this VCL returns "miss" from vcl_hit, which 6.5 and later reject. The xkey vmod is not packaged
# for 6.0LTS, so varnish-modules is built from source, as in the image this mirrors.

FROM debian:bookworm-slim

ENV DEBIAN_FRONTEND=noninteractive

ARG PACKAGECLOUD_URL=https://packagecloud.io/install/repositories/varnishcache/varnish60lts/script.deb.sh
ARG VARNISH_MODULES_VERSION=0.15.0

RUN set -xe \
&& buildDeps=" \
make \
automake \
autotools-dev \
libedit-dev \
libjemalloc-dev \
libncurses-dev \
libpcre3-dev \
libtool \
pkg-config \
python3-docutils \
sphinx-common \
varnish-dev=6.0.12-1~bookworm \
" \
&& apt-get update -q -y \
&& apt-get install -q -y --no-install-recommends ca-certificates curl \
\
&& curl -s ${PACKAGECLOUD_URL} | bash \
&& apt-get install -q -y --allow-unauthenticated --no-install-recommends varnish=6.0.12-1~bookworm $buildDeps \
\
&& curl -A "Docker" -o /tmp/varnish-modules.tar.gz -D - -L -s https://github.com/varnish/varnish-modules/archive/refs/tags/${VARNISH_MODULES_VERSION}.tar.gz \
&& tar zxpf /tmp/varnish-modules.tar.gz -C /tmp/ \
&& cd /tmp/varnish-modules-${VARNISH_MODULES_VERSION} \
&& ./bootstrap \
&& ./configure \
&& make \
&& make install \
&& rm -f /tmp/varnish-modules.tar.gz && rm -Rf /tmp/varnish-modules-${VARNISH_MODULES_VERSION} \
\
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false $buildDeps \
&& rm -rf /var/lib/apt/lists/*
21 changes: 21 additions & 0 deletions tests/varnish/Dockerfile-9
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Image for running the varnishtest suite in tests/varnish/ against varnish9.vcl.
#
# Mirrors docker/Dockerfile-varnish9 from ibexa/docker: the VCL imports the xkey vmod, which the
# official image does not ship.

FROM varnish:9.0

SHELL ["/bin/bash", "-c"]

# Root is only needed to install the vmod; the image drops back to the unprivileged user the base
# image runs as by default.
USER root
RUN set -e && \
read -ra vmod_deps <<< "$VMOD_DEPS" && \
varnish_version=$(dpkg-query -W -f='${Version}' varnish) && \
apt-get update && \
apt-get -y --no-install-recommends install "${vmod_deps[@]/varnish-dev/varnish-dev=$varnish_version}" && \
install-vmod https://github.com/varnish/varnish-modules/releases/download/0.28.0/varnish-modules-0.28.0.tar.gz && \
rm -rf /var/lib/apt/lists/*

USER varnish
Loading
Loading