view release on metacpan or search on metacpan
Revision history for Airlock
0.001 2026-10-04 18:07:00Z
- Airlock::Upstream::Authentik turns an authentik login into an Airlock
subject and builds the matching Airlock::Factor::Upstream. authentik
reports the second factor with nothing configured: a password login
carries amr=pwd, a login with TOTP amr=pwd,mfa. Its one acr value says
nothing, and max_age=0 is the one value authentik discards, so its
reauth_params sends prompt=login; the POD says what was measured
- t/91-live-authentik.t drives the whole chain against a real authentik:
a device flow through Airlock::Client, a browser login with and without
TOTP, an approval through the Airlock core, and the upstream policy
holding only for the login with the second factor. t/authentik/ has the
fixtures and what was observed, including authentik's rate limit on the
device authorization endpoint, which answers slow_down to the request
that starts a flow and not just to a client polling too fast
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
subtest 'upstream' => sub {
my $clock = 10_000;
my $factor = Airlock::Factor::Upstream->new( now => sub { $clock } );
is( $factor->name, 'upstream', 'name' );
is( $factor->amr, 'mfa', 'amr' );
is( $factor->needs_proof, 0, 'needs no proof' );
is( $factor->verify( { id => 'a', amr => [qw( pwd otp )] } ), 1, 'otp in amr' );
is( $factor->verify( { id => 'a', amr => [qw( pwd mfa )] } ), 1, 'mfa in amr' );
is( $factor->verify( { id => 'a', amr => [qw( hwk )] } ), 1, 'hwk in amr' );
is( $factor->verify( { id => 'a', amr => [qw( pwd )] } ), 0, 'password only' );
is( $factor->verify( { id => 'a', amr => [] } ), 0, 'empty amr' );
is( $factor->verify( { id => 'a' } ), 0, 'no amr at all' );
is( $factor->verify( { id => 'a', acr => 'gold' } ), 0, 'an acr nobody configured means nothing' );
my $acr = Airlock::Factor::Upstream->new( accept_amr => [], accept_acr => [qw( gold silver )], now => sub { $clock } );
is( $acr->verify( { id => 'a', acr => 'gold' } ), 1, 'configured acr' );
is( $acr->verify( { id => 'a', acr => 'bronze' } ), 0, 'other acr' );
is( $acr->verify( { id => 'a', amr => ['otp'] } ), 0, 'amr is not accepted when the list is empty' );
is_deeply( $acr->reauth_params, { max_age => 0, acr_values => 'gold silver' }, 'reauth params carry the acr values' );
is_deeply( $factor->reauth_params, { max_age => 0 }, 'reauth params without acr values' );
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
1;
```
- [ ] **Step 5: `lib/Airlock/Factor/TOTP.pm` schreiben**
`lib/Airlock/Factor/TOTP.pm`:
```perl
package Airlock::Factor::TOTP;
# ABSTRACT: Time-based one-time password (RFC 6238) as an Airlock factor
use Moo;
with 'Airlock::Factor';
use Airlock::Code;
use Carp qw( croak );
use Crypt::URandom qw( urandom );
use Digest::SHA qw( hmac_sha1 );
use Types::Standard qw( CodeRef Int );
use namespace::autoclean;
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
is( $t->airlock->respond( 'post', '/device', { client_id => 'cli' }, {} )->[0], 200, 'method is case-insensitive' );
is_deeply( [ @{ $t->airlock->respond( 'POST', '/device', undef, {} ) }[ 0, 2 ] ], [ 400, { error => 'invalid_request' } ], 'unparseable parameters' );
};
subtest 'respond: token' => sub {
my $t = AirlockTest->new;
my $start = $t->airlock->respond( 'POST', '/device', { client_id => 'cli' }, {} )->[2];
my $poll = sub { [ @{ $t->airlock->respond( 'POST', '/token', { grant_type => $grant, client_id => 'cli', device_code => $start->{device_code}, @_ }, {} ) }[ 0, 2 ] ] };
is_deeply( $poll->(), [ 400, { error => 'authorization_pending' } ], 'pending' );
is_deeply( $poll->( grant_type => 'password' ), [ 400, { error => 'unsupported_grant_type' } ], 'another grant type' );
is_deeply( $poll->( grant_type => undef ), [ 400, { error => 'unsupported_grant_type' } ], 'no grant type' );
is_deeply( $poll->( device_code => undef ), [ 400, { error => 'invalid_request' } ], 'no device code' );
is_deeply( $poll->( client_id => 'open' ), [ 400, { error => 'invalid_grant' } ], 'another client' );
$t->airlock->approve( $start->{user_code}, subject => { id => 'alice' } );
$t->advance(5);
my $granted = $poll->();
is( $granted->[0], 200, 'granted' );
is( $granted->[1]{token_type}, 'Bearer', 'token response' );
ok( $t->airlock->verify_token( $granted->[1]{access_token} ), 'the token verifies' );
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
1;
```
`examples/lib/AirlockExample/StoreDBIO.pm`:
```perl
package AirlockExample::StoreDBIO;
# The four Airlock store subs on a DBIO schema.
#
# my $schema = AirlockExample::Schema->connect( $dsn, $user, $password );
# my $store = AirlockExample::StoreDBIO->new( schema => $schema );
# my $airlock = Airlock->new( store => $store->as_subs, ... );
use Moo;
use Carp qw( croak );
use namespace::autoclean;
has schema => ( is => 'ro', required => 1 );
has source => ( is => 'ro', default => 'Airlock' );
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
ok( !eval { $keycloak->subject($bad); 1 }, 'claims without sub croak' );
}
};
subtest 'factor' => sub {
my $factor = $keycloak->factor( max_age => 300, now => sub { 1000 } );
isa_ok( $factor, 'Airlock::Factor::Upstream' );
is( $factor->name, 'upstream', 'name' );
is( $factor->max_age, 300, 'options are passed on' );
is( $factor->verify( $keycloak->subject( { sub => 'x', amr => ['otp'], auth_time => 900 } ) ), 1, 'holds for a login with a second factor' );
is( $factor->verify( $keycloak->subject( { sub => 'x', amr => ['pwd'], auth_time => 900 } ) ), 0, 'not for a password login' );
my $by_acr = Airlock::Upstream::Keycloak->new( mfa_amr => [], mfa_acr => ['2'] )->factor;
is( $by_acr->verify( { id => 'x', acr => '2' } ), 1, 'mfa_acr configures the factor' );
is( $by_acr->verify( { id => 'x', acr => '1', amr => ['otp'] } ), 0, 'and mfa_amr can be emptied' );
};
done_testing;
```
- [ ] **Step 2: Test laufen lassen, er muss scheitern**
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
],
"users": [
{
"username": "plain",
"enabled": true,
"email": "plain@example.org",
"emailVerified": true,
"firstName": "Plain",
"lastName": "User",
"credentials": [
{ "type": "password", "value": "plain-password", "temporary": false }
]
},
{
"username": "otp",
"enabled": true,
"email": "otp@example.org",
"emailVerified": true,
"firstName": "Otp",
"lastName": "User",
"credentials": [
{ "type": "password", "value": "otp-password", "temporary": false },
{
"type": "otp",
"secretData": "{\"value\":\"12345678901234567890\"}",
"credentialData": "{\"subType\":\"totp\",\"digits\":6,\"counter\":0,\"period\":30,\"algorithm\":\"HmacSHA1\"}"
}
]
}
]
}
```
`t/keycloak/README.md`:
````markdown
# Keycloak live test
`t/90-live-keycloak.t` runs only when `TEST_AIRLOCK_KEYCLOAK_URL` is set. It
needs a Keycloak with the realm `airlock-test` from `realm.json` in this
directory: a public client `airlock-test-cli` with the device authorization
grant and direct access grants enabled, a user `plain` with a password, and a
user `otp` with a password and a TOTP credential whose secret is the RFC 6238
test secret `12345678901234567890`.
## Start a throwaway Keycloak
```bash
docker run --rm --name airlock-keycloak -p 8080:8080 \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
-v "$PWD/t/keycloak/realm.json:/opt/keycloak/data/import/realm.json:ro" \
quay.io/keycloak/keycloak:latest start-dev --import-realm
```
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
use Airlock::Upstream::Keycloak;
my $issuer = $ENV{TEST_AIRLOCK_KEYCLOAK_URL} =~ s{/+\z}{}r.'/realms/airlock-test';
my $http = HTTP::Tiny->new( timeout => 20 );
sub claims {
my ( $jwt ) = @_;
return decode_json( decode_base64url( ( split /\./, $jwt )[1] ) );
}
sub password_login {
my ( $token_endpoint, %form ) = @_;
my $response = $http->post_form( $token_endpoint, { grant_type => 'password', client_id => 'airlock-test-cli', scope => 'openid', %form } );
ok( $response->{success}, 'direct grant for '.$form{username} ) or diag $response->{content};
return decode_json( $response->{content} );
}
my $client = Airlock::Client->new(
issuer => $issuer,
client_id => 'airlock-test-cli',
scope => 'openid',
sleep => sub { sleep 1 },
on_prompt => sub { }
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
# the client expects; any other answer would croak with "poll failed".
ok( !eval { $client->poll( { %$start, interval => 1, expires_in => 3 } ); 1 }, 'polling without approval ends' );
like( $@, qr/the code expired before anyone approved it/, 'because the code ran out, not because of an unexpected answer' );
};
subtest 'what Keycloak says about a login with and without a second factor' => sub {
my $keycloak = Airlock::Upstream::Keycloak->new;
my $factor = $keycloak->factor;
my $totp = Airlock::Factor::TOTP->new( secret => sub { }, last_step => sub { }, accept_step => sub { } );
my $plain = password_login( $client->token_endpoint, username => 'plain', password => 'plain-password' );
my $otp = password_login(
$client->token_endpoint,
username => 'otp',
password => 'otp-password',
totp => $totp->code_at( '12345678901234567890', int( time / 30 ) )
);
for my $case ( [ plain => $plain ], [ otp => $otp ] ) {
my ( $name, $tokens ) = @$case;
for my $kind (qw( id_token access_token )) {
next unless $tokens->{$kind};
my $claims = claims( $tokens->{$kind} );
diag $name.' '.$kind.': acr='.( $claims->{acr} // '(none)' ).' amr='.( ref $claims->{amr} ? join( ',', @{ $claims->{amr} } ) : $claims->{amr} // '(none)' ).' auth_time='.( $claims->{auth_time} // '(none)' );
}
}
my $plain_subject = $keycloak->subject( claims( $plain->{id_token} ) );
my $otp_subject = $keycloak->subject( claims( $otp->{id_token} ) );
ok( length $plain_subject->{id}, 'the subject has an id' );
isnt( $plain_subject->{id}, $otp_subject->{id}, 'two users, two ids' );
is( $factor->verify($plain_subject), 0, 'a password login does not satisfy the upstream factor' );
is( $factor->verify($otp_subject), 1, 'a login with TOTP does' );
};
done_testing;
```
Run: `prove -lr t/90-live-keycloak.t` â Expected: `skipped: set TEST_AIRLOCK_KEYCLOAK_URL to run the Keycloak live test`.
- [ ] **Step 6: Keycloak starten und den Realm importieren**
examples/lib/AirlockExample/StoreDBIO.pm view on Meta::CPAN
package AirlockExample::StoreDBIO;
# The four Airlock store subs on a DBIO schema.
#
# my $schema = AirlockExample::Schema->connect( $dsn, $user, $password );
# my $store = AirlockExample::StoreDBIO->new( schema => $schema );
# my $airlock = Airlock->new( store => $store->as_subs, ... );
use Moo;
use Carp qw( croak );
use namespace::autoclean;
has schema => ( is => 'ro', required => 1 );
has source => ( is => 'ro', default => 'Airlock' );
lib/Airlock/Factor/TOTP.pm view on Meta::CPAN
package Airlock::Factor::TOTP;
# ABSTRACT: Time-based one-time password (RFC 6238) as an Airlock factor
use Moo;
with 'Airlock::Factor';
use Airlock::Code;
use Carp qw( croak );
use Crypt::URandom qw( urandom );
use Digest::SHA qw( hmac_sha1 );
use Types::Standard qw( CodeRef Int );
use namespace::autoclean;
lib/Airlock/Factor/TOTP.pm view on Meta::CPAN
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Airlock::Factor::TOTP - Time-based one-time password (RFC 6238) as an Airlock factor
=head1 VERSION
version 0.001
=head1 SYNOPSIS
my $totp = Airlock::Factor::TOTP->new(
secret => sub { my ( $subject ) = @_; $db->totp_secret( $subject->{id} ) },
last_step => sub { my ( $subject ) = @_; $db->totp_step( $subject->{id} ) },
lib/Airlock/Upstream/Authentik.pm view on Meta::CPAN
Unlike L<Airlock::Upstream::Keycloak>, there is nothing to configure in
authentik first. These are the claims of authentik 2026.8.3, observed through
the whole chain in F<t/91-live-authentik.t>, with the default flows and no
mapper added:
=over 4
=item *
A password login carries C<< amr => ['pwd'] >>, a login with TOTP
C<< amr => [ 'pwd', 'mfa' ] >>. The default L</mfa_amr> recognises C<mfa>, so
the factor tells the two apart out of the box.
=item *
C<acr> is C<goauthentik.io/providers/oauth2/default> for both, and is of no
use here. L</mfa_acr> is therefore empty, and C<acr_values> in an
authorization request does not change it either.
=item *
lib/Airlock/Upstream/Keycloak.pm view on Meta::CPAN
my $result = $airlock->approve( $code, subject => $keycloak->subject($claims) );
=head1 DESCRIPTION
When the host application logs people in through Keycloak, this class turns
the token claims into the subject L<Airlock> wants, and builds the
L<Airlock::Factor::Upstream> that recognises a Keycloak login with a second
factor.
A Keycloak realm in its default configuration does not report a second factor
in the token: with Keycloak 26.8.0 a password login and a login with TOTP both
carry C<acr=1> and no C<amr>. Two settings change that:
=over 4
=item *
the client, or a client scope it uses, has the protocol mapper
I<Authentication Method Reference (AMR)> (C<oidc-amr-mapper>);
=item *
the steps of the authentication flow carry a reference value
(C<default.reference.value>, with C<default.reference.maxAge>), for example
C<pwd> on the password form and C<otp> on the OTP form.
=back
A login with TOTP then carries C<< amr => [ 'pwd', 'otp' ] >>, which the
default L</mfa_amr> recognises. F<t/keycloak/setup.pl> in the distribution does
the second part through the Admin REST API, and F<t/90-live-keycloak.t> checks
the whole chain against a running Keycloak.
=head2 mfa_amr
t/41-factor-callback-upstream.t view on Meta::CPAN
subtest 'upstream' => sub {
my $clock = 10_000;
my $factor = Airlock::Factor::Upstream->new( now => sub { $clock } );
is( $factor->name, 'upstream', 'name' );
is( $factor->amr, 'mfa', 'amr' );
is( $factor->needs_proof, 0, 'needs no proof' );
is( $factor->verify( { id => 'a', amr => [qw( pwd otp )] } ), 1, 'otp in amr' );
is( $factor->verify( { id => 'a', amr => [qw( pwd mfa )] } ), 1, 'mfa in amr' );
is( $factor->verify( { id => 'a', amr => [qw( hwk )] } ), 1, 'hwk in amr' );
is( $factor->verify( { id => 'a', amr => [qw( pwd )] } ), 0, 'password only' );
is( $factor->verify( { id => 'a', amr => [] } ), 0, 'empty amr' );
is( $factor->verify( { id => 'a' } ), 0, 'no amr at all' );
is( $factor->verify( { id => 'a', acr => 'gold' } ), 0, 'an acr nobody configured means nothing' );
my $acr = Airlock::Factor::Upstream->new( accept_amr => [], accept_acr => [qw( gold silver )], now => sub { $clock } );
is( $acr->verify( { id => 'a', acr => 'gold' } ), 1, 'configured acr' );
is( $acr->verify( { id => 'a', acr => 'bronze' } ), 0, 'other acr' );
is( $acr->verify( { id => 'a', amr => ['otp'] } ), 0, 'amr is not accepted when the list is empty' );
is_deeply( $acr->reauth_params, { max_age => 0, acr_values => 'gold silver' }, 'reauth params carry the acr values' );
is_deeply( $factor->reauth_params, { max_age => 0 }, 'reauth params without acr values' );
t/45-upstream-keycloak.t view on Meta::CPAN
ok( !eval { $keycloak->subject($bad); 1 }, 'claims without sub croak' );
}
};
subtest 'factor' => sub {
my $factor = $keycloak->factor( max_age => 300, now => sub { 1000 } );
isa_ok( $factor, 'Airlock::Factor::Upstream' );
is( $factor->name, 'upstream', 'name' );
is( $factor->max_age, 300, 'options are passed on' );
is( $factor->verify( $keycloak->subject( { sub => 'x', amr => ['otp'], auth_time => 900 } ) ), 1, 'holds for a login with a second factor' );
is( $factor->verify( $keycloak->subject( { sub => 'x', amr => ['pwd'], auth_time => 900 } ) ), 0, 'not for a password login' );
my $by_acr = Airlock::Upstream::Keycloak->new( mfa_amr => [], mfa_acr => ['2'] )->factor;
is( $by_acr->verify( { id => 'x', acr => '2' } ), 1, 'mfa_acr configures the factor' );
is( $by_acr->verify( { id => 'x', acr => '1', amr => ['otp'] } ), 0, 'and mfa_amr can be emptied' );
};
done_testing;
t/46-upstream-authentik.t view on Meta::CPAN
subtest 'factor' => sub {
my $factor = $authentik->factor( max_age => 300, now => sub { 1000 } );
isa_ok( $factor, 'Airlock::Factor::Upstream' );
is( $factor->name, 'upstream', 'name' );
is( $factor->max_age, 300, 'options are passed on' );
# authentik writes mfa, and needs nothing configured to do it
is( $factor->verify( $authentik->subject( { sub => 'x', amr => [qw( pwd mfa )], acr => $acr, auth_time => 900 } ) ),
1, 'holds for a login with a second factor' );
is( $factor->verify( $authentik->subject( { sub => 'x', amr => ['pwd'], acr => $acr, auth_time => 900 } ) ),
0, 'not for a password login' );
# the one acr authentik sends says nothing, so it must not decide anything
is( $factor->verify( { id => 'x', acr => $acr } ), 0, 'the constant acr alone is not a second factor' );
is_deeply( $authentik->mfa_acr, [], 'and mfa_acr is empty by default' );
my $by_acr = Airlock::Upstream::Authentik->new( mfa_amr => [], mfa_acr => ['high'] )->factor;
is( $by_acr->verify( { id => 'x', acr => 'high' } ), 1, 'mfa_acr still configures the factor' );
is( $by_acr->verify( { id => 'x', acr => $acr, amr => ['mfa'] } ), 0, 'and mfa_amr can be emptied' );
};
subtest 'max_age against an old session with a fresh token' => sub {
t/60-endpoints.t view on Meta::CPAN
is( $t->airlock->respond( 'post', '/device', { client_id => 'cli' }, {} )->[0], 200, 'method is case-insensitive' );
is_deeply( [ @{ $t->airlock->respond( 'POST', '/device', undef, {} ) }[ 0, 2 ] ], [ 400, { error => 'invalid_request' } ], 'unparseable parameters' );
};
subtest 'respond: token' => sub {
my $t = AirlockTest->new;
my $start = $t->airlock->respond( 'POST', '/device', { client_id => 'cli' }, {} )->[2];
my $poll = sub { [ @{ $t->airlock->respond( 'POST', '/token', { grant_type => $grant, client_id => 'cli', device_code => $start->{device_code}, @_ }, {} ) }[ 0, 2 ] ] };
is_deeply( $poll->(), [ 400, { error => 'authorization_pending' } ], 'pending' );
is_deeply( $poll->( grant_type => 'password' ), [ 400, { error => 'unsupported_grant_type' } ], 'another grant type' );
is_deeply( $poll->( grant_type => undef ), [ 400, { error => 'unsupported_grant_type' } ], 'no grant type' );
is_deeply( $poll->( device_code => undef ), [ 400, { error => 'invalid_request' } ], 'no device code' );
is_deeply( $poll->( client_id => 'open' ), [ 400, { error => 'invalid_grant' } ], 'another client' );
$t->airlock->approve( $start->{user_code}, subject => { id => 'alice' } );
$t->advance(5);
my $granted = $poll->();
is( $granted->[0], 200, 'granted' );
is( $granted->[1]{token_type}, 'Bearer', 'token response' );
ok( $t->airlock->verify_token( $granted->[1]{access_token} ), 'the token verifies' );
t/90-live-keycloak.t view on Meta::CPAN
return $response;
}
# What a person does in the browser after the device showed its code: open the
# link, log in, give the one-time code if asked, and grant the device access.
sub approve_in_browser {
my ( $start, %login ) = @_;
my $browser = HTTP::Tiny->new( cookie_jar => HTTP::CookieJar->new, timeout => 20 );
my $page = $browser->get( $start->{verification_uri_complete} );
my $form = form( $page->{content} ) or return 'no login form at '.$start->{verification_uri_complete};
return 'the first page is not a login form' unless $form->{field}{username} && $form->{field}{password};
$page = submit( $browser, $form, username => $login{username}, password => $login{password} );
$form = form( $page->{content} ) or return 'nothing to continue with after the password';
if ( $form->{field}{otp} ) {
return 'Keycloak asked for a one-time code but the test has none for '.$login{username} unless $login{totp};
# Keycloak takes a code once. If an earlier run used this time step, the
# form comes back; then wait for the next step and try once more.
for my $attempt ( 1, 2 ) {
$page = submit( $browser, $form, otp => $totp->code_at( $login{totp}, int( time / 30 ) ) );
$form = form( $page->{content} ) or return 'nothing to continue with after the one-time code';
last unless $form->{field}{otp};
return 'the one-time code was refused twice' if $attempt == 2;
t/90-live-keycloak.t view on Meta::CPAN
# A poll that outlives a short deadline proves Keycloak answered
# authorization_pending the way the client expects; any other answer would
# croak with "poll failed".
ok( !eval { $client->poll( { %$start, interval => 1, expires_in => 3 } ); 1 }, 'polling without approval ends' );
like( $@, qr/the code expired before anyone approved it/, 'because the code ran out, not because of an unexpected answer' );
};
my %subject;
for my $case (
{ name => 'password only', username => 'plain', password => 'plain-password', amr => ['pwd'] },
{ name => 'password and TOTP', username => 'otp', password => 'otp-password', amr => [qw( pwd otp )], totp => $totp_secret }
)
{
subtest 'the whole device flow, logging in with '.$case->{name} => sub {
my $client = client();
my $start = $client->start;
my $before = time;
is( approve_in_browser( $start, %$case ), '', 'a person logs in and grants the device access' ) or return;
my $token = eval { $client->poll( { %$start, interval => 1, expires_in => 20 } ) };
ok( $token && $token->{access_token}, 'the client gets its token' ) or return diag $@;
t/90-live-keycloak.t view on Meta::CPAN
cmp_ok( $claims->{auth_time} // 0, '>=', $before - 60, 'auth_time is the login just made' );
is_deeply( claims( $token->{access_token} )->{amr}, $case->{amr}, 'the access token says the same' );
$subject{ $case->{username} } = Airlock::Upstream::Keycloak->new->subject($claims);
};
}
subtest 'the upstream factor on real Keycloak claims' => sub {
plan skip_all => 'needs both logins' unless $subject{plain} && $subject{otp};
my $factor = Airlock::Upstream::Keycloak->new->factor( max_age => 300 );
isnt( $subject{plain}{id}, $subject{otp}{id}, 'two people, two ids' );
is( $factor->verify( $subject{plain} ), 0, 'a password login does not hold' );
is( $factor->verify( $subject{otp} ), 1, 'a login with TOTP does' );
my $stale = Airlock::Upstream::Keycloak->new->factor( max_age => 300, now => sub { time + 400 } );
is( $stale->verify( $subject{otp} ), 0, 'but not once it is older than max_age' );
};
done_testing;
t/91-live-authentik.t view on Meta::CPAN
on_prompt => sub { }
);
}
# What a person does after the device showed its code: log in, then open the
# verification link, which authentik turns into one run of the authorization
# flow. Returns '' when the device was approved, otherwise what went wrong.
sub approve_in_browser {
my ( $start, %login ) = @_;
my $browser = AuthentikExecutor->new( base_url => $base );
eval { $browser->login( username => $login{username}, password => $login{password},
totp_secret => $login{totp} ); 1 } or return 'the login failed: '.( $@ =~ s/\n.*//sr );
my $who = $browser->whoami;
return 'the login did not make a session' unless $who && $who->{username} eq $login{username};
my $response = $browser->ua->get( $start->{verification_uri_complete} );
my $location = $response->header('Location')
or return 'the verification link answered '.$response->status_line.' instead of a redirect';
my ( $flow ) = $location =~ m{/if/flow/([^/?]+)};
return 'the verification link went to '.$location.' instead of a flow' unless $flow;
my ( $query ) = $location =~ m{\?(.*)\z};
my $challenge = eval { $browser->start( $flow, $query ) } or return 'the flow executor failed: '.( $@ =~ s/\n.*//sr );
return 'the approval flow stopped at '.( $challenge->{component} // 'nothing' ).' ('
.( $challenge->{error_message} // 'no message' ).')'
unless ( $challenge->{component} // '' ) eq 'ak-provider-oauth2-device-code-finish';
return '';
}
# a device of an earlier run would make the password-only login ask for a code
sub forget_totp {
my ( $username ) = @_;
my $user = $api->find_user($username) or return;
for my $device ( @{ $api->list_authenticators( $user->{pk} ) || [] } ) {
next unless ( $device->{type} // '' ) =~ /totp/i;
eval { $api->call( DELETE => '/authenticators/admin/totp/'.$device->{pk}.'/' ) };
}
return;
}
t/91-live-authentik.t view on Meta::CPAN
# authorization_pending the way the client expects; any other answer would
# croak with "poll failed".
ok( !eval { $client->poll( { %$start, interval => 1, expires_in => 3 } ); 1 }, 'polling without approval ends' );
like( $@, qr/the code expired before anyone approved it/, 'because the code ran out, not because of an unexpected answer' );
};
my ( %subject, $totp_secret );
subtest 'enrol TOTP for the second person' => sub {
my $browser = AuthentikExecutor->new( base_url => $base );
ok( eval { $browser->login( username => 'airlock-otp', password => 'airlock-otp-password' ); 1 },
'a password login first' ) or return diag $@;
$totp_secret = eval { $browser->enroll_totp };
ok( $totp_secret, 'the setup flow hands out a secret' ) or return diag $@;
my $user = $api->find_user('airlock-otp');
ok( scalar @{ $api->list_authenticators( $user->{pk} ) }, 'and the device shows up in the API' );
};
for my $case (
{ name => 'password only', username => 'airlock-plain', amr => ['pwd'] },
{ name => 'password and TOTP', username => 'airlock-otp', amr => [qw( pwd mfa )], totp => \$totp_secret }
)
{
subtest 'the whole device flow, logging in with '.$case->{name} => sub {
my %login = ( username => $case->{username}, password => $case->{username}.'-password',
$case->{totp} ? ( totp => ${ $case->{totp} } ) : () );
my $client = client();
my $start = start_device($client);
my $before = time;
is( approve_in_browser( $start, %login ), '', 'a person logs in and grants the device access' ) or return;
my $token = eval { $client->poll( { %$start, interval => 1, expires_in => 30 } ) };
ok( $token && $token->{access_token}, 'the client gets its token' ) or return diag $@;
my $claims = claims( $token->{id_token} );
diag $case->{username}.': acr='.( $claims->{acr} // '(none)' ).' amr='.join( ',', @{ $claims->{amr} || [] } )
t/91-live-authentik.t view on Meta::CPAN
cmp_ok( $claims->{auth_time} // 0, '>=', $before - 60, 'auth_time is the login just made' );
is_deeply( claims( $token->{access_token} )->{amr}, $case->{amr}, 'the access token says the same' );
$subject{ $case->{username} } = Airlock::Upstream::Authentik->new->subject($claims);
};
}
subtest 'the upstream factor on real authentik claims' => sub {
plan skip_all => 'needs both logins' unless $subject{'airlock-plain'} && $subject{'airlock-otp'};
my $factor = Airlock::Upstream::Authentik->new->factor( max_age => 300 );
isnt( $subject{'airlock-plain'}{id}, $subject{'airlock-otp'}{id}, 'two people, two ids' );
is( $factor->verify( $subject{'airlock-plain'} ), 0, 'a password login does not hold' );
is( $factor->verify( $subject{'airlock-otp'} ), 1, 'a login with TOTP does' );
my $stale = Airlock::Upstream::Authentik->new->factor( max_age => 300, now => sub { time + 400 } );
is( $stale->verify( $subject{'airlock-otp'} ), 0, 'but not once it is older than max_age' );
};
subtest 'an Airlock approval with a subject from a real login' => sub {
plan skip_all => 'needs both logins' unless $subject{'airlock-plain'} && $subject{'airlock-otp'};
my $upstream = Airlock::Upstream::Authentik->new;
my $airlock = Airlock->new(
clients => { 'airlock-test-device' => { scopes => ['admin'] } },
verification_uri => 'https://example.org/airlock',
policy => { always => ['upstream'] },
factors => [ $upstream->factor( max_age => 300 ) ]
);
my $refused = $airlock->open( client_id => 'airlock-test-device', scope => 'admin' );
ok( $refused->ok, 'a device opens a request' );
my $answer = $airlock->approve( $refused->data->{user_code}, subject => $subject{'airlock-plain'} );
is( $answer->status, 'reauth_required', 'the password-only login may not approve it' );
is_deeply( $answer->missing, ['upstream'], 'and is told which factor is missing' );
my $granted = $airlock->open( client_id => 'airlock-test-device', scope => 'admin' );
is( $airlock->approve( $granted->data->{user_code}, subject => $subject{'airlock-otp'} )->status,
'approved', 'the login with TOTP may' );
my $token = $airlock->redeem( device_code => $granted->data->{device_code}, client_id => 'airlock-test-device' );
ok( $token->ok && $token->data->{access_token}, 'and the device redeems its token' );
# the opaque token response carries no amr; the grant behind it does
my $grant = $airlock->verify_token( $token->data->{access_token} );
ok( $grant, 'the token verifies' ) or return;
t/91-live-authentik.t view on Meta::CPAN
ok( scalar( grep { $_ eq 'mfa' } @{ $grant->{amr} } ), 'and the grant records the second factor' )
or diag 'amr: '.join ' ', @{ $grant->{amr} };
is( $grant->{auth_time}, $subject{'airlock-otp'}{auth_time}, 'and the authentik auth_time' );
};
subtest 'an old session with a fresh token' => sub {
plan skip_all => 'needs the TOTP login' unless $subject{'airlock-otp'} && $totp_secret;
# authentik mints a new token from the session that is already there, and
# auth_time stays the moment that session began
my $browser = AuthentikExecutor->new( base_url => $base );
ok( eval { $browser->login( username => 'airlock-otp', password => 'airlock-otp-password',
totp_secret => $totp_secret ); 1 }, 'log in once' ) or return diag $@;
my $oidc = WWW::Authentik->new( base_url => $base, application => $slug )->oidc;
my %authorize = ( client_id => $client_id, redirect_uri => 'http://127.0.0.1:1/callback',
scope => 'openid', state => 's', nonce => 'n' );
my $first = claims( $oidc->exchange_authorization_code( client_id => $client_id,
redirect_uri => $authorize{redirect_uri}, code => $browser->authorization_code(%authorize) )->{id_token} );
sleep 3;
my $later = claims( $oidc->exchange_authorization_code( client_id => $client_id,
redirect_uri => $authorize{redirect_uri}, code => $browser->authorization_code(%authorize) )->{id_token} );
is( $later->{auth_time}, $first->{auth_time}, 'the second token carries the auth_time of the first login' );
t/authentik/README.md view on Meta::CPAN
`AUTHENTIK_BOOTSTRAP_TOKEN` from that `.env` is the API token below.
## Build the fixtures
```bash
perl -I ~/dev/p5-www-authentik/lib t/authentik/setup.pl http://127.0.0.1:9000 "$AUTHENTIK_BOOTSTRAP_TOKEN"
```
It makes an application `airlock-test` with a public OAuth2 provider that can do
the device flow, two users (`airlock-plain` and `airlock-otp`, password
`<username>-password`), and an empty flow that the brand needs as its
`flow_device_code` before anyone can approve a device code at `/device`. Every
step is an `ensure_*`, so it can be run again at any time. `--remove` as a third
argument takes it all away again.
Unlike Keycloak, authentik needs **nothing** configured to report a second
factor, so the script does not touch any mapper or flow step. Enrolling the TOTP
device is the test's own job: it goes through the setup flow the way a person
would, and deletes the device again at the end.
## Run
t/authentik/README.md view on Meta::CPAN
here: the shape of a flow challenge belongs to authentik and changes with its
versions, a copy would drift unnoticed, and a distribution that ships no
provider code should not carry two hundred lines of one.
## Findings
authentik 2026.8.3, recorded 2026-10-04, through the whole chain.
| Login | acr | amr | auth_time |
|---|---|---|---|
| device flow, browser login, password | `goauthentik.io/providers/oauth2/default` | `pwd` | time of login |
| device flow, browser login, password + TOTP | the same | `pwd`, `mfa` | time of login |
| a second token from the same session | the same | unchanged | **the first login**, not the new token |
| a refreshed token | the same | unchanged | unchanged |
What the runs established:
- **authentik reports the second factor out of the box.** No mapper, no scope,
no flow setting: a password login carries `amr=pwd`, a login with TOTP
`amr=pwd,mfa`, and `Airlock::Factor::Upstream` tells them apart with its
defaults. This is the difference to Keycloak, which says nothing until
`t/keycloak/setup.pl` has run.
- **`acr` is one constant string** whatever happened, so `mfa_acr` stays empty
in `Airlock::Upstream::Authentik`. Sending `acr_values` changes nothing.
- **`auth_time` is when the session began** for the grants Airlock meets â the
authorization code and the device code both take it from the session's login
event â and it survives a refresh and further authorization requests.
`max_age` on the factor therefore measures the age of the authentication,
which is what a caller wants: a token minted now from a ten-minute-old
t/authentik/setup.pl view on Meta::CPAN
#!/usr/bin/env perl
# Builds the fixtures t/91-live-authentik.t needs in a throwaway authentik.
#
# perl -I ~/dev/p5-www-authentik/lib t/authentik/setup.pl http://127.0.0.1:9000 API_TOKEN
#
# Unlike Keycloak, authentik needs nothing configured to report a second
# factor: a password login carries amr=pwd and a login with TOTP amr=pwd,mfa
# out of the box. So this script only creates what the test works with - an
# application with an OAuth2 provider that can do the device flow, a user with
# a password, a second user with a password, and the flow the brand needs
# before anyone can approve a device code. Enrolling the TOTP device is the
# test's own job, because it goes through the setup flow as a person would.
#
# It can be run any number of times; every call is an ensure_*.
#
# Checked against authentik 2026.8.3.
use strict;
use warnings;
use WWW::Authentik;
t/authentik/setup.pl view on Meta::CPAN
provider => $provider->{pk},
meta_description => 'Fixture of t/91-live-authentik.t in the Airlock distribution'
) );
for my $person ( [ 'airlock-plain', 'Airlock plain' ], [ 'airlock-otp', 'Airlock with TOTP' ] ) {
my ( $username, $name ) = @$person;
report( 'user '.$username, $api->ensure_user(
username => $username,
name => $name,
email => $username.'@example.org',
password => $username.'-password'
) );
}
print "\nclient_id: ", $provider->{client_id}, "\n";
print "run the test with:\n";
print " TEST_AIRLOCK_AUTHENTIK_URL=$base \\\n";
print " TEST_AIRLOCK_AUTHENTIK_TOKEN=... \\\n";
print " prove -lv t/91-live-authentik.t\n";
t/keycloak/README.md view on Meta::CPAN
# Keycloak live test
`t/90-live-keycloak.t` runs only when `TEST_AIRLOCK_KEYCLOAK_URL` is set. It
needs a Keycloak with the realm `airlock-test` from `realm.json` in this
directory: a public client `airlock-test-cli` with the device authorization
grant and direct access grants enabled, a user `plain` with a password, and a
user `otp` with a password and a TOTP credential whose secret is the RFC 6238
test secret `12345678901234567890`.
## Start a throwaway Keycloak
On Kubernetes (`k8s.yaml` in this directory; no persistence, NodePort service):
```bash
kubectl create namespace airlock-test
kubectl -n airlock-test create configmap airlock-realm --from-file=realm.json=t/keycloak/realm.json
kubectl -n airlock-test apply -f t/keycloak/k8s.yaml
t/keycloak/README.md view on Meta::CPAN
```bash
perl -I ~/dev/p5-www-keycloak/lib t/keycloak/setup.pl http://localhost:8080
```
The script uses `WWW::Keycloak` (repository `p5-www-keycloak`); point `-I` at
its `lib` until it is installed.
A default realm puts no `amr` into its tokens. Two things change that. The
client needs the AMR protocol mapper; that is part of `realm.json`. And each
step of the authentication flows needs a reference value, which `setup.pl` sets
through the Admin REST API: `pwd` on the password steps and `otp` on the OTP
steps of the `browser` and `direct grant` flows. The script can be run again at
any time; a restarted pod has lost the setting and needs it again.
## Run
```bash
TEST_AIRLOCK_KEYCLOAK_URL=http://localhost:8080 prove -lv t/90-live-keycloak.t
```
The test starts a device flow with `Airlock::Client`, logs in the way a browser
t/keycloak/README.md view on Meta::CPAN
the client receives. It needs `HTTP::CookieJar`. Keycloak accepts a one-time
code once; when two runs fall into the same 30 seconds the test waits for the
next code, so a run can take half a minute.
## Findings
Keycloak 26.8.0, recorded 2026-10-02.
| Realm | Login | acr | amr | auth_time |
|---|---|---|---|---|
| as imported, before `setup.pl` and without the AMR mapper | direct grant, password | `1` | absent | absent |
| as imported, before `setup.pl` and without the AMR mapper | direct grant, password + TOTP | `1` | absent | absent |
| with mapper and reference values | device flow, browser login, password | `1` | `pwd` | time of login |
| with mapper and reference values | device flow, browser login, password + TOTP | `1` | `pwd`, `otp` | time of login |
| with mapper and reference values | direct grant, password + TOTP | `1` | `pwd`, `otp` | absent |
What the runs established:
- `realm.json` imports as written, including the OTP credential.
- `Airlock::Client` completes a device flow against Keycloak: discovery, start,
`authorization_pending` while waiting, and the token after the approval. The
device response carries `verification_uri_complete`.
- **A default realm does not say in the token whether a second factor was
used.** With the AMR mapper and the reference values it does, and
`Airlock::Factor::Upstream` with its default `accept_amr` then tells the two
t/keycloak/realm.json view on Meta::CPAN
"users": [
{
"username": "plain",
"enabled": true,
"email": "plain@example.org",
"emailVerified": true,
"firstName": "Plain",
"lastName": "User",
"credentials": [
{
"type": "password",
"value": "plain-password",
"temporary": false
}
]
},
{
"username": "otp",
"enabled": true,
"email": "otp@example.org",
"emailVerified": true,
"firstName": "Otp",
"lastName": "User",
"credentials": [
{
"type": "password",
"value": "otp-password",
"temporary": false
},
{
"type": "otp",
"secretData": "{\"value\":\"12345678901234567890\"}",
"credentialData": "{\"subType\":\"totp\",\"digits\":6,\"counter\":0,\"period\":30,\"algorithm\":\"HmacSHA1\"}"
}
]
}
]
t/keycloak/setup.pl view on Meta::CPAN
#!/usr/bin/env perl
# Makes the test realm report how someone logged in.
#
# perl -I ~/dev/p5-www-keycloak/lib t/keycloak/setup.pl http://localhost:8080 [admin-user] [admin-password]
#
# Keycloak only puts an "amr" claim into a token when the client has the AMR
# protocol mapper and the steps of the authentication flows carry a reference
# value. The mapper is in realm.json; the reference values cannot be imported
# without spelling out every built-in flow, so this script sets both through
# the Admin REST API with WWW::Keycloak. It can be run any number of times.
#
# Checked against Keycloak 26.8.0.
use strict;
use warnings;
use WWW::Keycloak;
my ( $base, $user, $password ) = @ARGV;
die 'usage: setup.pl KEYCLOAK_URL [admin-user] [admin-password]'."\n" unless $base;
my $admin = WWW::Keycloak->new(
base_url => $base,
realm => 'airlock-test',
username => $user // 'admin',
password => $password // 'admin'
)->admin;
# how long, in seconds, a passed step counts towards amr
my $max_age = 3600;
sub report {
my ( $what, $result ) = @_;
printf "%-8s %s\n", $result->{changed} || 'ok', $what;
return;
}
report( 'client airlock-test-cli: AMR mapper', $admin->ensure_protocol_mapper(
client => 'airlock-test-cli',
name => 'amr',
protocolMapper => 'oidc-amr-mapper',
config => { map { $_ => 'true' } qw( id.token.claim access.token.claim introspection.token.claim userinfo.token.claim ) }
) );
for my $step (
[ 'browser', 'auth-username-password-form', 'pwd' ],
[ 'browser', 'auth-otp-form', 'otp' ],
[ 'direct grant', 'direct-grant-validate-password', 'pwd' ],
[ 'direct grant', 'direct-grant-validate-otp', 'otp' ]
)
{
my ( $flow, $authenticator, $amr ) = @$step;
report( $flow.' / '.$authenticator.' => '.$amr, $admin->ensure_execution_config(
flow => $flow,
authenticator => $authenticator,
alias => 'amr '.$flow.' '.$authenticator,
config => { 'default.reference.value' => $amr, 'default.reference.maxAge' => $max_age }
) );