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
2 changes: 1 addition & 1 deletion config/openconext/parameters.yaml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ parameters:
app_secret: SeTW1ThY0uR0WnS3cR37
application_name: OpenConext Middleware
# IP addresses of any HTTP proxies that are sitting in front of the application
# See: http://symfony.com/doc/current/request/load_balancer_reverse_proxy.html
# See: https://symfony.com/doc/current/deployment/proxies.html
trusted_proxies: ~

database_driver: pdo_mysql
Expand Down
1 change: 1 addition & 0 deletions config/packages/framework.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
framework:
secret: '"%secret%"'
trusted_proxies: '%trusted_proxies%'
#csrf_protection: true
#http_method_override: true

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

declare(strict_types=1);

/**
* Copyright 2026 SURFnet B.V.
*
* 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.
*/

namespace Surfnet\StepupMiddleware\ApiBundle\Logger;

use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
use Symfony\Component\HttpFoundation\RequestStack;

#[AutoconfigureTag('monolog.processor', ['channel' => 'request'])]
class SecurityContextProcessor implements ProcessorInterface
{
public function __construct(
private readonly RequestStack $requestStack,
private readonly Security $security,
) {
}

public function __invoke(LogRecord $record): LogRecord
{
$extra = $record->extra;

$request = $this->requestStack->getCurrentRequest();
if ($request !== null) {
$extra['http_method'] = $request->getMethod();
$extra['path'] = $request->getPathInfo();

$route = $request->attributes->get('_route');
if (is_string($route) && $route !== '') {
$extra['route'] = $route;
}

$clientIp = $request->getClientIp();
Comment thread
phavekes marked this conversation as resolved.
if ($clientIp !== null && $clientIp !== '') {
$extra['client_ip'] = $clientIp;
}
}

$user = $this->security->getUser();
if ($user !== null) {
$extra['user'] = $user->getUserIdentifier();
}

return $record->with(extra: $extra);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<?php

declare(strict_types=1);

/**
* Copyright 2026 SURFnet B.V.
*
* 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.
*/

namespace Surfnet\StepupMiddleware\ApiBundle\Tests\Logger;

use DateTimeImmutable;
use Mockery as m;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use Monolog\Level;
use Monolog\LogRecord;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Surfnet\StepupMiddleware\ApiBundle\Logger\SecurityContextProcessor;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\User\UserInterface;

final class SecurityContextProcessorTest extends TestCase
Comment thread
phavekes marked this conversation as resolved.
{
use MockeryPHPUnitIntegration;

#[Test]
public function it_enriches_log_record_with_request_and_user_data(): void
{
$requestStack = m::mock(RequestStack::class);
$security = m::mock(Security::class);

$request = Request::create(
uri: '/api/identity/resolve',
method: 'GET',
server: ['REMOTE_ADDR' => '192.168.1.100']
);
$request->attributes->set('_route', 'api_identity_resolve');

$user = m::mock(UserInterface::class);
$user->shouldReceive('getUserIdentifier')->andReturn('user-12345');

$requestStack->shouldReceive('getCurrentRequest')->andReturn($request);
$security->shouldReceive('getUser')->andReturn($user);

$processor = new SecurityContextProcessor($requestStack, $security);

$record = new LogRecord(
datetime: new DateTimeImmutable(),
channel: 'security',
level: Level::Debug,
message: 'Authenticator set no success response: request continues.',
context: ['authenticator' => 'CustomAuthenticator'],
extra: ['existing' => 'value']
);

$processed = $processor($record);

$this->assertSame('value', $processed->extra['existing']);
$this->assertSame('GET', $processed->extra['http_method']);
$this->assertSame('/api/identity/resolve', $processed->extra['path']);
$this->assertSame('api_identity_resolve', $processed->extra['route']);
$this->assertSame('192.168.1.100', $processed->extra['client_ip']);
$this->assertSame('user-12345', $processed->extra['user']);
}

#[Test]
public function it_enriches_log_record_when_request_is_present_without_user(): void
{
$requestStack = m::mock(RequestStack::class);
$security = m::mock(Security::class);

$request = Request::create(
uri: '/api/identity/resolve',
method: 'GET',
server: ['REMOTE_ADDR' => '192.168.1.100']
);
$request->attributes->set('_route', 'api_identity_resolve');

$requestStack->shouldReceive('getCurrentRequest')->andReturn($request);
$security->shouldReceive('getUser')->andReturnNull();

$processor = new SecurityContextProcessor($requestStack, $security);

$record = new LogRecord(
datetime: new DateTimeImmutable(),
channel: 'request',
level: Level::Info,
message: 'Unauthenticated request received',
context: [],
extra: ['existing' => 'value']
);

$processed = $processor($record);

$this->assertSame('value', $processed->extra['existing']);
$this->assertSame('GET', $processed->extra['http_method']);
$this->assertSame('/api/identity/resolve', $processed->extra['path']);
$this->assertSame('api_identity_resolve', $processed->extra['route']);
$this->assertSame('192.168.1.100', $processed->extra['client_ip']);
$this->assertArrayNotHasKey('user', $processed->extra);
}

#[Test]
public function it_omits_route_when_route_attribute_is_missing(): void
{
$requestStack = m::mock(RequestStack::class);
$security = m::mock(Security::class);

$request = Request::create(
uri: '/api/identity/resolve',
method: 'POST',
server: ['REMOTE_ADDR' => '192.168.1.100']
);

$user = m::mock(UserInterface::class);
$user->shouldReceive('getUserIdentifier')->andReturn('user-12345');

$requestStack->shouldReceive('getCurrentRequest')->andReturn($request);
$security->shouldReceive('getUser')->andReturn($user);

$processor = new SecurityContextProcessor($requestStack, $security);

$record = new LogRecord(
datetime: new DateTimeImmutable(),
channel: 'request',
level: Level::Info,
message: 'Request with unmatched route',
context: [],
extra: []
);

$processed = $processor($record);

$this->assertSame('POST', $processed->extra['http_method']);
$this->assertSame('/api/identity/resolve', $processed->extra['path']);
$this->assertSame('192.168.1.100', $processed->extra['client_ip']);
$this->assertSame('user-12345', $processed->extra['user']);
$this->assertArrayNotHasKey('route', $processed->extra);
}

#[Test]
public function it_handles_missing_request_and_missing_user(): void
{
$requestStack = m::mock(RequestStack::class);
$security = m::mock(Security::class);

$requestStack->shouldReceive('getCurrentRequest')->andReturnNull();
$security->shouldReceive('getUser')->andReturnNull();

$processor = new SecurityContextProcessor($requestStack, $security);

$record = new LogRecord(
datetime: new DateTimeImmutable(),
channel: 'app',
level: Level::Info,
message: 'CLI task executed',
context: [],
extra: []
);

$processed = $processor($record);

$this->assertSame([], $processed->extra);
}
}
Loading