The PHPUnit functional tests in tests/Functional exercise the Gateway at the HTTP level, in-process.
PHPUnit and Symfony's WebTestCase are used to send real HTTP requests (SAML AuthnRequests, SAML Responses) to the
Symfony kernel and the tests assert on the HTTP responses it receives back. There are no external dependencies:
no browser, web server, MariaDB or other devconf container. This makes these test fast and simple to run, easy to debug
with a normal PHPUnit/IDE setup and less likely to break than the Behat functional tests that use a real browser in a separate
Docker container.
The tests mirror the configuration that is used in the devconf environment. This makes recreating situations using devconf simpler. Scripts are included to create and update the test fixtures from a live devconf environment.
These test complement (for now) the Behat tests in tests/features, which run against a full devconf or CI Docker setup.
This document is aimed at developers who want to add or change PHPUnit functional tests. For running the tests, see the README.
- How it works
- Directory layout
- Writing a test
- Fixtures
- Capturing fixtures from devconf
- Re-signing captured responses
- Verifying the Gateway's responses
- Baseline responses
- Gotchas and limitations
Many of the fixtures used by the functional tests are captured from a full OpenConext-devconf environment using helper scripts in tests/Functional/bin: the gateway database, the key material and the SAML Messages that are not generated by the gateway. For SAML Messages that are generated by the gateway, a baseline was captured. This way we can detect is the gateway starts behaving differently.
The tests run in a dedicated Symfony environment, functional (selected with APP_ENV=functional in
ci/qa/phpunit-functional.xml). It is separate from test (unit tests) and smoketest (Behat). Unlike those, it does
not import config/services_test.yaml: it uses the base configuration plus:
| File | Purpose |
|---|---|
config/packages/functional/framework.yaml |
Enables framework.test and mock file sessions |
config/packages/functional/doctrine.yaml |
File-backed SQLite for the gateway database connection |
config/packages/functional/monolog.yaml |
Logs to var/log/functional.log instead of stderr |
config/packages/functional/twig.yaml |
Strict Twig variables |
config/services_functional.yaml |
Points all SAML key parameters (saml_*, gssp_*) at tests/Functional/Fixtures/devconf/keys/, instead of /config/gateway/... in the container, and uses the Yubikey and SMS test doubles in Support/TestDouble/ (see Writing a test) |
Because services_test.yaml is not imported, the SSO-on-2FA cookie is encrypted with the real Halite crypto helper (not
the dummy of the Behat tests), so SsoOn2faFlowTest decrypts and forges cookie values with that helper. The other
parameters (e.g. the SSO-on-2FA cookie name, lifetime and key) come from config/openconext/parameters.yaml.
The environment is not in debug mode, so the container is cached. Running ci/qa/phpunit-functional will remove var/cache/functional, forcing the cache to update.
The Gateway only reads from its database. The tests use a SQLite database, file-backed in the functional cache dir
(var/cache/functional/*.db, see config/packages/functional/doctrine.yaml). The file-backed database survives the
kernel reboot the test client performs before every request, so each request runs on a fresh kernel and container,
like in production. The schema and fixtures are (re)created once for every test:
GatewayWebTestCase::setUp()boots the kernel andDevconfFixtureLoadercreates the schema from the Doctrine entity metadata (SchemaTool).- It then loads
Fixtures/devconf/database.sql: the data captured from the devconf Gateway database (SPs, institution configuration, whitelist and registered second factors).
Because the database is recreated in every setUp(), a test that would modify the db cannot leak into other tests.
The database is small, so this is almost free and would allow us to change configuration on the fly in tests.
Time is not mocked. This proved hard, new DateTime('now') is called in several places. And resigning would still be
necessary unless we could set the SAML Request ID's used in the SAML Requests that are generated by the gateway to known
values only during testing, which also is not trivial to do safely.
So, instead we update timestamps and SAML IDs where needed and resign the message. This is possible because we have
imported the keys used by OpenConext-devconf in fixtures and thus can resign any SAML messages that it generated.
The Stepup-Gateway doen not currently checkt the timestamps in the AuthnRequests sent to the Stepup-Gateway, so for these we can use static fixtures. When this changes, we can update the time and resign them in a similar fashion.
The tests use real messages captured from devconf, signed with the devconf keys:
- AuthnRequests (SP to Gateway) are captured and replayed as is. They are signed (HTTP-Redirect binding), so they cannot be modified.
- Responses (IdP or GSSP to Gateway) can not be replayed as captured: they contain the (random) request ID of the
AuthnRequest the Gateway sent, and timestamps that limit their validity. Instead of mocking time, we update the ID and
timestamps in the SAML Responses and then resign them using
SamlResponseResigner.
tests/Functional/
├── Gateway/ Test classes (SfoFlowTest, SsoFlowTest, SsoOn2faFlowTest, GsspFlowTest, AdfsSfoFlowTest, GsspProxyTest, SecondFactorBypassTest)
├── Support/
│ ├── GatewayWebTestCase.php Base test case (client, database, fixtures)
│ ├── Database/DevconfFixtureLoader.php Creates the schema and loads database.sql
│ ├── TestDouble/YubikeyService.php Accepts well-formed Yubikey OTPs without Yubico, keeps the public ID check
│ ├── TestDouble/SmsService.php Keeps the SMS messages instead of sending them, so a test can read the OTP
│ └── Saml/
│ ├── SamlFixtureLoader.php Loads SAML fixture files
│ ├── SamlRequestParser.php Reads the AuthnRequest the Gateway sends (e.g. from a redirect Location)
│ ├── SamlResponseParser.php Reads the SAML Response the Gateway returns
│ ├── SamlResponseResigner.php Makes a captured Response valid for a new request
│ ├── SamlResponseNormalizer.php Replaces IDs, timestamps and signature values, for baseline comparison
│ └── SamlSignatureVerifier.php Verifies the XML signatures of a SAML message against a certificate
├── Fixtures/devconf/ Everything captured from devconf (by hand)
│ ├── database.sql
│ ├── keys/ Certificates and private keys (<name>.crt / <name>.key)
│ └── saml/
│ ├── authn-requests/ *.php fixtures with manually captured AuthnRequests
│ └── responses/ *.php fixtures with manually captured Responses
├── Fixtures/saml/baselines/ Baseline for responses generated by the Stepup-Gateway
└── bin/
├── capture-devconf-fixture Capture gateway database and devconf keys from a devconf instance
├── convert-saml-to-fixture Convert a SAML message to a .php fixture file
└── anonymise-string Randomise a string (stdin to stdout), keeping its structure and length
ci/qa/phpunit-functional(.xml) Test runner and PHPUnit configuration
Extend GatewayWebTestCase. It provides:
$this->client: theKernelBrowser$this->samlFixtures:loadRedirectAuthnRequest(),loadPostResponse(), ...$this->samlResigner: re-signs captured SAML ResponsesassertSamlResponseSignatureIsValid(),assertSamlResponseAnswersRequest(),assertSamlResponseTimestampsAreValid()andassertSamlResponseMatchesBaseline(): see Verifying the Gateway's responses and Baseline responsesgetSamlResponseFromCurrentPage(): parses theSAMLResponseof the auto-submit form the Gateway renders (returns aSamlResponseParserwith status, audience, NameID, signed, ...) andgetFormAction(): the ACS URL of that form.
A test follows the flow like a browser would. This is a condensed version of a test in GsspFlowTest:
// 1. The SP sends a captured AuthnRequest, keep its ID to check the InResponseTo of the Gateway's response
$query = $this->samlFixtures->loadRedirectAuthnRequest('sfo-redirect-jane-a1-loa2');
$sfoRequestId = SamlRequestParser::fromRedirectUrl($query)->getId();
$this->client->request('GET', 'https://gateway.dev.openconext.local/second-factor-only/single-sign-on?' . $query,
server: ['HTTPS' => 'on']);
// 2. Follow redirects until the Gateway redirects to the remote party, and read the AuthnRequest it sent
$gatewayRequest = SamlRequestParser::fromRedirectUrl(
$this->followRedirectsUntilLocationStartsWith('https://demogssp.dev.openconext.local/saml/sso')
);
// 3. Answer as the remote party: take the captured response, and make it valid for the Gateway's request
$this->client->request('POST', 'https://gateway.dev.openconext.local/gssp/demo_gssp/consume-assertion', [
'SAMLResponse' => $this->samlResigner->resign(
$this->samlFixtures->loadPostResponse('demo-gssp-response-jane-a1'),
$gatewayRequest
),
], server: ['HTTPS' => 'on']);
// 4. Assert on the SAML response the Gateway sends to the SP
$this->followRedirects();
$samlResponse = $this->getSamlResponseFromCurrentPage();
$this->assertSamlResponseSignatureIsValid($samlResponse);
$this->assertSamlResponseAnswersRequest($samlResponse, $sfoRequestId);
$this->assertSamlResponseTimestampsAreValid($samlResponse);
$this->assertSamlResponseMatchesBaseline($samlResponse, 'gateway-sfo-response-jane-a1-loa3-redirect');See tests/Functional/Gateway/*Test.php for complete examples.
Tips:
- Use users and SPs from
database.sql. To see what is available look at the SQL (or the devconf configuration): e.g.joe-a-yk(Yubikey),joe-a-smsandjane-a-sms(SMS) andjane-a1(Demo GSSP) ofinstitution-a.example.com, andjoe-b1(Demo GSSP, self-asserted, registered through Self-Service) ofinstitution-b.example.com. - The Yubikey service is a test double (
Support/TestDouble/YubikeyService): it does not call the Yubico cloud API and accepts any well-formed OTP, but the Gateway still checks that the OTP is of the user's Yubikey (its public ID must be thesecond_factor_identifierof the token).submitYubikeyOtp(self::JOE_A_YK_YUBIKEY_ID)submits an OTP of the Yubikey ofjoe-a-yk; useYubikeyService::otpForPublicId()to generate an OTP yourself. Unlike the Behat double inconfig/services_test.yaml, it does not accept the OTP of another Yubikey: with that double, a test of a wrong Yubikey can not fail. - The SMS service is a test double (
Support/TestDouble/SmsService): it does not send the SMS, but keeps it. The Gateway generates, stores and verifies the OTP as usual.submitSmsOtp(self::JOE_A_SMS_MSISDN)submits the last OTP that was sent tojoe-a-sms(useself::JANE_A_SMS_MSISDNforjane-a-sms).getSmsOtpSentTo()returns the OTP of the last SMS to a phone number. - To see what the Gateway did, read
var/log/functional.log.
All fixtures are in tests/Functional/Fixtures/devconf and are captured from a running devconf. They are committed, so
running the tests does not require devconf.
A SAML fixture is a PHP file that returns a string. This keeps the fixture executable and lets it carry documentation: the generated header and a block comment with the decoded XML make it easy to see what a fixture contains.
saml/authn-requests/<name>.phpreturns the HTTP-Redirect query string (SAMLRequest=...&RelayState=...&SigAlg=...&Signature=...).saml/responses/<name>.phpreturns the base64 encoded XML of a Response (the value of theSAMLResponsePOST parameter).
SamlFixtureLoader loads them by name, without extension (loadRedirectAuthnRequest('sso-redirect-loa2-1')).
Name fixtures after what they contain, e.g. sfo-redirect-jane-a1-loa2, ssp-response-joe-a-yk.
The responses the Gateway sends to an SP are not captured by hand: these are baselines, generated
by the tests and kept in a separate directory, Fixtures/saml/baselines/<name>.php (loaded with
loadBaselineResponse()).
A running devconf (OpenConext-devconf, started with
./start-dev-env.sh) with the users and tokens the tests need (register tokens through Self-Service). Fixtures are
captured with the host names of devconf (*.dev.openconext.local), so the tests use these host names as well.
The current database capture was created by:
- bootstrapping a stepup devconf (i.e. only the admin user is active with a yubikey token)
- Registering a yubikey token for joe-a-yk, vetted by admin
- Registering a Demo GSSP token for jane-a1, vetted by admin
- Registering an SMS token for joe-a-sms (phone number +31 (0) 612345678), vetted by admin
- Registering an SMS token for jane-a-sms (phone number +31 (0) 633333333), vetted by admin
- Registering a Demo GSSP token for joe-b1 in Self-Service, with SMS as the recovery method (a self-asserted token)
- Registering a Demo GSSP token for jane-b1, vetted by admin
- Registering an SMS token for joe-b-sms (phone number +31 (0) 622222222) in Self-Service, with a recovery code as the recovery method (a self-asserted token)
- Registering a Yubikey token for joe-d-yk, vetted by admin. (TODO)
Preparing a devconf for capturing the database fixture is currently a manual proces. The list above is there to allow recreating the devconf state for capturing a new (extended) database fixture. Automating this in some way would make sense in the future.
php tests/Functional/bin/capture-devconf-fixture /path/to/OpenConext-devconf database
php tests/Functional/bin/capture-devconf-fixture /path/to/OpenConext-devconf keys
databaseperformsmysqldumpof the live devconfmariadbcontainer (the devconf one, not the smoketest one). It captured the data only, with column names in the inserts. Then it converts it to SQLite-compatible SQL and writes it toFixtures/devconf/database.sql. It anonymizes the Yubikey identifiers because these are real and not mocked. Tests are written such that they do not rely on the second factor id guids. The gateway schema is not part of the dump. It is generated from the Doctrine entity mapping in the Stepup-Gateway code.keyscopies the certificates and private keys used by the SPs, IdPs and GSSPs of devconf toFixtures/devconf/keys/. The keys are the well known devconf development keys.
The idea is that the devconf configuration and the configuration and the fixtures are kept in sync. So you capture the database again when you register a new token, add or modify an SP or change the configuration of an institution. This means that changes to the devconf configuration must be made with these functional tests in mind.
SAML messages are captured from the browser, while going through the flow in devconf:
-
Install a SAML inspector in the browser (e.g. SAML Tracer), and perform the authentication in devconf.
-
Copy the message:
- AuthnRequest (HTTP-Redirect): the URL/query string of the request to the Gateway
(
.../single-sign-on?SAMLRequest=...&SigAlg=...&Signature=...). Copy the complete query string; the signature is over exactly these (encoded) parameters. - Response (HTTP-POST): the value of the
SAMLResponseform parameter of the POST to the Gateway (e.g..../consume-assertion), the base64 encoded XML.
- AuthnRequest (HTTP-Redirect): the URL/query string of the request to the Gateway
(
-
Convert it to a fixture:
php tests/Functional/bin/convert-saml-to-fixture --auto "<captured message>" sfo-redirect-jane-a1-loa2 php tests/Functional/bin/convert-saml-to-fixture --file captured.txt ssp-response-jane-a1The type (
authn-request-redirect,authn-request-post,response-post) is detected automatically, unless it is given with--type. The fixture is written toFixtures/devconf/saml/authn-requestsor.../responsesbased on the type. A comment is added to the fixture with a summary of the message (issuer, destination, ...) and the decoded XML.
SamlResponseResigner::resign($base64Response, SamlRequestParser $request) returns a base64 Response that the Gateway
accepts as the answer to $request. It updates:
- the
InResponseToof the Response and theSubjectConfirmationData: set to the ID of the request. - the timestamps (
IssueInstant,NotBefore,NotOnOrAfter,AuthnInstant,SessionNotOnOrAfter). These are shifted such that the Response was issued now. The length of the validity windows is preserved. - the signature (
ds:Signature) of the Assertion.
The private key is looked up using the certificate in the Response's ds:KeyInfo. The resigner searches
Fixtures/devconf/keys/*.crt for the first matching certificate, and uses the .key file with the same basename.
These keys and certificates were copied from devconf using capture-devconf-fixture keys.
SamlRequestParser::fromRedirectUrl($location) decodes the AuthnRequest in a redirect the Gateway sends, and gives the
request ID (getId()) that is required by the resigner.
Checks SAML Responses the Gateway returns:
assertSamlResponseSignatureIsValid($samlResponse) verifies the XML signature with SamlSignatureVerifier, against the
Gateway IdP certificate (Fixtures/devconf/keys/gateway_idp.crt). It checks that the signature is as expected from the
Stepup-Gateway:
- it is valid signature (checks digest and signature value);
- it is an enveloped signature over exactly its parent element;
- it uses a RSA-SHA256 and a SHA-256 digest.
assertSamlResponseAnswersRequest($samlResponse, $requestId) asserts that InResponseTo of the Response, and of the
SubjectConfirmationData of the assertion, is the ID of the SP's AuthnRequest. The tests keep that ID when they send the
request (SamlRequestParser::fromRedirectUrl() for HTTP-Redirect, SamlRequestParser::fromPostBinding() for HTTP-POST).
SAML Error responses are checked as well.
assertSamlResponseTimestampsAreValid($samlResponse) asserts that the response is correct for a response that was just
issued. Time is not mocked, so the checks are relative to the start of the test (set in setUp()) and to the current time:
IssueInstantof the Response and the Assertion, andAuthnInstant, are between the start of the test and now;- the assertion is valid now:
Conditions/@NotBefore<= now <Conditions/@NotOnOrAfter, andSubjectConfirmationData/@NotOnOrAfterhas not passed; - the assertion is valid for at most 5 minutes (
MAX_ASSERTION_VALIDITY_SECONDSinGatewayWebTestCase), and theSubjectConfirmationDatadoes not outlive theConditions; SessionNotOnOrAfterhas not passed, when present.
For an error response (no assertion) only the IssueInstant is checked. SAML timestamps have a precision of a second, the
comparison is done on whole seconds.
assertSamlResponseMatchesBaseline() compares the whole response with a baseline, see below.
A baseline is a captured SAML Response of the Gateway to an SP. The baseline test compares the Response against it.
The goal is to detect structural changes: an added or removed attribute, a different AuthnContext, Conditions or SubjectConfirmation, a changed certificate, namespace or element order.
$this->assertSamlResponseMatchesBaseline($samlResponse, 'gateway-sso-response-joe-a-yk-loa3');Baselines are response fixtures in Fixtures/saml/baselines/, kept separate from the SAML messages that were captured
manually in Fixtures/devconf/saml/. Before the comparison both XML documents are normalized by
SamlResponseNormalizer. Everything that differs between two runs is replaced by a placeholder.
Baselines are generated from the functional tests, not captured from devconf. When the Response legitimately changes or
a new baseline fixture is added, run the functional tests with UPDATE_SAML_BASELINES=1 to update the baselines instead
of asserting against them.
UPDATE_SAML_BASELINES=1 ci/qa/phpunit-functional
A baseline is written only if it does not exist, or if its normalized XML differs from the actual Response. Unchanged
baselines are not touched, so the diff only contains real changes. The fixture is written with
bin/convert-saml-to-fixture --type=response-baseline to make it human-readable and easy to review using git.
- Running these tests requires the PHP
pdo_sqliteandgmpextensions.