Airlock
view release on metacpan or search on metacpan
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
}
=method oauth
my ( $http_status, $json ) = @{ $result->oauth };
The result as RFC 8628 wants it on the wire: 200 with the payload, or 400 with
C<error>.
=cut
1;
```
- [ ] **Step 5: `lib/Airlock.pm` ersetzen**
Die Methode heiÃt `open`, wie in der Spec. Innerhalb des Pakets wird das eingebaute `open` nirgends aufgerufen; wer es je braucht, schreibt `CORE::open`.
`lib/Airlock.pm`:
```perl
package Airlock;
# ABSTRACT: Embeddable device authorization (RFC 8628) with step-up second factors
use Moo;
use Airlock::Code;
use Airlock::Policy;
use Airlock::Result;
use Airlock::Store::Memory;
use Carp qw( croak );
use Types::Standard qw( ArrayRef CodeRef ConsumerOf HashRef InstanceOf Int Str );
use namespace::autoclean;
our $VERSION = '0.001';
=synopsis
my $airlock = Airlock->new(
clients => { 'my-cli' => { name => 'My CLI', scopes => [qw( read admin )] } },
verification_uri => 'https://my.example.org/airlock',
store => { insert => sub {...}, find => sub {...}, update => sub {...}, purge => sub {...} },
policy => { step_up => { admin => ['totp'] } },
factors => [ Airlock::Factor::Callback->new( name => 'totp', amr => 'otp', verify => sub {...} ) ],
);
# human side: the host application renders its own page
my $view = $airlock->inspect( $typed_code, subject => $subject ) or return not_found();
my $needs = $airlock->requirements( $view, $subject ); # ['totp']
my $done = $airlock->approve( $typed_code, subject => $subject, proofs => { totp => $typed_totp } );
=description
Airlock approves a waiting request from an already trusted session: the server
side of the OAuth 2.0 Device Authorization Grant (RFC 8628), with an optional
second factor before the approval counts.
It is a core to embed. The host application supplies who is logged in, the
approval page and where rows are kept. Airlock supplies codes, the state
machine, poll rules, one-time redemption, step-up policy, second factors and
the two machine endpoints.
A request moves C<pending> to C<approved>, C<denied> or C<expired>, and
C<approved> to C<redeemed> exactly once.
=cut
has clients => (
is => 'ro',
isa => HashRef | CodeRef,
required => 1
);
=attr clients
Required. Who may ask. A hash of client id to C<< { name => ..., scopes => [...] } >>,
or a coderef called with a client id that returns such a hash or nothing. A
client without C<scopes> may ask for any scope.
=cut
has verification_uri => (
is => 'ro',
isa => Str,
required => 1
);
=attr verification_uri
Required. Where the host application serves its approval page.
=cut
has store => (
is => 'lazy',
isa => HashRef[CodeRef]
);
sub _build_store { Airlock::Store::Memory->new->as_subs }
=attr store
Hash of four coderefs: C<insert>, C<find>, C<update> and optionally C<purge>.
The contract is documented in L<Airlock::Store::Memory> and checked by
L<Airlock::Test::Store>. Default: an in-process store.
=cut
has policy => (
is => 'lazy',
isa => InstanceOf['Airlock::Policy'],
coerce => sub { ref $_[0] eq 'HASH' ? Airlock::Policy->new( $_[0] ) : $_[0] }
);
sub _build_policy { Airlock::Policy->new }
=attr policy
An L<Airlock::Policy> or the hash to build one from. Default: no factors.
=cut
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
$self->_emit( 'factor_failed', client_id => $row->{client_id}, subject => $subject->{id}, factor => $factor->name );
return $self->_fail( $final ? 'too_many_failures' : 'factor_failed', missing => [ $factor->name ] );
}
sub _issue_opaque {
my ( $self, $grant, $now ) = @_;
my $token = $self->code->secret;
$self->store->{insert}->( {
hash => $self->code->hash($token),
kind => 'token',
user_code => undef,
client_id => $grant->{client_id},
scope => $grant->{scope},
state => 'active',
created => $now,
expires => $now + $self->token_ttl,
poll_interval => undef,
last_poll => undef,
subject => $grant->{subject},
amr => join( ' ', @{ $grant->{amr} } ),
acr => $grant->{acr},
auth_time => $grant->{auth_time},
approved => undef,
origin_ip => undef,
origin_ua => undef,
factor_failures => 0
} );
return {
access_token => $token,
token_type => 'Bearer',
expires_in => $self->token_ttl,
scope => $grant->{scope}
};
}
1;
```
- [ ] **Step 6: Tests laufen lassen**
Run: `prove -lr t/50-core.t t/51-core-factors.t t/52-core-token.t`
Expected: PASS (19, 8 und 5 Subtests), ohne Warnungen auf STDERR.
- [ ] **Step 7: Modul in den Load-Test**
` Airlock::Result` in die Liste in `t/00-load.t` (`Airlock` steht schon drin). Run: `prove -lr t` â Expected: PASS.
- [ ] **Step 8: Ãbergabe**
Commit-fertig lassen, Karte nach `review`. Betreff: `Implement the Airlock core`; `Changes`: `- Airlock: open, inspect, requirements, approve, deny, redeem; opaque tokens with verify_token and revoke_token; events`.
---
### Task 6: Maschinen-Endpunkte: `respond`, `to_app`, `Airlock::HTTPMessage`
Spec: Abschnitte 3 und 5. Abweichung von Revision 2 der Spec, in Revision 3 nachgezogen: `handle` ist keine Methode von `Airlock`, sondern lebt in `Airlock::HTTPMessage`, weil die Hausregel verzögertes `require` verbietet und `Airlock` selbst nicht ...
**Files:**
- Create: `lib/Airlock/Role/Endpoints.pm`, `lib/Airlock/HTTPMessage.pm`
- Modify: `lib/Airlock.pm` (Rolle einbinden, Synopsis ergänzen)
- Test: `t/60-endpoints.t`, `t/61-httpmessage.t`
- Modify: `t/00-load.t`
**Interfaces:**
- Consumes: `Airlock->open`, `Airlock->redeem`, `Airlock::Result->oauth` (Aufgabe 5); Fixture `AirlockTest` (Aufgabe 5).
- Produces: auf `Airlock`: `->respond( $method, $path, \%params, \%origin )` â `[ $status, \%headers, \%json ]`; `->parse_form($body)` â HashRef oder leere Liste (im Listenkontext immer mit `scalar` aufrufen); `->encode_body(\%json)` â JSON-Byt...
- [ ] **Step 1: Die Tests schreiben**
`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' );
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
done_testing;
```
`t/61-httpmessage.t`:
```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use lib 't/lib';
use HTTP::Request;
use JSON::MaybeXS;
use Airlock::HTTPMessage;
use AirlockTest;
my $t = AirlockTest->new;
my $http = Airlock::HTTPMessage->new( airlock => $t->airlock );
sub request {
my ( $method, $uri, $body, @header ) = @_;
return HTTP::Request->new( $method, $uri, [ 'Content-Type' => 'application/x-www-form-urlencoded', 'User-Agent' => 'lwp-test/1.0', @header ], $body );
}
subtest 'device' => sub {
my $response = $http->handle( request( POST => 'https://example.org/airlock/device', 'client_id=cli&scope=read' ), ip => '192.0.2.4' );
isa_ok( $response, 'HTTP::Response' );
is( $response->code, 200, 'status' );
is( $response->message, 'OK', 'status message' );
is( $response->header('Content-Type'), 'application/json', 'content type' );
is( $response->header('Cache-Control'), 'no-store', 'no-store' );
my $json = decode_json( $response->content );
my $row = $t->row( $json->{device_code} );
is( $row->{origin_ip}, '192.0.2.4', 'origin ip from the caller' );
is( $row->{origin_ua}, 'lwp-test/1.0', 'origin ua from the request' );
my $poll = $http->handle( request( POST => '/airlock/token', 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&client_id=cli&device_code='.$json->{device_code} ) );
is( $poll->code, 400, 'token: status' );
is( $poll->message, 'Bad Request', 'token: status message' );
is_deeply( decode_json( $poll->content ), { error => 'authorization_pending' }, 'token: body' );
};
subtest 'refusals' => sub {
is( $http->handle( request( GET => '/airlock/device' ) )->code, 405, 'GET' );
is( $http->handle( request( GET => '/airlock/device' ) )->header('Allow'), 'POST', 'Allow header' );
is( $http->handle( request( POST => '/airlock/nope', 'client_id=cli' ) )->code, 404, 'unknown route' );
is( $http->handle( HTTP::Request->new( POST => '/airlock/device', [ 'Content-Type' => 'application/json' ], '{"client_id":"cli"}' ) )->code, 400, 'a JSON body is not read' );
is( $http->handle( HTTP::Request->new( POST => '/airlock/device' ) )->code, 400, 'no body, no headers' );
is( $http->handle( request( POST => '/airlock/device', 'client_id=cli&pad='.( 'x' x 20000 ) ) )->code, 413, 'a body over the limit' );
};
ok( !eval { Airlock::HTTPMessage->new; 1 }, 'airlock is required' );
done_testing;
```
- [ ] **Step 2: Tests laufen lassen, sie müssen scheitern**
Run: `prove -lr t/60-endpoints.t t/61-httpmessage.t`
Expected: FAIL mit `Can't locate object method "respond" via package "Airlock"` und `Can't locate Airlock/HTTPMessage.pm in @INC`.
- [ ] **Step 3: `lib/Airlock/Role/Endpoints.pm` schreiben**
`lib/Airlock/Role/Endpoints.pm`:
```perl
package Airlock::Role::Endpoints;
# ABSTRACT: The two machine endpoints of Airlock, framework-neutral and as PSGI
use JSON::MaybeXS;
use Moo::Role;
our $VERSION = '0.001';
=synopsis
# PSGI
builder { mount '/airlock' => $airlock->to_app; mount '/' => $app };
# anything else
my ( $status, $headers, $json ) = @{ $airlock->respond( 'POST', '/device', \%params, { ip => $ip, ua => $ua } ) };
=description
The device authorization endpoint and the token endpoint of RFC 8628, answered
in one place: L</respond>. L</to_app> is a thin PSGI skin over it that needs
neither Plack nor any other framework. L<Airlock::HTTPMessage> is the same for
L<HTTP::Request> and L<HTTP::Response>.
Routes are matched on the last path segment, so the endpoints can be mounted
anywhere: C<POST .../device> and C<POST .../token>.
=cut
requires qw( open redeem );
sub device_grant_type { 'urn:ietf:params:oauth:grant-type:device_code' }
sub max_body { 16384 }
=method max_body
Largest request body, in bytes, the endpoints read. 16384.
=cut
has _json => (
is => 'lazy',
init_arg => undef
);
sub _build__json { JSON::MaybeXS->new( utf8 => 1, canonical => 1, convert_blessed => 1 ) }
sub respond {
my ( $self, $method, $path, $param, $origin ) = @_;
my ( $route ) = ( $path // '' ) =~ m{([^/]*)/?\z};
return $self->_reply( 404, { error => 'not_found' } )
unless $route eq 'device' || $route eq 'token';
return $self->_reply( 405, { error => 'invalid_request' }, Allow => 'POST' )
unless uc( $method // '' ) eq 'POST';
return $self->_reply( 400, { error => 'invalid_request' } ) unless ref $param eq 'HASH';
return $self->_reply( 400, { error => 'unsupported_grant_type' } )
if $route eq 'token' && ( $param->{grant_type} // '' ) ne $self->device_grant_type;
my $result = $route eq 'device'
? $self->open( client_id => $param->{client_id}, scope => $param->{scope}, origin => $origin )
: $self->redeem( device_code => $param->{device_code}, client_id => $param->{client_id} );
return $self->_reply( @{ $result->oauth } );
}
=method respond
my ( $status, $headers, $json ) = @{ $airlock->respond( $method, $path, \%params, \%origin ) };
Answers one request. C<%params> are the decoded form parameters, or anything
that is not a hash when the body could not be parsed. Returns the HTTP status,
a hash of headers and the response body as a data structure.
=cut
sub encode_body {
my ( $self, $json ) = @_;
return $self->_json->encode($json);
}
=method encode_body
my $bytes = $airlock->encode_body($json);
The response body as JSON bytes.
=cut
sub parse_form {
my ( $self, $body ) = @_;
my %param;
for my $pair ( split /&/, $body // '' ) {
next unless length $pair;
my ( $key, $value ) = map { $self->_unescape($_) } split /=/, $pair, 2;
return if exists $param{$key};
$param{$key} = $value // '';
}
return \%param;
}
=method parse_form
my $params = $airlock->parse_form($body);
Decodes an C<application/x-www-form-urlencoded> body. Returns nothing when a
parameter appears twice, which RFC 6749 forbids.
=cut
sub to_app {
my ( $self ) = @_;
return sub {
my ( $env ) = @_;
my $length = $env->{CONTENT_LENGTH} || 0;
return $self->_psgi( $self->_reply( 413, { error => 'invalid_request' } ) ) if $length > $self->max_body;
my $body = '';
if ( $length && ( $env->{CONTENT_TYPE} // '' ) =~ m{\Aapplication/x-www-form-urlencoded\b}i ) {
while ( length $body < $length ) {
my $read = $env->{'psgi.input'}->read( my $chunk, $length - length $body );
last unless $read;
$body .= $chunk;
}
}
return $self->_psgi( $self->respond(
$env->{REQUEST_METHOD}, $env->{PATH_INFO}, scalar $self->parse_form($body),
{ ip => $env->{REMOTE_ADDR}, ua => $env->{HTTP_USER_AGENT} }
) );
};
}
=method to_app
my $app = $airlock->to_app;
The two endpoints as a PSGI application.
=cut
sub _reply {
my ( $self, $status, $json, %header ) = @_;
return [
$status,
{ 'Content-Type' => 'application/json', 'Cache-Control' => 'no-store', 'Pragma' => 'no-cache', %header },
$json
];
}
sub _psgi {
my ( $self, $reply ) = @_;
my ( $status, $headers, $json ) = @$reply;
return [ $status, [ map { $_ => $headers->{$_} } sort keys %$headers ], [ $self->encode_body($json) ] ];
}
sub _unescape {
my ( $self, $text ) = @_;
return unless defined $text;
$text =~ tr/+/ /;
$text =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ge;
return $text;
}
1;
```
- [ ] **Step 4: Die Rolle in `lib/Airlock.pm` einbinden**
Direkt unter `use Moo;` einfügen:
```perl
with 'Airlock::Role::Endpoints';
```
Und in der Synopsis nach dem schlieÃenden `);` des Konstruktors einfügen:
```perl
# machine side: mount the two JSON endpoints
my $app = $airlock->to_app;
```
- [ ] **Step 5: `lib/Airlock/HTTPMessage.pm` schreiben**
`lib/Airlock/HTTPMessage.pm`:
```perl
package Airlock::HTTPMessage;
# ABSTRACT: Airlock's machine endpoints for HTTP::Request and HTTP::Response
use Moo;
use HTTP::Response;
use HTTP::Status qw( status_message );
use Types::Standard qw( InstanceOf );
use namespace::autoclean;
our $VERSION = '0.001';
=synopsis
my $http = Airlock::HTTPMessage->new( airlock => $airlock );
my $response = $http->handle( $request, ip => $remote_address );
=description
For a host application that is neither PSGI nor anything Airlock knows about,
but can produce an L<HTTP::Request> and send an L<HTTP::Response>. This is a
separate class so that L<Airlock> itself does not depend on L<HTTP::Message>.
=cut
has airlock => (
is => 'ro',
isa => InstanceOf['Airlock'],
required => 1
);
=attr airlock
Required. The L<Airlock> to answer for.
=cut
sub handle {
my ( $self, $request, %origin ) = @_;
my $airlock = $self->airlock;
my $content = $request->content // '';
my $form = ( $request->header('Content-Type') // '' ) =~ m{\Aapplication/x-www-form-urlencoded\b}i;
my ( $status, $headers, $json ) = @{
length $content > $airlock->max_body
? [ 413, { 'Content-Type' => 'application/json' }, { error => 'invalid_request' } ]
: $airlock->respond(
$request->method, $request->uri->path, scalar $airlock->parse_form( $form ? $content : '' ),
{ ua => scalar $request->header('User-Agent'), %origin }
)
};
return HTTP::Response->new(
$status, status_message($status), [ map { $_ => $headers->{$_} } sort keys %$headers ],
$airlock->encode_body($json)
);
}
=method handle
my $response = $http->handle( $request, ip => $remote_address );
Answers an L<HTTP::Request> for C<POST .../device> or C<POST .../token> with an
L<HTTP::Response>. Pass the remote address, which a request object does not
carry.
=cut
1;
```
- [ ] **Step 6: Tests laufen lassen**
Run: `prove -lr t/60-endpoints.t t/61-httpmessage.t`
Expected: PASS (4 Subtests und 3 Tests), ohne Warnungen auf STDERR. Eine Warnung `Odd number of elements` heiÃt, dass `parse_form` irgendwo ohne `scalar` in einer Argumentliste steht.
- [ ] **Step 7: Module in den Load-Test**
` Airlock::HTTPMessage` und ` Airlock::Role::Endpoints` in die Liste in `t/00-load.t`. Run: `prove -lr t` â Expected: PASS.
- [ ] **Step 8: Ãbergabe**
Commit-fertig lassen, Karte nach `review`. Betreff: `Add machine endpoints: respond, to_app, Airlock::HTTPMessage`; `Changes`: `- Device and token endpoint as PSGI (to_app), for HTTP::Request (Airlock::HTTPMessage) and framework-neutral (respond)`.
---
### Task 7: `Airlock::Client`
Spec: Abschnitt 6 (Client).
**Files:**
- Create: `lib/Airlock/Client.pm`
- Test: `t/70-client.t`
- Modify: `t/00-load.t`
**Interfaces:**
- Consumes: `Airlock::QR->new( text =>, quiet => )->terminal(%opt)` (Aufgabe 1); `Airlock->to_app` (Aufgabe 6) und `AirlockTest` (Aufgabe 5) nur im Test.
- Produces: `Airlock::Client->new( client_id =>, scope =>, issuer => | device_endpoint => + token_endpoint =>, ua => $http_tiny, on_prompt => sub ($start), sleep => sub ($seconds), now => sub )`; `->start` â HashRef der Device-Antwort; `->poll($sta...
- [ ] **Step 1: Den Test schreiben**
Der Test ersetzt `HTTP::Tiny` durch eine Unterklasse, die eine PSGI-App im selben Prozess aufruft; so teilen Test und Server Uhr und Speicher. Ein Subtest geht zusätzlich über einen echten Socket. Dort baut der Server-Prozess sein eigenes `Airlock`...
`t/70-client.t`:
```perl
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Test::More;
use lib 't/lib';
use HTTP::Server::PSGI;
use Test::TCP;
use JSON::MaybeXS;
use Airlock::Client;
use AirlockTest;
# A stand-in for HTTP::Tiny that talks to a PSGI app in-process: no socket, no
# second process, so the test and the server share one clock and one store.
{
package LocalUA;
use Moo;
extends 'HTTP::Tiny';
has app => ( is => 'ro', required => 1 );
has seen => ( is => 'ro', default => sub { [] } );
sub request {
my ( $self, $method, $url, $args ) = @_;
my $body = $args->{content} // '';
my ( $path ) = $url =~ m{\Ahttps?://[^/]+(/[^?]*)};
push @{ $self->seen }, { method => $method, url => $url, body => $body, headers => $args->{headers} };
CORE::open( my $input, '<', \$body ) or die $!;
my $psgi = $self->app->( {
REQUEST_METHOD => $method,
PATH_INFO => $path,
CONTENT_TYPE => $args->{headers}{'content-type'},
CONTENT_LENGTH => length $body,
REMOTE_ADDR => '127.0.0.1',
HTTP_USER_AGENT => 'local-ua',
'psgi.input' => $input
} );
return {
success => $psgi->[0] < 400 ? 1 : '',
status => $psgi->[0],
reason => 'local',
content => join( '', @{ $psgi->[2] } ),
headers => { @{ $psgi->[1] } }
};
}
}
sub fixture {
my ( %arg ) = @_;
my $t = AirlockTest->new;
my $app = delete $arg{app} || $t->airlock->to_app;
my @slept;
my $after_sleep = delete $arg{after_sleep} || sub { };
my $ua = LocalUA->new( app => $app );
my $client = Airlock::Client->new(
client_id => 'cli',
scope => 'read write',
device_endpoint => 'http://airlock.test/airlock/device',
token_endpoint => 'http://airlock.test/airlock/token',
ua => $ua,
now => sub { $t->clock },
sleep => sub { push @slept, $_[0]; $t->advance( $_[0] ); $after_sleep->( $t, scalar @slept ) },
on_prompt => sub { },
%arg
);
return ( $t, $client, \@slept, $ua );
}
subtest 'start' => sub {
my ( $t, $client, undef, $ua ) = fixture();
my $start = $client->start;
like( $start->{device_code}, qr/\A[0-9a-f]{64}\z/, 'device_code' );
like( $start->{user_code}, qr/\A\w{4}-\w{4}\z/, 'user_code' );
is( $t->row( $start->{device_code} )->{scope}, 'read write', 'the scope arrived' );
is( $ua->seen->[0]{headers}{accept}, 'application/json', 'asks for JSON' );
like( $ua->seen->[0]{headers}{'content-type'}, qr{\Aapplication/x-www-form-urlencoded}, 'sends a form' );
my ( undef, $unknown ) = fixture( client_id => 'nope' );
ok( !eval { $unknown->start; 1 }, 'an unknown client croaks' );
like( $@, qr/start failed: invalid_client/, 'with the server error' );
};
subtest 'login: approved while polling' => sub {
my ( $t, $client, $slept ) = fixture(
after_sleep => sub {
my ( $t, $polls ) = @_;
return unless $polls == 2;
my ( $row ) = grep { ( $_->{state} // '' ) eq 'pending' } values %{ $t->memory->_rows };
$t->airlock->approve( $row->{user_code}, subject => { id => 'alice' } );
}
);
my $token = $client->login;
is( $token->{token_type}, 'Bearer', 'token response' );
is( $t->airlock->verify_token( $token->{access_token} )->{subject}, 'alice', 'the token belongs to who approved' );
is_deeply( $slept, [ 5, 5 ], 'waited the server interval before every poll, never polled without waiting' );
};
subtest 'poll: slow_down adds five seconds' => sub {
my $calls = 0;
my @reply = ( 'slow_down', 'authorization_pending', 'slow_down' );
my $app = sub {
my $error = $reply[ $calls++ ];
return [ 400, [ 'Content-Type' => 'application/json' ], [ encode_json( { error => $error } ) ] ] if $error;
return [ 200, [ 'Content-Type' => 'application/json' ], [ encode_json( { access_token => 'tok', token_type => 'Bearer' } ) ] ];
};
my ( undef, $client, $slept ) = fixture( app => $app );
my $token = $client->poll( { device_code => 'd', interval => 2, expires_in => 600 } );
is( $token->{access_token}, 'tok', 'token' );
is_deeply( $slept, [ 2, 7, 7, 12 ], 'the interval grows by five on each slow_down and stays grown' );
};
subtest 'poll: errors' => sub {
for my $error (qw( access_denied expired_token invalid_grant )) {
my $app = sub { [ 400, [], [ encode_json( { error => $error } ) ] ] };
my ( undef, $client ) = fixture( app => $app );
ok( !eval { $client->poll( { device_code => 'd', interval => 1, expires_in => 60 } ); 1 }, $error.' croaks' );
like( $@, qr/poll failed: $error/, 'with the error' );
}
my ( undef, $described ) = fixture( app => sub { [ 400, [], [ encode_json( { error => 'access_denied', error_description => 'no thanks' } ) ] ] } );
eval { $described->poll( { device_code => 'd', interval => 1, expires_in => 60 } ) };
like( $@, qr/access_denied \(no thanks\)/, 'error_description is included' );
my ( undef, $html ) = fixture( app => sub { [ 502, [], ['<html>Bad Gateway</html>'] ] } );
ok( !eval { $html->poll( { device_code => 'd', interval => 1, expires_in => 60 } ); 1 }, 'a non-JSON error croaks' );
like( $@, qr/poll failed: 502/, 'with the status' );
my ( undef, $odd ) = fixture( app => sub { [ 200, [], ['[1,2,3]'] ] } );
ok( !eval { $odd->poll( { device_code => 'd', interval => 1, expires_in => 60 } ); 1 }, 'JSON that is not an object croaks' );
};
subtest 'poll: errors reported with status 200' => sub {
my @reply = ( { error => 'authorization_pending' }, { access_token => 'tok' } );
my ( undef, $client, $slept ) = fixture( app => sub { [ 200, [], [ encode_json( shift @reply ) ] ] } );
is( $client->poll( { device_code => 'd', interval => 3, expires_in => 60 } )->{access_token}, 'tok', 'pending with 200 keeps polling' );
is( scalar @$slept, 2, 'two polls' );
};
subtest 'poll: gives up when the code has expired' => sub {
my ( undef, $client, $slept ) = fixture( app => sub { [ 400, [], [ encode_json( { error => 'authorization_pending' } ) ] ] } );
ok( !eval { $client->poll( { device_code => 'd', interval => 5, expires_in => 12 } ); 1 }, 'croaks' );
like( $@, qr/the code expired before anyone approved it/, 'and says why' );
is( scalar @$slept, 3, 'after the polls that fit into the lifetime' );
};
subtest 'poll: defaults for a sparse response' => sub {
my ( undef, $client, $slept ) = fixture( app => sub { [ 200, [], [ encode_json( { access_token => 'tok' } ) ] ] } );
$client->poll( { device_code => 'd' } );
is_deeply( $slept, [5], 'interval defaults to five seconds' );
};
subtest 'discovery' => sub {
my $config = { device_authorization_endpoint => 'http://id.test/device', token_endpoint => 'http://id.test/token' };
my $app = sub { [ 200, [], [ encode_json($config) ] ] };
my $ua = LocalUA->new( app => $app );
my $client = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test/realms/main/', ua => $ua );
is( $client->device_endpoint, 'http://id.test/device', 'device endpoint' );
is( $client->token_endpoint, 'http://id.test/token', 'token endpoint' );
is( scalar @{ $ua->seen }, 1, 'one discovery request for both' );
is( $ua->seen->[0]{url}, 'http://id.test/realms/main/.well-known/openid-configuration', 'at the well-known URL, without a double slash' );
my $partial = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test', ua => LocalUA->new( app => sub { [ 200, [], ['{"token_endpoint":"http://id.test/token"}'] ] } ) );
ok( !eval { $partial->device_endpoint; 1 }, 'a server without device endpoint croaks' );
like( $@, qr/discovery has no device_authorization_endpoint/, 'and says what is missing' );
my $down = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test', ua => LocalUA->new( app => sub { [ 503, [], ['down'] ] } ) );
ok( !eval { $down->token_endpoint; 1 }, 'a failed discovery croaks' );
like( $@, qr/discovery failed: 503/, 'with the status' );
ok( !eval { Airlock::Client->new( client_id => 'cli' )->device_endpoint; 1 }, 'neither issuer nor endpoints croaks' );
like( $@, qr/needs issuer, or device_endpoint and token_endpoint/, 'and says what to give' );
};
subtest 'prompt_text' => sub {
my ( undef, $client ) = fixture();
my $start = { verification_uri => 'https://example.org/airlock', user_code => 'BCDF-GHJK', verification_uri_complete => 'https://example.org/airlock?user_code=BCDF-GHJK' };
my $text = $client->prompt_text( $start, ansi => 0 );
like( $text, qr{\AOpen https://example.org/airlock and enter the code BCDF-GHJK\nOr scan:\n}, 'where to go and the code' );
like( $text, qr/[\x{2580}\x{2584}\x{2588}]{10}/, 'followed by the QR code' );
is( $client->prompt_text( { verification_uri => 'https://x', user_code => 'ABCD' } ), "Open https://x and enter the code ABCD\n", 'no QR code without verification_uri_complete' );
};
subtest 'against a real socket' => sub {
# the server is a process of its own, so it builds its own Airlock: the
# in-process store refuses to be carried across a fork
my $server = Test::TCP->new(
code => sub {
my ( $port ) = @_;
HTTP::Server::PSGI->new( host => '127.0.0.1', port => $port )->run( AirlockTest->new->airlock->to_app );
}
);
my $base = 'http://127.0.0.1:'.$server->port.'/airlock';
my $client = Airlock::Client->new( client_id => 'cli', device_endpoint => $base.'/device', token_endpoint => $base.'/token', sleep => sub { }, on_prompt => sub { } );
my $start = $client->start;
like( $start->{user_code}, qr/\A\w{4}-\w{4}\z/, 'start over HTTP' );
is( $start->{verification_uri}, 'https://example.org/airlock', 'the response is what the server sent' );
ok( !eval { Airlock::Client->new( client_id => 'nope', device_endpoint => $base.'/device', token_endpoint => $base.'/token' )->start; 1 }, 'a refusal over HTTP croaks' );
like( $@, qr/invalid_client/, 'with the server error' );
};
subtest 'poll: nonsense from the server does not become a busy loop' => sub {
for my $bad ( 0, -5, 'soon', '1e9', 2.5, [], undef, '' ) {
my ( undef, $client, $slept ) = fixture( app => sub { [ 200, [], [ encode_json( { access_token => 'tok' } ) ] ] } );
$client->poll( { device_code => 'd', interval => $bad, expires_in => 60 } );
is_deeply( $slept, [5], 'interval '.( defined $bad ? ref $bad ? 'reference' : '"'.$bad.'"' : 'undef' ).' falls back to five seconds' );
}
for my $bad ( 0, -1, 'never', undef ) {
my $polls = 0;
my ( undef, $client, $slept ) = fixture( app => sub { $polls++; [ 400, [], [ encode_json( { error => 'authorization_pending' } ) ] ] } );
ok( !eval { $client->poll( { device_code => 'd', interval => 100, expires_in => $bad } ); 1 }, 'gives up' );
is( $polls, 6, 'expires_in '.( defined $bad ? '"'.$bad.'"' : 'undef' ).' falls back to ten minutes' );
}
};
done_testing;
```
- [ ] **Step 2: Test laufen lassen, er muss scheitern**
Run: `prove -lr t/70-client.t`
Expected: FAIL mit `Can't locate Airlock/Client.pm in @INC`.
- [ ] **Step 3: `lib/Airlock/Client.pm` schreiben**
`lib/Airlock/Client.pm`:
```perl
package Airlock::Client;
# ABSTRACT: OAuth 2.0 device flow client (RFC 8628)
use Moo;
use Airlock::QR;
use Carp qw( croak );
use HTTP::Tiny;
use JSON::MaybeXS;
use Types::Standard qw( CodeRef InstanceOf Str );
use namespace::autoclean;
our $VERSION = '0.001';
=synopsis
my $client = Airlock::Client->new(
issuer => 'https://id.example.org/realms/main',
client_id => 'my-cli',
scope => 'openid profile',
);
my $token = $client->login; # prints code and QR to STDERR, then waits
print $token->{access_token};
=description
The other side of the device flow: what a command line tool runs to get a
token. It starts the flow, shows the person where to go, polls the token
endpoint at the pace the server sets, and returns the token response.
It speaks plain RFC 8628 and so works against L<Airlock>, Keycloak, and
anything else that implements the grant, including servers that report errors
with status 200.
=cut
has client_id => (
is => 'ro',
isa => Str,
required => 1
);
=attr client_id
Required. The client identifier registered with the server.
=cut
has scope => (
is => 'ro',
isa => Str,
default => ''
);
=attr scope
Scopes to ask for, separated by spaces. Default: none.
=cut
has issuer => (
is => 'ro',
isa => Str,
predicate => 'has_issuer'
);
=attr issuer
The issuer URL. When given, the endpoints are read from
C<< <issuer>/.well-known/openid-configuration >>.
=cut
has device_endpoint => (
is => 'lazy',
isa => Str
);
sub _build_device_endpoint { $_[0]->_discovered('device_authorization_endpoint') }
=attr device_endpoint
The device authorization endpoint. Discovered from C<issuer> unless given.
=cut
has token_endpoint => (
is => 'lazy',
isa => Str
);
sub _build_token_endpoint { $_[0]->_discovered('token_endpoint') }
=attr token_endpoint
The token endpoint. Discovered from C<issuer> unless given.
=cut
has ua => (
is => 'lazy',
isa => InstanceOf['HTTP::Tiny']
);
sub _build_ua { HTTP::Tiny->new( agent => 'Airlock-Client/'.$VERSION, timeout => 30 ) }
=attr ua
The L<HTTP::Tiny> to use. HTTPS needs L<IO::Socket::SSL>.
=cut
has on_prompt => (
is => 'lazy',
isa => CodeRef
);
sub _build_on_prompt {
my ( $self ) = @_;
return sub {
my ( $start ) = @_;
binmode STDERR, ':encoding(UTF-8)';
print STDERR $self->prompt_text($start);
};
}
=attr on_prompt
Coderef called with the device authorization response once the flow has
started. The default prints L</prompt_text> to STDERR.
=cut
has sleep => (
is => 'ro',
isa => CodeRef,
default => sub { sub { sleep $_[0] } }
);
=attr sleep
Coderef called with the seconds to wait between polls. For tests.
=cut
has now => (
is => 'ro',
isa => CodeRef,
default => sub { sub { time } }
);
=attr now
Coderef returning the current epoch. For tests.
=cut
has _discovery => (
is => 'lazy',
init_arg => undef
);
sub _build__discovery {
my ( $self ) = @_;
croak __PACKAGE__.'->new needs issuer, or device_endpoint and token_endpoint' unless $self->has_issuer;
my $url = $self->issuer =~ s{/+\z}{}r.'/.well-known/openid-configuration';
my $response = $self->ua->get( $url, { headers => { Accept => 'application/json' } } );
croak __PACKAGE__.' discovery failed: '.$response->{status}.' '.$response->{reason}.' for '.$url
unless $response->{success};
my $data = $self->_decode($response);
croak __PACKAGE__.' discovery returned no JSON object for '.$url unless %$data;
return $data;
}
sub _discovered {
my ( $self, $key ) = @_;
return $self->_discovery->{$key} // croak __PACKAGE__.' discovery has no '.$key;
}
sub device_grant_type { 'urn:ietf:params:oauth:grant-type:device_code' }
sub start {
my ( $self ) = @_;
my $response = $self->_post( $self->device_endpoint, {
client_id => $self->client_id,
length $self->scope ? ( scope => $self->scope ) : ()
} );
my $data = $self->_decode($response);
croak __PACKAGE__.'->start failed: '.$self->_reason( $response, $data )
unless $response->{success} && defined $data->{device_code} && defined $data->{user_code};
return $data;
}
=method start
my $start = $client->start;
Begins the flow. Returns the device authorization response: C<device_code>,
C<user_code>, C<verification_uri>, optionally C<verification_uri_complete>,
C<expires_in> and C<interval>. Croaks when the server refuses.
=cut
sub poll {
my ( $self, $start ) = @_;
my $interval = $self->_seconds( $start->{interval}, 5 );
my $deadline = $self->now->() + $self->_seconds( $start->{expires_in}, 600 );
while ( $self->now->() < $deadline ) {
$self->sleep->($interval);
my $response = $self->_post( $self->token_endpoint, {
grant_type => $self->device_grant_type,
device_code => $start->{device_code},
client_id => $self->client_id
} );
my $data = $self->_decode($response);
return $data if $response->{success} && defined $data->{access_token};
my $error = $data->{error} // '';
next if $error eq 'authorization_pending';
if ( $error eq 'slow_down' ) {
$interval += 5;
next;
}
croak __PACKAGE__.'->poll failed: '.$self->_reason( $response, $data );
}
croak __PACKAGE__.'->poll gave up: the code expired before anyone approved it';
}
=method poll
my $token = $client->poll($start);
Waits for the approval. Sleeps the interval the server asked for, adds five
seconds on every C<slow_down>, and returns the token response. Croaks on
C<access_denied>, C<expired_token>, any other error, and when the code's
lifetime runs out.
=cut
sub login {
my ( $self ) = @_;
my $start = $self->start;
$self->on_prompt->($start);
return $self->poll($start);
}
=method login
my $token = $client->login;
L</start>, the prompt, then L</poll>.
=cut
sub prompt_text {
my ( $self, $start, %arg ) = @_;
my $text = 'Open '.$start->{verification_uri}.' and enter the code '.$start->{user_code}."\n";
return $text unless defined $start->{verification_uri_complete};
return $text.'Or scan:'."\n".Airlock::QR->new( text => $start->{verification_uri_complete}, quiet => 2 )->terminal(%arg);
}
=method prompt_text
print STDERR $client->prompt_text($start);
What to show the person: where to go, the code, and a QR code of
C<verification_uri_complete> when the server sent one. Takes the options of
L<Airlock::QR/terminal>.
=cut
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
use Airlock;
use Airlock::Test::Store;
use AirlockExample::Schema;
use AirlockExample::StoreDBIO;
sub schema {
my $schema = AirlockExample::Schema->connect( 'dbi:SQLite:dbname=:memory:', '', '', { RaiseError => 1, PrintError => 0 } );
my @ddl = grep { /\S/ } split /;/, path('examples/schema.sql')->slurp_utf8 =~ s/^--.*$//mgr;
$schema->storage->dbh_do( sub { $_[1]->do($_) for @ddl } );
return $schema;
}
subtest 'store contract' => sub {
Airlock::Test::Store->new( store => AirlockExample::StoreDBIO->new( schema => schema() )->as_subs )->run;
};
subtest 'a whole flow on the schema' => sub {
my $schema = schema();
my $clock = 1_000_000;
my $airlock = Airlock->new(
clients => { cli => {} },
verification_uri => 'https://example.org/airlock',
store => AirlockExample::StoreDBIO->new( schema => $schema )->as_subs,
now => sub { $clock }
);
my $start = $airlock->open( client_id => 'cli', scope => 'read' )->data;
ok( $airlock->approve( $start->{user_code}, subject => { id => 'alice' } )->ok, 'approved' );
my $token = $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->data->{access_token};
is( $airlock->verify_token($token)->{subject}, 'alice', 'the token verifies from the schema' );
is( $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->status, 'invalid_grant', 'redeemed once' );
is( $schema->resultset('Airlock')->search( { hash => [ $start->{device_code}, $token ] } )->count, 0, 'no secret in the table' );
};
done_testing;
```
`t/82-example-psgi.t`:
```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use lib 'examples/lib';
BEGIN {
plan skip_all => 'Plack is needed for this example'
unless eval { require Plack::Test; require Plack::Util; require HTTP::Request::Common; 1 };
}
use JSON::MaybeXS;
use HTTP::Request::Common qw( GET POST );
my $app = Plack::Util::load_psgi('examples/app.psgi');
my $test = Plack::Test->create($app);
my $grant = 'urn:ietf:params:oauth:grant-type:device_code';
sub start {
my ( $scope ) = @_;
my $response = $test->request( POST '/airlock/device', [ client_id => 'demo-cli', scope => $scope ] );
is( $response->code, 200, 'device endpoint' );
return decode_json( $response->content );
}
sub poll {
my ( $start ) = @_;
my $response = $test->request( POST '/airlock/token', [ grant_type => $grant, client_id => 'demo-cli', device_code => $start->{device_code} ] );
return decode_json( $response->content );
}
subtest 'plain scope: look, approve, token' => sub {
my $start = start('read');
is( poll($start)->{error}, 'authorization_pending', 'pending' );
my $form = $test->request( GET '/approve' );
like( $form->content, qr/name="user_code"/, 'without a code the page asks for one' );
my $look = $test->request( GET '/approve?user_code='.$start->{user_code} );
is( $look->code, 200, 'approval page' );
like( $look->content, qr/<b>Demo CLI<\/b> wants access: read/, 'shows client and scopes' );
unlike( $look->content, qr/name="pin"/, 'no PIN for a plain scope' );
is( poll($start)->{error}, 'slow_down', 'looking approved nothing (and the second poll came too fast)' );
my $done = $test->request( POST '/approve', [ user_code => $start->{user_code}, action => 'approve' ] );
like( $done->content, qr/Approved/, 'approved' );
is( $test->request( GET '/approve?user_code='.$start->{user_code} )->code, 404, 'the code is used up' );
};
subtest 'step-up scope: PIN' => sub {
my $start = start('read admin');
like( $test->request( GET '/approve?user_code='.$start->{user_code} )->content, qr/name="pin"/, 'the page asks for the PIN' );
my $wrong = $test->request( POST '/approve', [ user_code => $start->{user_code}, action => 'approve', pin => '0000' ] );
is( $wrong->code, 403, 'wrong PIN' );
like( $wrong->content, qr/Wrong PIN/, 'says so' );
my $right = $test->request( POST '/approve', [ user_code => $start->{user_code}, action => 'approve', pin => '4711' ] );
like( $right->content, qr/Approved/, 'right PIN' );
};
subtest 'deny' => sub {
my $start = start('read');
like( $test->request( POST '/approve', [ user_code => $start->{user_code}, action => 'deny' ] )->content, qr/Denied/, 'denied' );
is( poll($start)->{error}, 'access_denied', 'the device learns it' );
};
subtest 'unknown code and escaping' => sub {
my $response = $test->request( GET '/approve?user_code=%3Cscript%3E' );
is( $response->code, 404, 'unknown code' );
unlike( $response->content, qr/<script>/, 'nothing typed is echoed' );
};
subtest 'qr' => sub {
my $start = start('read');
my $qr = $test->request( GET '/qr.svg?user_code='.$start->{user_code} );
is( $qr->code, 200, 'QR code' );
is( $qr->header('Content-Type'), 'image/svg+xml', 'as SVG' );
like( $qr->content, qr/\A<svg /, 'SVG body' );
is( $test->request( GET '/qr.svg?user_code=ZZZZ-ZZZZ' )->code, 404, 'no QR code for an unknown code' );
};
done_testing;
```
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
my $code = $param{user_code} // '';
return ( 200, $self->_form('') ) unless length $code;
if ( ( $param{action} // '' ) eq 'deny' ) {
my $denied = $airlock->deny( $code, subject => $subject );
return $denied->ok ? ( 200, '<p>Denied. You can close this window.</p>' ) : ( 404, $self->_form('That code is unknown or has expired.') );
}
my $view = $airlock->inspect( $code, subject => $subject )
or return ( 404, $self->_form('That code is unknown or has expired.') );
my $needs = $airlock->requirements( $view, $subject );
return ( 200, $self->_confirm( $view, $needs, '' ) ) unless ( $param{action} // '' ) eq 'approve';
my $result = $airlock->approve( $code, subject => $subject, proofs => { pin => $param{pin} } );
return ( 200, '<p>Approved. You can close this window.</p>' ) if $result->ok;
return ( 403, '<p>Too many wrong attempts. Start again on the device.</p>' ) if $result->status eq 'too_many_failures';
return ( 404, $self->_form('That code is unknown or has expired.') ) if $result->status eq 'unknown_code';
return ( $result->status eq 'factor_required' ? 200 : 403,
$self->_confirm( $view, $needs, $result->status eq 'factor_failed' ? 'Wrong PIN.' : '' ) );
}
sub _form {
my ( $self, $message ) = @_;
return '<p>'.$self->escape($message).'</p>'
.'<form method="get" action="/approve"><label>Code <input name="user_code" autofocus></label>'
.'<button>Continue</button></form>';
}
sub _confirm {
my ( $self, $view, $needs, $message ) = @_;
my $pin = grep( { $_ eq 'pin' } @$needs ) ? '<label>PIN <input name="pin" inputmode="numeric" autocomplete="off"></label>' : '';
# YOUR CSRF TOKEN GOES INTO THIS FORM. Approving is a state change made with
# the person's session; check the token before calling approve or deny.
return '<p>'.$self->escape($message).'</p>'
.'<p><b>'.$self->escape( $view->{client_name} ).'</b> wants access: '
.$self->escape( join ', ', @{ $view->{scopes} } ).'</p>'
.'<p>Asked '.$view->{age}.' seconds ago from '.$self->escape( $view->{origin}{ip} )
.' ('.$self->escape( $view->{origin}{ua} ).')</p>'
.'<form method="post" action="/approve">'
.'<input type="hidden" name="user_code" value="'.$self->escape( $view->{user_code} ).'">'
.$pin
.'<button name="action" value="approve">Approve</button>'
.'<button name="action" value="deny">Deny</button></form>';
}
1;
```
- [ ] **Step 8: Die Plack-App, die Mojolicious-App und das CLI schreiben**
`examples/app.psgi`:
```perl
#!/usr/bin/env perl
# Airlock in a Plack application.
#
# plackup -Ilib -Iexamples/lib examples/app.psgi
# perl -Ilib examples/login.pl # in a second terminal
#
# The machine endpoints are mounted with to_app. The approval page is this
# application's own: it reads the request, asks Airlock, renders HTML.
use strict;
use warnings;
use Airlock::QR;
use AirlockExample::Demo;
use Plack::Builder;
use Plack::Request;
my $demo = AirlockExample::Demo->new;
my $approve = sub {
my ( $env ) = @_;
my $request = Plack::Request->new($env);
my $param = $request->method eq 'POST' ? $request->body_parameters : $request->query_parameters;
my ( $status, $html ) = $demo->page( map { $_ => scalar $param->get($_) } qw( user_code action pin ) );
return [ $status, [ 'Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store' ], [$html] ];
};
# The QR code a device without a terminal would show: it leads the phone to
# the approval page with the code filled in.
my $qr = sub {
my ( $env ) = @_;
my $view = $demo->airlock->inspect( Plack::Request->new($env)->query_parameters->get('user_code') )
or return [ 404, [ 'Content-Type' => 'text/plain' ], ['unknown code'] ];
my $uri = $demo->airlock->verification_uri.'?user_code='.$view->{user_code};
return [ 200, [ 'Content-Type' => 'image/svg+xml', 'Cache-Control' => 'no-store' ], [ Airlock::QR->new( text => $uri )->svg ] ];
};
builder {
mount '/airlock' => $demo->airlock->to_app;
mount '/approve' => $approve;
mount '/qr.svg' => $qr;
};
```
`examples/mojo.pl`:
```perl
#!/usr/bin/env perl
# Airlock in a Mojolicious application.
#
# perl -Ilib -Iexamples/lib examples/mojo.pl daemon -l http://*:5000
# perl -Ilib examples/login.pl # in a second terminal
#
# There is no plugin: the two machine endpoints are one route that hands the
# request to respond, and the approval page is an ordinary action.
use Mojolicious::Lite;
use Airlock::QR;
use AirlockExample::Demo;
my $demo = AirlockExample::Demo->new;
post '/airlock/:route' => [ route => [qw( device token )] ] => sub {
my ( $c ) = @_;
my ( $status, $headers, $json ) = @{ $demo->airlock->respond(
'POST', $c->req->url->path->to_string, scalar $demo->airlock->parse_form( $c->req->body ),
{ ip => $c->tx->remote_address, ua => $c->req->headers->user_agent }
) };
$c->res->headers->header( $_ => $headers->{$_} ) for keys %$headers;
$c->render( json => $json, status => $status );
};
any [qw( GET POST )] => '/approve' => sub {
my ( $c ) = @_;
my ( $status, $html ) = $demo->page( map { $_ => scalar $c->param($_) } qw( user_code action pin ) );
$c->res->headers->cache_control('no-store');
$c->render( data => $html, format => 'html', status => $status );
};
get '/qr' => sub {
my ( $c ) = @_;
my $view = $demo->airlock->inspect( $c->param('user_code') ) or return $c->render( text => 'unknown code', status => 404 );
my $uri = $demo->airlock->verification_uri.'?user_code='.$view->{user_code};
$c->render( data => Airlock::QR->new( text => $uri )->svg, format => 'svg' );
};
app->start;
```
`examples/login.pl`:
```perl
#!/usr/bin/env perl
# The device side: get a token from one of the example apps.
#
# perl -Ilib examples/login.pl [scope ...]
#
# Against an OpenID Connect provider, pass issuer => 'https://.../realms/x'
# instead of the two endpoints and let the client discover them.
use strict;
use warnings;
use Airlock::Client;
my $base = $ENV{AIRLOCK_EXAMPLE_URL} // 'http://localhost:5000';
my $client = Airlock::Client->new(
client_id => 'demo-cli',
scope => join( ' ', @ARGV ),
device_endpoint => $base.'/airlock/device',
token_endpoint => $base.'/airlock/token'
);
my $token = $client->login;
print 'access_token: '.$token->{access_token}."\n";
print 'scope: '.( $token->{scope} // '' )."\n";
```
- [ ] **Step 9: App-Tests laufen lassen**
Run: `prove -lr t/82-example-psgi.t t/83-example-mojo.t`
Expected: PASS (5 Subtests und 22 Tests).
- [ ] **Step 10: Von Hand ausprobieren**
Terminal 1: `plackup -Ilib -Iexamples/lib examples/app.psgi`
Terminal 2: `perl -Ilib examples/login.pl read admin`
Expected: Terminal 2 zeigt URL, Code und QR-Code. Im Browser `http://localhost:5000/approve` öffnen, Code eingeben, PIN `4711`, bestätigen. Terminal 2 gibt innerhalb von fünf Sekunden `access_token:` und `scope: read admin` aus.
- [ ] **Step 11: `README.md` ersetzen**
`README.md`:
````markdown
# Airlock
Embeddable device authorization (RFC 8628) with step-up second factors.
A device or CLI shows a short code. A logged-in person enters or scans it
somewhere else, sees who wants what, approves â if the policy says so, only
after a second factor â and the device gets its token.
Airlock is a core to embed, not an application. The host application supplies
who is logged in, the approval page and four storage subs. Airlock supplies
codes, the state machine, poll rules, one-time redemption, step-up policy,
second factors, QR codes, the two machine endpoints, and a device-flow client.
It has no HTML, no database driver and no web framework at runtime.
## Installation
```bash
cpanm Airlock
```
## Embedding
```perl
use Airlock;
use Airlock::Factor::Callback;
my $airlock = Airlock->new(
clients => { 'my-cli' => { name => 'My CLI', scopes => [qw( read admin )] } },
verification_uri => 'https://my.example.org/approve',
store => { insert => sub {...}, find => sub {...}, update => sub {...}, purge => sub {...} },
policy => { step_up => { admin => ['totp'] } },
factors => [ Airlock::Factor::Callback->new( name => 'totp', amr => 'otp', verify => sub {...} ) ],
);
```
### Machine side
```perl
# PSGI, no Plack needed
builder { mount '/airlock' => $airlock->to_app; mount '/' => $app };
# HTTP::Request in, HTTP::Response out
my $response = Airlock::HTTPMessage->new( airlock => $airlock )->handle( $request, ip => $remote_address );
# anything else
my ( $status, $headers, $json ) = @{ $airlock->respond( 'POST', $path, \%form, { ip => $ip, ua => $ua } ) };
```
Two routes, matched on the last path segment: `POST .../device` and
`POST .../token`.
### Human side
The approval page is yours. Airlock gives it data and takes its decision:
```perl
my $view = $airlock->inspect( $typed_code, subject => $subject ) or return not_found();
my $needs = $airlock->requirements( $view, $subject ); # ['totp']
my $done = $airlock->approve( $typed_code, subject => $subject, proofs => { totp => $typed } );
my $done = $airlock->deny( $typed_code, subject => $subject );
```
`$subject` is who is logged in: `{ id => ... }`, optionally with `amr`, `acr`
and `auth_time` from your identity provider. Login, CSRF protection and rate
limits are yours too; `on_event` reports every `code_miss` and
`factor_failed` to hang a limit on.
## Store
Four subs against whatever database you have:
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
## QR codes
```perl
my $qr = Airlock::QR->new( text => $verification_uri_complete );
$qr->svg; # for the web
$qr->data_uri; # for an <img>
$qr->terminal; # for a CLI
```
## Client
```perl
my $token = Airlock::Client->new(
issuer => 'https://id.example.org/realms/main',
client_id => 'my-cli',
)->login;
```
Works against Airlock, Keycloak and any other RFC 8628 server.
## Examples
`examples/` has the whole thing running: `app.psgi` (Plack) and `mojo.pl`
(Mojolicious) with a minimal approval page, `login.pl` as the device, and the
store on DBI and on DBIO.
## License
This library is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.
````
- [ ] **Step 12: Alles laufen lassen**
Run: `prove -lr t && dzil test`
Expected: beide PASS. `dzil test` prüft zusätzlich die POD-Syntax nach dem Weaving.
- [ ] **Step 13: Ãbergabe**
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;
docs/superpowers/plans/2026-10-02-airlock-phase-1.md view on Meta::CPAN
## 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.525 second using v1.01-cache-2.11-cpan-99fa8243a42 )