Airlock

 view release on metacpan or  search on metacpan

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

**Files:**
- Create: `examples/schema.sql`
- Create: `examples/lib/AirlockExample/StoreDBI.pm`, `examples/lib/AirlockExample/Schema.pm`, `examples/lib/AirlockExample/Schema/Result/Airlock.pm`, `examples/lib/AirlockExample/StoreDBIO.pm`, `examples/lib/AirlockExample/Demo.pm`
- Create: `examples/app.psgi`, `examples/mojo.pl`, `examples/login.pl`
- Test: `t/80-example-store-dbi.t`, `t/81-example-store-dbio.t`, `t/82-example-psgi.t`, `t/83-example-mojo.t`
- Modify: `README.md` (ganz ersetzen)

**Interfaces:**
- Consumes: alles aus den Aufgaben 1 bis 7; insbesondere `Airlock->row_fields`, `Airlock::Test::Store`, `->to_app`, `->respond`, `->parse_form`, `->inspect`, `->requirements`, `->approve`, `->deny`, `Airlock::QR->svg`, `Airlock::Client->login`.
- Produces: nichts, worauf andere Aufgaben bauen.

Die vier Tests überspringen sich selbst, wenn ihre optionale Abhängigkeit fehlt (`DBD::SQLite`, `DBIO`, `Plack`, `Mojolicious`). Zum Ausführen dieser Aufgabe müssen alle vier installiert sein, sonst ist nichts bewiesen: `cpanm DBD::SQLite Plack M...

- [ ] **Step 1: Die Tests schreiben**

`t/80-example-store-dbi.t`:

```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use lib 'examples/lib';

BEGIN {
  plan skip_all => 'DBI and DBD::SQLite are needed for this example'
    unless eval { require DBI; require DBD::SQLite; 1 };
}

use Path::Tiny qw( path );
use Airlock;
use Airlock::Test::Store;
use AirlockExample::StoreDBI;

sub database {
  my $dbh = DBI->connect( 'dbi:SQLite:dbname=:memory:', '', '', { RaiseError => 1, PrintError => 0 } );
  $dbh->do($_) for grep { /\S/ } split /;/, path('examples/schema.sql')->slurp_utf8 =~ s/^--.*$//mgr;
  return $dbh;
}

subtest 'store contract' => sub {
  Airlock::Test::Store->new( store => AirlockExample::StoreDBI->new( dbh => database() )->as_subs )->run;
};

subtest 'a whole flow on the database' => sub {
  my $dbh     = database();
  my $clock   = 1_000_000;
  my $airlock = Airlock->new(
    clients          => { cli => {} },
    verification_uri => 'https://example.org/airlock',
    store            => AirlockExample::StoreDBI->new( dbh => sub { $dbh } )->as_subs,
    now              => sub { $clock }
  );
  my $start = $airlock->open( client_id => 'cli', scope => 'read' )->data;
  is( $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->status, 'authorization_pending', 'pending' );
  ok( $airlock->approve( $start->{user_code}, subject => { id => 'alice', amr => [qw( pwd otp )] } )->ok, 'approved' );
  $clock += 5;
  my $token = $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->data->{access_token};
  is_deeply( $airlock->verify_token($token)->{amr}, [qw( pwd otp )], 'the token verifies from the database' );
  is( $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->status, 'invalid_grant', 'redeemed once' );
  my ( $secrets ) = $dbh->selectrow_array( 'SELECT COUNT(*) FROM airlock WHERE hash IN (?, ?)', undef, $start->{device_code}, $token );
  is( $secrets, 0, 'neither the device code nor the token is in the table' );
  $clock += 4000;
  is( $airlock->purge, 2, 'purge removes request and token' );
};

done_testing;
```

`t/81-example-store-dbio.t`:

```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use lib 'examples/lib';

BEGIN {
  plan skip_all => 'DBIO and DBD::SQLite are needed for this example'
    unless eval { require DBIO; require DBD::SQLite; 1 };
}

use Path::Tiny qw( path );
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`:

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

  last_poll       BIGINT,
  subject         VARCHAR(255),
  amr             VARCHAR(255),
  acr             VARCHAR(255),
  auth_time       BIGINT,
  approved        BIGINT,
  origin_ip       VARCHAR(64),
  origin_ua       VARCHAR(255),
  factor_failures INTEGER      NOT NULL DEFAULT 0
);

CREATE INDEX airlock_expires ON airlock (expires);
```

- [ ] **Step 4: Den DBI-Store schreiben**

`examples/lib/AirlockExample/StoreDBI.pm`:

```perl
package AirlockExample::StoreDBI;

# The four Airlock store subs on plain DBI. Table: examples/schema.sql.
#
#   my $store   = AirlockExample::StoreDBI->new( dbh => $dbh );
#   my $airlock = Airlock->new( store => $store->as_subs, ... );
#
# The handle must have RaiseError set: insert relies on the database refusing
# a duplicate hash or user code.

use Moo;
use Airlock;
use Carp qw( croak );
use namespace::autoclean;

# a DBI handle, or a coderef returning one (for connection pools and forks)
has dbh => ( is => 'ro', required => 1 );

has table => ( is => 'ro', default => 'airlock' );

sub _dbh {
  my ( $self ) = @_;
  return ref $self->dbh eq 'CODE' ? $self->dbh->() : $self->dbh;
}

sub _fields { Airlock->row_fields }

sub insert {
  my ( $self, $row ) = @_;
  my @fields = $self->_fields;
  $self->_dbh->do(
    'INSERT INTO '.$self->table.' ('.join( ', ', @fields ).') VALUES ('.join( ', ', ('?') x @fields ).')',
    undef, @{$row}{@fields}
  );
  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;
  return $self->_dbh->selectrow_hashref(
    'SELECT '.join( ', ', $self->_fields ).' FROM '.$self->table.' WHERE '.$field.' = ?', undef, $value
  );
}

# The WHERE on the old state is the whole point: of two concurrent redeems
# only one statement changes a row.
sub update {
  my ( $self, $hash, $from_state, $changes ) = @_;
  my %known  = map { $_ => 1 } $self->_fields;
  my @fields = sort keys %$changes;
  croak __PACKAGE__.'->update unknown field' if grep { !$known{$_} } @fields;
  my $changed = $self->_dbh->do(
    'UPDATE '.$self->table.' SET '.join( ', ', map { $_.' = ?' } @fields ).' WHERE hash = ? AND state = ?',
    undef, @{$changes}{@fields}, $hash, $from_state
  );
  return $changed > 0 ? 1 : 0;
}

sub purge {
  my ( $self, $before ) = @_;
  return $self->_dbh->do( 'DELETE FROM '.$self->table.' WHERE expires < ?', undef, $before ) + 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 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;



( run in 0.739 second using v1.01-cache-2.11-cpan-1bcd28dbaf1 )