Skip to content

Commit fbe799c

Browse files
committed
Update PHP and SimpleSAMLphp. Refactor Test SP code. Add OpenConext theme that asks for username only.
- Update form PHP 8.2 to PHP 8.5 image - Update SimpleSAMLphp from 2.4.0 to 2.5.4 - Use own theme for the IdP login pages - Only als for username, remove password field - Add cancel button that sends AuthnFailed SAML error - Refactor SP.php (Test SP) to make it more maintainable - Show XML of the SAML Response in the TEST SP - Add a test suite
2 parents 94a696c + 257bf6d commit fbe799c

40 files changed

Lines changed: 6444 additions & 766 deletions

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
.idea/
22
/container/
3+
/tests/vendor/
4+
/tests/.phpunit.cache/

‎README.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,42 @@ With the `-r` option you can force a rebuild of the containers.
115115
./dev-start.sh -r
116116
```
117117

118+
The container runs SimpleSAMLphp 2.5.4 on PHP 8.5 (SimpleSAMLphp 2.5 requires PHP 8.3 or later).
119+
120+
## Functional tests
121+
122+
The `tests/` directory contains functional tests that drive the devssp like a browser: they use the Test SP
123+
(`sp.php`), log in at the local IdP and the EntraID mock IdP, check the AuthnRequests that the Test SP sends,
124+
and test the attribute authority (`aa.php`) and the SAML tools (`tools.php`). Flows to the Stepup gateway are
125+
stopped at the devssp, so the gateway is not needed.
126+
127+
The tests are a separate PHPUnit project with their own `composer.json`; they do not use SimpleSAMLphp.
128+
A test also fails when it causes an error in the error log of the devssp (SimpleSAMLphp, PHP and Apache errors),
129+
so errors that SimpleSAMLphp hides behind an error page are caught as well.
130+
131+
Run the tests in the running container (start it first with `./dev-start.sh`):
132+
```bash
133+
./dev-test.sh
134+
```
135+
This copies `tests/` to the container, installs the dependencies and runs PHPUnit. Options are passed to PHPUnit:
136+
```bash
137+
./dev-test.sh --filter EntraMock
138+
```
139+
140+
You can also run the tests from elsewhere, e.g. from the host or against a SimpleSAMLphp running outside Docker.
141+
They need PHP 8.3 or later and composer. These environment variables configure the tests (see `tests/phpunit.xml.dist`):
142+
- `DEVSSP_BASE_URL`: URL of the devssp, default `https://ssp.dev.openconext.local`
143+
- `DEVSSP_VERIFY_TLS`: verify the TLS certificate, default `0`
144+
- `DEVSSP_LOG_FILE`: the error log to check, default `/var/log/devssp/error.log`. Set it to an empty value to
145+
disable the log check.
146+
147+
```bash
148+
cd tests && composer install && DEVSSP_LOG_FILE= vendor/bin/phpunit
149+
```
150+
151+
In the container the Apache error log (to which SimpleSAMLphp logs) is written to both stderr (`docker compose logs`)
152+
and `/var/log/devssp/error.log`, see `docker/conf/000-default.conf`.
153+
118154
## Debugging
119155
The container has XDebug installed and configured.
120156

‎dev-test.sh‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env bash
2+
3+
# Run the functional tests (see tests/) in the running devssp container.
4+
# Start the container first with ./dev-start.sh
5+
#
6+
# Usage: ./dev-test.sh [phpunit options]
7+
# e.g. ./dev-test.sh --filter EntraMock
8+
# ./dev-test.sh --testdox
9+
10+
set -e
11+
12+
# get the directory of this script
13+
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
14+
cd "$DIR"
15+
16+
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
17+
echo "Usage: $0 [phpunit options]"
18+
echo "Runs the functional tests in tests/ in the running ssp container (start it with ./dev-start.sh)"
19+
echo "Any options are passed to phpunit, e.g.: $0 --filter EntraMock"
20+
exit 0
21+
fi
22+
23+
if [[ -z "$(docker compose ps --status running --quiet ssp)" ]]; then
24+
echo "The ssp container is not running. Start it with ./dev-start.sh"
25+
exit 1
26+
fi
27+
28+
TESTS_DIR=/var/www/devssp-tests
29+
30+
# Copy the tests to the container. Keep the vendor directory in the container, so composer install is quick.
31+
echo "Copying tests/ to ${TESTS_DIR} in the ssp container"
32+
docker compose exec -T ssp sh -c "mkdir -p ${TESTS_DIR} && cd ${TESTS_DIR} && find . -mindepth 1 -maxdepth 1 ! -name vendor -exec rm -rf {} +"
33+
COPYFILE_DISABLE=1 tar -C tests --exclude=./vendor --exclude=./.phpunit.cache -cf - . \
34+
| docker compose exec -T ssp tar -C "${TESTS_DIR}" -xf - 2>/dev/null
35+
36+
echo "Installing the test dependencies"
37+
docker compose exec -T -e COMPOSER_ALLOW_SUPERUSER=1 ssp \
38+
composer --working-dir="${TESTS_DIR}" install --no-interaction --no-progress --quiet
39+
40+
# Use a TTY (colors) when we have one
41+
TTY_OPT=-T
42+
if [[ -t 1 ]]; then
43+
TTY_OPT=
44+
fi
45+
46+
echo "Running the tests"
47+
# shellcheck disable=SC2086
48+
docker compose exec ${TTY_OPT} -w "${TESTS_DIR}" ssp vendor/bin/phpunit "$@"

‎docker/Dockerfile‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,26 @@
1-
FROM ghcr.io/openconext/openconext-basecontainers/php82-apache2-node20-composer2:latest
1+
FROM ghcr.io/openconext/openconext-basecontainers/php85-apache2-node24:latest
22
# See:
3-
# https://github.com/OpenConext/OpenConext-BaseContainers/blob/main/php82-apache2-node20-composer2/Dockerfile
3+
# https://github.com/OpenConext/OpenConext-BaseContainers/blob/main/php85-apache2-node24/Dockerfile
44

5-
# https://github.com/OpenConext/OpenConext-BaseContainers/blob/main/php82-apache2/Dockerfile
5+
# https://github.com/OpenConext/OpenConext-BaseContainers/blob/main/php85-apache2/Dockerfile
66
# Exposes PORT 80 for apache
77

88
LABEL maintainer="pieter.vandermeulen@surf.nl"
99
WORKDIR /var/www/simplesaml
1010
# Install SimpleSAMLphp from the project's release tarball
11-
RUN curl -L "https://github.com/simplesamlphp/simplesamlphp/releases/download/v2.4.0/simplesamlphp-2.4.0-full.tar.gz" \
11+
RUN curl -L "https://github.com/simplesamlphp/simplesamlphp/releases/download/v2.5.4/simplesamlphp-2.5.4-full.tar.gz" \
1212
| tar -xvz -C /var/www/simplesaml --strip-components=1
1313
COPY ./modules/ /var/www/simplesaml/my-modules/
14+
# The openconext module (OpenConext theme + username-only authsource of the IdPs) must live in
15+
# modules/ to be discovered by SimpleSAMLphp
16+
COPY ./modules/openconext/ /var/www/simplesaml/modules/openconext/
1417
COPY ./html/* /var/www/html
1518
COPY ./sspwww/* /var/www/simplesaml/public/
1619
COPY ./sspconf/ /var/www/simplesaml/config/
1720
COPY ./sspattributemap/Openconext_short_to_urn.php /var/www/simplesaml/attributemap/
1821
COPY ./conf/000-default.conf /etc/apache2/sites-enabled/
1922

23+
RUN mkdir -p /var/log/devssp && chmod 1777 /var/log/devssp
2024
RUN mkdir -p /var/www/simplesaml/data
2125
RUN chown -R www-data:www-data /var/www/simplesaml/data
2226

‎docker/conf/000-default.conf‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
11
ServerName ssp.dev.openconext.local
22

3-
<VirtualHost *:80>
4-
ServerAdmin webmaster@localhost
5-
DocumentRoot /var/www/html
6-
ErrorLog ${APACHE_LOG_DIR}/error.log
7-
CustomLog ${APACHE_LOG_DIR}/access.log combined
8-
DirectoryIndex disabled
9-
DirectoryIndex index.php index.html
10-
# The standard devssp IdP
11-
Alias /simplesaml /var/www/simplesaml/public/
12-
# The EntraID mock IdP
13-
Alias /entra-mock /var/www/simplesaml/public/
14-
<Directory /var/www/simplesaml/public>
15-
Require all granted
3+
# Send the (main server) error log through tee: it still goes to stderr, so it shows up in
4+
# `docker compose logs`, and is also written to /var/log/devssp/error.log so the functional
5+
# tests (see tests/) can check that a test did not cause any errors.
6+
# SimpleSAMLphp logs to stderr ('logging.handler' => 'stderr'), PHP errors go here as well.
7+
ErrorLog "|/usr/bin/tee -a /var/log/devssp/error.log"
8+
9+
<VirtualHost *:80>
10+
ServerAdmin webmaster@localhost
11+
DocumentRoot /var/www/html
12+
# This is a development container. The base image enables mod_expires globally
13+
# (ExpiresByType text/css "access plus 1 year" etc.), which would add a one-year
14+
# max-age/Expires to all responses and make browsers keep serving stale SimpleSAMLphp
15+
# module assets (CSS/JS) after theme changes. Disable it here: assets are served with
16+
# max-age=0 + ETag (see 'assets.caching' in config.php), so browsers revalidate on every
17+
# request and get the current file.
18+
ExpiresActive Off
19+
CustomLog ${APACHE_LOG_DIR}/access.log combined
20+
DirectoryIndex disabled
21+
DirectoryIndex index.php index.html
22+
# The standard devssp IdP
23+
Alias /simplesaml /var/www/simplesaml/public/
24+
# The EntraID mock IdP
25+
Alias /entra-mock /var/www/simplesaml/public/
26+
<Directory /var/www/simplesaml/public>
27+
Require all granted
1628
</Directory>
1729
</VirtualHost>
18-

‎docker/html/index.html‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -156,19 +156,16 @@ <h2 id="attibute-authority">Attibute Authority</h2>
156156

157157
<h2 id="entra-mock-idp">EntraID mock IdP</h2>
158158
<p>
159-
A second IdP that emulates an EntraID (Azure AD) tenant, for testing the Stepup-AzureMFA GSSP without a real
160-
EntraID tenant.
159+
A second IdP, intended for testing Stepup-AzureMFA GSSP. Authenticate with the same username and password as the main IdP.
160+
Emulate cancelling an authentication by authentication with username <code>cancel</code> and password <code>cancel</code>.
161161
</p>
162162
<ul>
163163
<li>EntityID / IdP metadata: <a href="https://ssp.dev.openconext.local/entra-mock/saml2/idp/metadata.php"><code>https://ssp.dev.openconext.local/entra-mock/saml2/idp/metadata.php</code></a></li>
164-
<li>SingleSignOnService endpoint (HTTP-Redirect): <code>https://ssp.dev.openconext.local/entra-mock/module.php/saml/idp/singleSignOnService</code></li>
164+
<li>SingleSignOnService endpoint: <code>https://ssp.dev.openconext.local/entra-mock/module.php/saml/idp/singleSignOnService</code></li>
165165
</ul>
166166
<p>
167-
Authenticate with the same username and password as at the main IdP (see <a href="#test-accounts">Test accounts</a>),
168-
e.g. <code>jane-a1</code> / <code>jane-a1</code>. There is no SSO, neither with the main IdP nor at the mock
169-
itself: every authentication shows the login page.
170-
Emulate a user cancelling the authentication at EntraID by logging in with username <code>cancel</code> and
171-
password <code>cancel</code>.
167+
Authenticate with the same username as at the main IdP (see <a href="#test-accounts">Test accounts</a>),
168+
e.g. <code>jane-a1</code>.
172169
</p>
173170

174171
<h2 id="tools">Tools</h2>

‎docker/modules/debugsp/composer.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"type": "simplesamlphp-module",
1212
"require": {
1313
"simplesamlphp/composer-module-installer": "^1.3",
14-
"simplesamlphp/simplesamlphp": "^2.1"
14+
"simplesamlphp/simplesamlphp": "^2.5"
1515
},
1616
"autoload": {
1717
"psr-4": {

‎docker/modules/debugsp/src/Auth/Source/SP.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public function __construct($info, $config)
4949
}
5050

5151

52-
public function startSSO(string $idp, array $state): void
52+
public function startSSO(string $idp, array $state): never
5353
{
5454
$state_json = json_encode($state);
5555
Logger::debug("debugsp\Auth\Source\SP::startSSO('$idp', $state_json)");
@@ -77,7 +77,7 @@ public function startSSO(string $idp, array $state): void
7777

7878
// Override \SimpleSAML\Auth\Source\SP::sendSAML2AuthnRequest() to allow us to make last minute changes to the
7979
// AuthnRequest before it is sent to the IdP
80-
public function sendSAML2AuthnRequest(Binding $binding, AuthnRequest $ar): void
80+
public function sendSAML2AuthnRequest(Binding $binding, AuthnRequest $ar): never
8181
{
8282
Logger::debug('debugsp: debugsp\Auth\Source\SP::sendSAML2AuthnRequest(...)');
8383
if (isset($this->state['debugsp:AssertionConsumerServiceURL'])) {

‎docker/modules/debugsp/src/Controller/ServiceProvider.php‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
namespace SimpleSAML\Module\debugsp\Controller;
66

77
use SimpleSAML\Logger;
8+
use SimpleSAML\Session;
9+
use SimpleSAML\Utils\HTTP;
810
use Symfony\Component\HttpFoundation\Request;
911
use Symfony\Component\HttpFoundation\Response;
1012
use SimpleSAML\HTTP\RunnableResponse;
@@ -39,10 +41,100 @@ public function assertionConsumerService(string $sourceId): RunnableResponse
3941
$_POST['SAMLResponse'] = $_POST['_SAMLResponse'];
4042
}
4143

44+
// Store the SAML Response as received (verbatim) in the session, so the Test SP (sp.php) can show it.
45+
// This saves a trip to the SAML tracer browser plugin.
46+
$samlResponse = self::parseSamlResponse();
47+
if ($samlResponse === null) {
48+
// Let parent handle the request (and the error)
49+
return parent::assertionConsumerService($sourceId);
50+
}
51+
$session = Session::getSessionFromRequest();
52+
$session->setData('array', 'DEBUGSP_SAML_RESPONSE', $samlResponse);
53+
54+
// Intercept SAML error responses (e.g. the Responder / AuthnFailed response that the EntraID mock
55+
// IdP returns when the user presses Cancel at the login page). Instead of letting SimpleSAMLphp
56+
// handle the error (which results in an SSP error page), redirect back to the Test SP (sp.php),
57+
// which shows a "SAML Error Status" section with the details and the XML of the response.
58+
if ($samlResponse['StatusCode'] !== '' && $samlResponse['StatusCode'] !== \SAML2\Constants::STATUS_SUCCESS) {
59+
Logger::info('debugsp: received SAML error response, redirecting to the Test SP');
60+
61+
$httpUtils = new HTTP();
62+
$relayState = $_REQUEST['RelayState'] ?? null;
63+
if (is_string($relayState) && strlen($relayState) > 0) {
64+
return new RunnableResponse([$httpUtils, 'redirectTrustedURL'], [$httpUtils->checkURLAllowed($relayState)]);
65+
}
66+
67+
// No (valid) RelayState: redirect to the Test SP for this authsource
68+
$returnTo = $httpUtils->getBaseURL() . 'sp.php?sp=' . urlencode($sourceId);
69+
return new RunnableResponse([$httpUtils, 'redirectTrustedURL'], [$returnTo]);
70+
}
71+
4272
// Let parent handle the response
4373
return parent::assertionConsumerService($sourceId);
4474
}
4575

76+
/**
77+
* Parse the raw SAMLResponse of the current request. Returns an array with the main fields of the
78+
* response and its assertion, and the XML of the response as received ('xml').
79+
* Returns null when the request carries no SAML 2.0 Response.
80+
*
81+
* @return array|null
82+
*/
83+
private static function parseSamlResponse(): ?array
84+
{
85+
$encoded = $_POST['SAMLResponse'] ?? $_GET['SAMLResponse'] ?? null;
86+
if (!is_string($encoded) || $encoded === '') {
87+
return null;
88+
}
89+
90+
$xml = base64_decode($encoded, true);
91+
if ($xml === false || $xml === '') {
92+
return null;
93+
}
94+
95+
$doc = new \DOMDocument();
96+
if (!@$doc->loadXML($xml)) {
97+
// HTTP-Redirect binding responses are deflated after base64 encoding
98+
$inflated = @gzinflate($xml);
99+
if ($inflated === false || !@$doc->loadXML($inflated)) {
100+
return null;
101+
}
102+
$xml = $inflated;
103+
}
104+
105+
$xpath = new \DOMXPath($doc);
106+
$xpath->registerNamespace('samlp', 'urn:oasis:names:tc:SAML:2.0:protocol');
107+
$xpath->registerNamespace('saml', 'urn:oasis:names:tc:SAML:2.0:assertion');
108+
109+
if ($xpath->query('/samlp:Response')->length !== 1) {
110+
return null; // not a SAML 2.0 Response
111+
}
112+
113+
$value = static fn (string $expression): string => (string) $xpath->evaluate("string($expression)");
114+
$assertion = '/samlp:Response/saml:Assertion';
115+
116+
return [
117+
'ID' => $value('/samlp:Response/@ID'),
118+
'InResponseTo' => $value('/samlp:Response/@InResponseTo'),
119+
'IssueInstant' => $value('/samlp:Response/@IssueInstant'),
120+
'Destination' => $value('/samlp:Response/@Destination'),
121+
'Issuer' => $value('/samlp:Response/saml:Issuer'),
122+
'StatusCode' => $value('/samlp:Response/samlp:Status/samlp:StatusCode/@Value'),
123+
'SubStatusCode' => $value('/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode/@Value'),
124+
'StatusMessage' => $value('/samlp:Response/samlp:Status/samlp:StatusMessage'),
125+
'EncryptedAssertion' => $xpath->query('/samlp:Response/saml:EncryptedAssertion')->length > 0 ? 'yes' : '',
126+
'Assertion ID' => $value("$assertion/@ID"),
127+
'Assertion IssueInstant' => $value("$assertion/@IssueInstant"),
128+
'Conditions NotBefore' => $value("$assertion/saml:Conditions/@NotBefore"),
129+
'Conditions NotOnOrAfter' => $value("$assertion/saml:Conditions/@NotOnOrAfter"),
130+
'Audience' => $value("$assertion/saml:Conditions/saml:AudienceRestriction/saml:Audience"),
131+
'AuthnInstant' => $value("$assertion/saml:AuthnStatement/@AuthnInstant"),
132+
'SessionNotOnOrAfter' => $value("$assertion/saml:AuthnStatement/@SessionNotOnOrAfter"),
133+
'SessionIndex' => $value("$assertion/saml:AuthnStatement/@SessionIndex"),
134+
'xml' => $xml,
135+
];
136+
}
137+
46138

47139
/**
48140
* Metadata endpoint for SAML SP

0 commit comments

Comments
 (0)