Airlock
view release on metacpan or search on metacpan
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
like( $@, qr/otpauth_uri needs issuer/, 'and says what is missing' );
};
subtest 'construction' => sub {
ok( !eval { Airlock::Factor::TOTP->new( secret => sub { }, last_step => sub { } ); 1 }, 'accept_step is required' );
ok( !eval { Airlock::Factor::TOTP->new( secret => sub { }, accept_step => sub { } ); 1 }, 'last_step is required' );
};
done_testing;
```
`t/41-factor-callback-upstream.t`:
```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Airlock::Factor::Callback;
use Airlock::Factor::Upstream;
subtest 'callback' => sub {
my @seen;
my $factor = Airlock::Factor::Callback->new(
name => 'pin',
amr => 'pin',
verify => sub { push @seen, [@_]; $_[1] eq '4711' }
);
is( $factor->name, 'pin', 'name' );
is( $factor->amr, 'pin', 'amr' );
is( $factor->needs_proof, 1, 'needs a proof' );
is( $factor->available_for( { id => 'alice' } ), 1, 'available to everyone without an available sub' );
is( $factor->verify( { id => 'alice' }, '4711' ), 1, 'right proof' );
is( $factor->verify( { id => 'alice' }, '0000' ), 0, 'wrong proof' );
is_deeply( $seen[0], [ { id => 'alice' }, '4711' ], 'the sub gets subject and proof' );
my $limited = Airlock::Factor::Callback->new(
name => 'pin',
amr => 'pin',
verify => sub { 1 },
available => sub { $_[0]{id} eq 'alice' }
);
is( $limited->available_for( { id => 'alice' } ), 1, 'available sub: yes' );
is( $limited->available_for( { id => 'bob' } ), 0, 'available sub: no' );
ok( !eval { Airlock::Factor::Callback->new( name => 'pin', amr => 'pin' ); 1 }, 'verify is required' );
ok( !eval { Airlock::Factor::Callback->new( amr => 'pin', verify => sub { 1 } ); 1 }, 'name is required' );
};
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' );
my $fresh = Airlock::Factor::Upstream->new( max_age => 300, now => sub { $clock } );
is( $fresh->verify( { id => 'a', amr => ['otp'], auth_time => 9_700 } ), 1, 'exactly max_age old' );
is( $fresh->verify( { id => 'a', amr => ['otp'], auth_time => 9_699 } ), 0, 'one second too old' );
is( $fresh->verify( { id => 'a', amr => ['otp'] } ), 0, 'no auth_time counts as too old' );
is( $fresh->verify( { id => 'a', amr => ['pwd'], auth_time => 9_999 } ), 0, 'fresh but weak' );
};
done_testing;
```
`t/42-policy.t`:
```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Airlock::Policy;
subtest 'empty policy' => sub {
my $policy = Airlock::Policy->new;
is_deeply( $policy->required( { scopes => [qw( read admin )] }, { id => 'a' } ), [], 'nothing required' );
is( $policy->fresh( { id => 'a' }, 1000 ), 1, 'always fresh' );
};
subtest 'always and step_up' => sub {
my $policy = Airlock::Policy->new(
always => ['upstream'],
step_up => { admin => ['totp'], delete => [qw( totp pin )] }
);
is_deeply( $policy->required( { scopes => ['read'] }, {} ), ['upstream'], 'plain scope' );
is_deeply( $policy->required( { scopes => [qw( read admin )] }, {} ), [qw( upstream totp )], 'step-up scope' );
is_deeply( $policy->required( { scopes => [qw( admin delete )] }, {} ), [qw( upstream totp pin )], 'no duplicates, stable order' );
is_deeply( $policy->required( { scopes => [] }, {} ), ['upstream'], 'no scopes' );
is_deeply( $policy->required( {}, {} ), ['upstream'], 'request without scopes key' );
};
subtest 'decide' => sub {
my @seen;
my $policy = Airlock::Policy->new(
step_up => { admin => ['totp'] },
decide => sub {
my ( $request, $subject, $names ) = @_;
push @seen, [ $request, $subject, [@$names] ];
return $subject->{id} eq 'root' ? [ @$names, 'pin' ] : $names;
}
);
is_deeply( $policy->required( { scopes => ['admin'] }, { id => 'root' } ), [qw( totp pin )], 'coderef extends the list' );
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
},
);
=description
For a host application that already has a second factor somewhere else, for
example in its directory server. Airlock hands over subject and proof and
takes the answer.
=cut
has _verify => (
is => 'ro',
isa => CodeRef,
init_arg => 'verify',
required => 1
);
=attr verify
Required. Coderef called with the subject and the proof; returns true when the
proof holds.
=cut
has _available => (
is => 'ro',
isa => CodeRef,
init_arg => 'available',
predicate => '_has_available'
);
=attr available
Optional. Coderef called with the subject; returns true when the subject can
use this factor. Without it the factor is available to everyone.
=cut
sub verify {
my ( $self, $subject, $proof ) = @_;
return $self->_verify->( $subject, $proof ) ? 1 : 0;
}
sub available_for {
my ( $self, $subject ) = @_;
return 1 unless $self->_has_available;
return $self->_available->($subject) ? 1 : 0;
}
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;
our $VERSION = '0.001';
=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} ) },
accept_step => sub { my ( $subject, $step ) = @_; $db->set_totp_step( $subject->{id}, $step ) },
);
# enrolment
my $secret = $totp->generate_secret;
my $uri = $totp->otpauth_uri( secret => $secret, account => 'getty@example.org', issuer => 'Mothership' );
=description
TOTP with HMAC-SHA1, which is what authenticator apps implement. Airlock stores
nothing itself: the secret and the last accepted time step come from the host
application through three coderefs.
A code is accepted once. C<last_step> and C<accept_step> are what make that
true, which is why both are required.
=cut
has '+name' => ( default => 'totp' );
has '+amr' => ( default => 'otp' );
has _secret => (
is => 'ro',
isa => CodeRef,
init_arg => 'secret',
required => 1
);
=attr secret
Required. Coderef called with the subject; returns the raw secret bytes, or
nothing when the subject has not enrolled.
=cut
has _last_step => (
is => 'ro',
isa => CodeRef,
init_arg => 'last_step',
required => 1
);
=attr last_step
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
`t/60-endpoints.t`:
```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use lib 't/lib';
use JSON::MaybeXS;
use AirlockTest;
my $grant = 'urn:ietf:params:oauth:grant-type:device_code';
sub psgi {
my ( $app, %arg ) = @_;
my $body = $arg{body} // '';
CORE::open( my $input, '<', \$body ) or die $!;
my $response = $app->( {
REQUEST_METHOD => $arg{method} // 'POST',
PATH_INFO => $arg{path},
CONTENT_TYPE => exists $arg{type} ? $arg{type} : 'application/x-www-form-urlencoded',
CONTENT_LENGTH => exists $arg{length} ? $arg{length} : length $body,
REMOTE_ADDR => '192.0.2.9',
HTTP_USER_AGENT => 'test-agent/1.0',
'psgi.input' => $input
} );
my %header = @{ $response->[1] };
return ( $response->[0], \%header, decode_json( join '', @{ $response->[2] } ) );
}
subtest 'respond: routes' => sub {
my $t = AirlockTest->new;
my ( $status, $headers, $json ) = @{ $t->airlock->respond( 'POST', '/device', { client_id => 'cli', scope => 'read' }, { ip => '192.0.2.9' } ) };
is( $status, 200, 'device: 200' );
is( $headers->{'Content-Type'}, 'application/json', 'content type' );
is( $headers->{'Cache-Control'}, 'no-store', 'no-store' );
ok( $json->{device_code} && $json->{user_code}, 'device authorization response' );
for my $path ( '/airlock/device', 'device', '/device/', '/a/b/c/device' ) {
is( $t->airlock->respond( 'POST', $path, { client_id => 'cli' }, {} )->[0], 200, 'mounted at '.$path );
}
is_deeply( [ @{ $t->airlock->respond( 'POST', '/nope', {}, {} ) }[ 0, 2 ] ], [ 404, { error => 'not_found' } ], 'unknown route' );
is( $t->airlock->respond( 'POST', '/devices', {}, {} )->[0], 404, 'a longer segment is not the route' );
is( $t->airlock->respond( 'POST', '', {}, {} )->[0], 404, 'empty path' );
is( $t->airlock->respond( 'POST', undef, {}, {} )->[0], 404, 'undef path' );
my $get = $t->airlock->respond( 'GET', '/device', { client_id => 'cli' }, {} );
is( $get->[0], 405, 'GET is refused' );
is( $get->[1]{Allow}, 'POST', 'with an Allow header' );
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' );
};
subtest 'parse_form' => sub {
my $airlock = AirlockTest->new->airlock;
is_deeply( $airlock->parse_form('a=1&b=two'), { a => 1, b => 'two' }, 'pairs' );
is_deeply( $airlock->parse_form('scope=read+write&x=%41%2fb%3D'), { scope => 'read write', x => 'A/b=' }, 'plus and percent' );
is_deeply( $airlock->parse_form('a=1=2'), { a => '1=2' }, 'only the first = splits' );
is_deeply( $airlock->parse_form('flag&b='), { flag => '', b => '' }, 'no value and empty value' );
is_deeply( $airlock->parse_form(''), {}, 'empty' );
is_deeply( $airlock->parse_form(undef), {}, 'undef' );
is_deeply( $airlock->parse_form('&&a=1&'), { a => 1 }, 'empty pairs are skipped' );
is( $airlock->parse_form('a=1&a=2'), undef, 'a repeated parameter is refused' );
is_deeply( $airlock->parse_form('a=%zz'), { a => '%zz' }, 'a broken escape stays as it is' );
};
subtest 'to_app' => sub {
my $t = AirlockTest->new;
my $app = $t->airlock->to_app;
my ( $status, $headers, $json ) = psgi( $app, path => '/device', body => 'client_id=cli&scope=read+write' );
is( $status, 200, 'device: 200' );
is( $headers->{'Content-Type'}, 'application/json', 'content type' );
is( $headers->{'Cache-Control'}, 'no-store', 'no-store' );
my $row = $t->row( $json->{device_code} );
is( $row->{scope}, 'read write', 'the form body was decoded' );
is( $row->{origin_ip}, '192.0.2.9', 'origin ip from REMOTE_ADDR' );
is( $row->{origin_ua}, 'test-agent/1.0', 'origin ua from the header' );
my $token_body = 'grant_type='.$grant =~ s/:/%3A/gr.'&client_id=cli&device_code='.$json->{device_code};
is_deeply( [ ( psgi( $app, path => '/token', body => $token_body ) )[ 0, 2 ] ], [ 400, { error => 'authorization_pending' } ], 'token: pending' );
is( ( psgi( $app, path => '/device', method => 'GET' ) )[0], 405, 'GET' );
is( ( psgi( $app, path => '/other', body => 'client_id=cli' ) )[0], 404, 'unknown route' );
is_deeply( [ ( psgi( $app, path => '/device', body => 'client_id=cli&client_id=open' ) )[ 0, 2 ] ], [ 400, { error => 'invalid_request' } ], 'repeated parameter' );
is_deeply( [ ( psgi( $app, path => '/device', body => '{"client_id":"cli"}', type => 'application/json' ) )[ 0, 2 ] ], [ 400, { error => 'invalid_client' } ], 'a JSON body is not read' );
is( ( psgi( $app, path => '/device', body => 'client_id=cli', type => 'application/x-www-form-urlencoded; charset=UTF-8' ) )[0], 200, 'content type with a charset' );
is( ( psgi( $app, path => '/device', body => 'client_id=cli', type => undef ) )[0], 400, 'no content type' );
is( ( psgi( $app, path => '/device', body => 'client_id=cli&pad='.( 'x' x 20000 ) ) )[0], 413, 'a body over the limit is refused unread' );
is( ( psgi( $app, path => '/device', body => 'client_id=cli', length => 100 ) )[0], 200, 'a body shorter than its Content-Length does not hang' );
is( ( psgi( $app, path => '/device', body => '', length => 0 ) )[0], 400, 'an empty body' );
};
done_testing;
```
`t/61-httpmessage.t`:
```perl
#!/usr/bin/env perl
use strict;
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
- [ ] **Step 5: Den DBIO-Store schreiben**
`examples/lib/AirlockExample/Schema.pm`:
```perl
package AirlockExample::Schema;
# DBIO schema for the Airlock table. Used by AirlockExample::StoreDBIO.
use DBIO 'Schema';
__PACKAGE__->load_namespaces;
1;
```
`examples/lib/AirlockExample/Schema/Result/Airlock.pm`:
```perl
package AirlockExample::Schema::Result::Airlock;
# The Airlock table as a DBIO result class. Same columns as examples/schema.sql.
use DBIO::Candy;
table 'airlock';
primary_column hash => { data_type => 'varchar', size => 64 };
column kind => { data_type => 'varchar', size => 16 };
column user_code => { data_type => 'varchar', size => 16, is_nullable => 1 };
column client_id => { data_type => 'varchar', size => 255 };
column scope => { data_type => 'text' };
column state => { data_type => 'varchar', size => 16 };
column created => { data_type => 'bigint' };
column expires => { data_type => 'bigint' };
column poll_interval => { data_type => 'integer', is_nullable => 1 };
column last_poll => { data_type => 'bigint', is_nullable => 1 };
column subject => { data_type => 'varchar', size => 255, is_nullable => 1 };
column amr => { data_type => 'varchar', size => 255, is_nullable => 1 };
column acr => { data_type => 'varchar', size => 255, is_nullable => 1 };
column auth_time => { data_type => 'bigint', is_nullable => 1 };
column approved => { data_type => 'bigint', is_nullable => 1 };
column origin_ip => { data_type => 'varchar', size => 64, is_nullable => 1 };
column origin_ua => { data_type => 'varchar', size => 255, is_nullable => 1 };
column factor_failures => { data_type => 'integer', default_value => 0 };
unique_constraint airlock_user_code => ['user_code'];
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' );
sub _rs { $_[0]->schema->resultset( $_[0]->source ) }
sub insert {
my ( $self, $row ) = @_;
$self->_rs->create( { %$row } );
return 1;
}
sub find {
my ( $self, $field, $value ) = @_;
croak __PACKAGE__.'->find by '.$field.' is not supported' unless $field eq 'hash' || $field eq 'user_code';
return unless defined $value;
my $row = $self->_rs->search( { $field => $value } )->single or return;
return { $row->get_columns };
}
# One UPDATE ... WHERE hash = ? AND state = ?. A resultset update returns the
# number of rows it changed, as '0E0' when there were none.
sub update {
my ( $self, $hash, $from_state, $changes ) = @_;
return $self->_rs->search( { hash => $hash, state => $from_state } )->update( { %$changes } ) > 0 ? 1 : 0;
}
sub purge {
my ( $self, $before ) = @_;
return $self->_rs->search( { expires => { '<' => $before } } )->delete + 0;
}
sub as_subs {
my ( $self ) = @_;
return {
insert => sub { $self->insert(@_) },
find => sub { $self->find(@_) },
update => sub { $self->update(@_) },
purge => sub { $self->purge(@_) }
};
}
1;
```
- [ ] **Step 6: Store-Tests laufen lassen**
Run: `prove -lr t/80-example-store-dbi.t t/81-example-store-dbio.t`
Expected: PASS (je 2 Subtests).
- [ ] **Step 7: Die gemeinsame Demo-Logik schreiben**
Login und CSRF-Schutz gehören der Host-App. Das Beispiel markiert beide Stellen mit einem Kommentar in GroÃbuchstaben, statt sie vorzutäuschen.
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
Commit-fertig lassen, Karte nach `review`. Betreff: `Add examples and README`; `Changes`: `- Examples: Plack and Mojolicious host apps, store on DBI and DBIO, device CLI`.
---
### Task 9: Keycloak: Abbildung und Live-Test
Spec: Abschnitt 7. **Diese Aufgabe braucht ein laufendes Keycloak und ist die einzige, deren Inhalt ungeprüft ist.** Wo dieses Keycloak läuft, entscheidet der Maintainer; nicht auf einer Maschine mit knappem Speicher starten. Schritte 1 bis 5 gehen...
Was hier als Annahme steht und vom Live-Test bestätigt oder widerlegt wird:
- der Aufbau von `t/keycloak/realm.json`, besonders das OTP-Credential des Nutzers `otp` und das Client-Attribut für den Device-Grant;
- dass Keycloaks Direct Grant den Parameter `totp` annimmt;
- dass ein Login mit TOTP im Token an `amr` oder `acr` erkennbar ist und die Standardwerte `mfa_amr => [qw( mfa otp hwk )]`, `mfa_acr => []` dafür passen.
**Files:**
- Create: `lib/Airlock/Upstream/Keycloak.pm`
- Create: `t/keycloak/realm.json`, `t/keycloak/README.md`
- Test: `t/45-upstream-keycloak.t`, `t/90-live-keycloak.t`
- Modify: `t/00-load.t`
**Interfaces:**
- Consumes: `Airlock::Factor::Upstream->new( accept_amr =>, accept_acr =>, max_age =>, now => )` und `Airlock::Factor::TOTP->code_at` (Aufgabe 4); `Airlock::Client` mit `issuer`, `->device_endpoint`, `->token_endpoint`, `->start`, `->poll` (Aufgabe 7...
- Produces: `Airlock::Upstream::Keycloak->new( mfa_amr => [...], mfa_acr => [...] )`; `->subject(\%claims)` â `{ id, amr, acr, auth_time }`; `->factor(%upstream_opts)` â `Airlock::Factor::Upstream`.
- [ ] **Step 1: Den Unit-Test schreiben**
`t/45-upstream-keycloak.t`:
```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Airlock::Upstream::Keycloak;
my $keycloak = Airlock::Upstream::Keycloak->new;
subtest 'subject' => sub {
is_deeply(
$keycloak->subject( { sub => 'f:1234:alice', amr => [qw( pwd otp )], acr => '1', auth_time => 1700000000, email => 'a@example.org' } ),
{ id => 'f:1234:alice', amr => [qw( pwd otp )], acr => '1', auth_time => 1700000000 },
'sub, amr, acr and auth_time are taken, nothing else'
);
is_deeply( $keycloak->subject( { sub => 'x' } ), { id => 'x', amr => [], acr => undef, auth_time => undef }, 'a token without the optional claims' );
is_deeply( $keycloak->subject( { sub => 'x', amr => 'pwd otp' } )->{amr}, [qw( pwd otp )], 'amr as a string is split' );
my $claims = { sub => 'x', amr => ['pwd'] };
push @{ $keycloak->subject($claims)->{amr} }, 'otp';
is_deeply( $claims->{amr}, ['pwd'], 'the claims are not modified through the subject' );
for my $bad ( undef, {}, { sub => '' }, 'x' ) {
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**
Run: `prove -lr t/45-upstream-keycloak.t`
Expected: FAIL mit `Can't locate Airlock/Upstream/Keycloak.pm in @INC`.
- [ ] **Step 3: `lib/Airlock/Upstream/Keycloak.pm` schreiben**
`lib/Airlock/Upstream/Keycloak.pm`:
```perl
package Airlock::Upstream::Keycloak;
# ABSTRACT: Use a Keycloak login as the subject of an Airlock approval
use Moo;
use Airlock::Factor::Upstream;
use Carp qw( croak );
use Types::Standard qw( ArrayRef Str );
use namespace::autoclean;
our $VERSION = '0.001';
=synopsis
my $keycloak = Airlock::Upstream::Keycloak->new;
my $airlock = Airlock->new(
policy => { always => ['upstream'] },
factors => [ $keycloak->factor( max_age => 300 ) ],
...
);
# in the approval action, with the claims of the person's ID token
my $result = $airlock->approve( $code, subject => $keycloak->subject($claims) );
=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.
=cut
has mfa_amr => (
is => 'ro',
isa => ArrayRef[Str],
default => sub { [qw( mfa otp hwk )] }
);
=attr mfa_amr
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
}
=method subject
my $subject = $keycloak->subject($claims);
The Airlock subject for a set of token claims: C<id> from C<sub>, and C<amr>,
C<acr> and C<auth_time> as Keycloak sent them. Croaks without C<sub>.
=cut
sub factor {
my ( $self, %arg ) = @_;
return $self->factor_class->new( accept_amr => $self->mfa_amr, accept_acr => $self->mfa_acr, %arg );
}
=method factor
my $factor = $keycloak->factor( max_age => 300 );
An L<Airlock::Factor::Upstream> that holds for a Keycloak login with a second
factor. Takes its options.
=cut
1;
```
- [ ] **Step 4: Unit-Test laufen lassen, Modul in den Load-Test**
Run: `prove -lr t/45-upstream-keycloak.t` â Expected: PASS (2 Subtests). Dann ` Airlock::Upstream::Keycloak` in die Liste in `t/00-load.t` und `prove -lr t` â Expected: PASS.
- [ ] **Step 5: Realm, Anleitung und Live-Test schreiben**
`t/keycloak/realm.json`:
```json
{
"realm": "airlock-test",
"enabled": true,
"clients": [
{
"clientId": "airlock-test-cli",
"publicClient": true,
"standardFlowEnabled": false,
"directAccessGrantsEnabled": true,
"attributes": {
"oauth2.device.authorization.grant.enabled": "true"
}
}
],
"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
```
Keycloak needs about 1 GB of memory. Do not start it on a machine that is
already short of it.
## Run
```bash
TEST_AIRLOCK_KEYCLOAK_URL=http://localhost:8080 prove -lv t/90-live-keycloak.t
```
## Findings
Recorded by whoever ran the test last. The `diag` lines of the test print
what to copy here.
| Keycloak version | Login | acr | amr | auth_time |
|---|---|---|---|---|
````
`t/90-live-keycloak.t`:
```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
# Live test against a real Keycloak. Off unless TEST_AIRLOCK_KEYCLOAK_URL is
# set to its base URL (for example http://localhost:8080) and the realm from
# t/keycloak/realm.json is imported. See t/keycloak/README.md.
BEGIN {
plan skip_all => 'set TEST_AIRLOCK_KEYCLOAK_URL to run the Keycloak live test'
unless $ENV{TEST_AIRLOCK_KEYCLOAK_URL};
}
use HTTP::Tiny;
use JSON::MaybeXS;
use MIME::Base64 qw( decode_base64url );
use Airlock::Client;
use Airlock::Factor::TOTP;
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 { }
);
subtest 'the client runs against Keycloak\'s device endpoint' => sub {
like( $client->device_endpoint, qr{\Ahttp}, 'discovery finds the device authorization endpoint' );
my $start = $client->start;
ok( length $start->{device_code}, 'device_code' );
ok( length $start->{user_code}, 'user_code' );
like( $start->{verification_uri}, qr{\Ahttp}, 'verification_uri' );
diag 'Keycloak device response keys: '.join( ', ', sort keys %$start );
# Nobody approves in this test. A poll that outlives a short deadline proves
# Keycloak answered authorization_pending (and slow_down, if it did) 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' );
};
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**
Nach `t/keycloak/README.md`, mit einer festen Versions-Markierung statt `latest`; die Version in die Findings-Tabelle eintragen.
Expected: Das Log meldet den Import des Realms `airlock-test` ohne Fehler, und `curl -s $URL/realms/airlock-test/.well-known/openid-configuration` liefert JSON mit `device_authorization_endpoint`.
Wenn der Import scheitert: `realm.json` gegen die Dokumentation genau dieser Keycloak-Version korrigieren (Abschnitt âImporting a realmâ und das Export-Format eines von Hand angelegten Realms sind die Referenz). Am sichersten: Client und Nutzer i...
- [ ] **Step 7: Live-Test laufen lassen und lesen**
Run: `TEST_AIRLOCK_KEYCLOAK_URL=http://localhost:8080 prove -lv t/90-live-keycloak.t`
Expected: Der erste Subtest ist PASS; das ist der Nachweis, dass `Airlock::Client` gegen Keycloaks Device-Endpunkt läuft. Im zweiten Subtest drucken die `diag`-Zeilen `acr`, `amr` und `auth_time` für beide Nutzer, je aus ID- und Access-Token.
- [ ] **Step 8: Die Abbildung an den Befund anpassen**
Die `diag`-Zeilen in die Findings-Tabelle in `t/keycloak/README.md` übertragen. Dann drei Fälle:
1. Der OTP-Login trägt ein `amr` aus `mfa`/`otp`/`hwk`, der Passwort-Login nicht: die Standardwerte stimmen, nichts ändern.
2. Der Unterschied liegt in `acr` (oder in anderen `amr`-Werten): die Standardwerte von `mfa_acr` beziehungsweise `mfa_amr` in `lib/Airlock/Upstream/Keycloak.pm` auf die beobachteten Werte setzen, in der POD der beiden Attribute Keycloak-Version und ...
3. Die Tokens beider Logins sind an `acr` und `amr` nicht zu unterscheiden: Keycloak liefert die Information in der Standardkonfiguration nicht. Dann nichts raten. Als Notiz auf die Karte, was beobachtet wurde; der Maintainer entscheidet, ob der Test...
- [ ] **Step 9: Alles laufen lassen**
Run: `prove -lr t && TEST_AIRLOCK_KEYCLOAK_URL=http://localhost:8080 prove -lv t/90-live-keycloak.t && dzil test`
Expected: alles PASS (in Fall 3 des vorigen Schritts mit den zwei bekannten roten Assertions im Live-Test, auf der Karte vermerkt).
- [ ] **Step 10: Ãbergabe**
Commit-fertig lassen, Karte nach `review`, mit Keycloak-Version und Befund in der Notiz. Betreff: `Add Keycloak subject mapping and live test`; `Changes`: `- Airlock::Upstream::Keycloak: Keycloak token claims as Airlock subject; live test behind TEST...
( run in 1.474 second using v1.01-cache-2.11-cpan-f5f21f1076c )