| 1 | package Browser::OIDC; | ||
| 2 | |||
| 3 | use 5.020; | ||
| 4 | use warnings; | ||
| 5 | use experimental qw/signatures postderef lexical_subs/; | ||
| 6 | |||
| 7 | use Browser::Open 'open_browser'; | ||
| 8 | use Carp; | ||
| 9 | use Digest::SHA 'sha256'; | ||
| 10 | use List::Util 1.33 qw/first none/; | ||
| 11 | use MIME::Base64 qw/encode_base64 encode_base64url decode_base64url/; | ||
| 12 | use Mojo::JSON 'decode_json'; | ||
| 13 | use Mojo::Server::Daemon; | ||
| 14 | use Mojo::URL; | ||
| 15 | use Mojo::UserAgent; | ||
| 16 | use Mojo::Util qw/encode random_bytes url_escape xml_escape/; | ||
| 17 | |||
| 18 | use Browser::OIDC::TokenResponse; | ||
| 19 | |||
| 20 | our $VERSION = '0.004'; | ||
| 21 | |||
| 22 | my $ua = Mojo::UserAgent->new; | ||
| 23 | |||
| 24 | my sub validate_url($name, $url) { | ||
| 25 | croak "$name is undefined" unless defined $url; | ||
| 26 | my $uri = Mojo::URL->new($url); | ||
| 27 | croak "Invalid URL for $name" unless ($uri->scheme // '') eq 'https' && length $uri->host; | ||
| 28 | } | ||
| 29 | |||
| 30 | sub new_from_discovery($class, $target_base) { | ||
| 31 | validate_url('target_base', $target_base); | ||
| 32 | my $response = $ua->get("$target_base/.well-known/openid-configuration")->result; | ||
| 33 | croak "Error: ". $response->code if not $response->is_success; | ||
| 34 | my $config = $response->json; | ||
| 35 | croak "Error: non-matching issuer" if $config->{issuer} ne $target_base; | ||
| 36 | return $class->new_from_config($config); | ||
| 37 | } | ||
| 38 | |||
| 39 | sub new_from_config($class, $config) { | ||
| 40 | validate_url($_, $config->{$_}) for qw/issuer authorization_endpoint token_endpoint jwks_uri/; | ||
| 41 | defined $config->{$_} && validate_url($_, $config->{$_}) for qw/userinfo_endpoint/; | ||
| 42 | my $auth_methods_supported = $config->{token_endpoint_auth_methods_supported} // ['client_secret_basic']; | ||
| 43 | my %auth_methods_supported = map { $_ => 1 } $auth_methods_supported->@*; | ||
| 44 | my $auth_method = first { $auth_methods_supported{$_} } qw/client_secret_post client_secret_basic none/; | ||
| 45 | croak("Don't know how to authenticate token") unless $auth_method; | ||
| 46 | my $grant_types_supported = $config->{grant_types_supported} // ['authorization_code']; | ||
| 47 | croak "Only Authorization Code Flow is supported yet" if none { $_ eq 'authorization_code' } $grant_types_supported->@*; | ||
| 48 | my $response_types_supported = $config->{response_types_supported} // ['code']; | ||
| 49 | croak "code is required for authorization code flow" if none { $_ eq 'code' } $response_types_supported->@*; | ||
| 50 | |||
| 51 | return bless { | ||
| 52 | $config->%{qw/issuer authorization_endpoint token_endpoint userinfo_endpoint claims_supported scopes_supported jwks_uri/}, | ||
| 53 | auth_method => $auth_method, | ||
| 54 | response_iss => !!$config->{authorization_response_iss_parameter_supported}, | ||
| 55 | ua => $ua, | ||
| 56 | }, $class; | ||
| 57 | } | ||
| 58 | |||
| 59 | my sub form_escape($input) { | ||
| 60 | return url_escape(encode('UTF-8', $input)) =~ s/%20/+/gr; | ||
| 61 | } | ||
| 62 | |||
| 63 | my sub term_escape($input) { | ||
| 64 | return $input =~ s/[[:cntrl:]]//gr; | ||
| 65 | } | ||
| 66 | |||
| 67 | sub get_token($self, %options) { | ||
| 68 | my $client_id = $options{client_id} // croak 'No client id given'; | ||
| 69 | |||
| 70 | my $state = encode_base64url(random_bytes(16)); | ||
| 71 | |||
| 72 | my $loop = Mojo::IOLoop->new; | ||
| 73 | my $daemon = Mojo::Server::Daemon->new(ioloop => $loop, listen => ['http://localhost:0'], silent => 1); | ||
| 74 | my $ioloop = $daemon->ioloop; | ||
| 75 | my ($code, $exception); | ||
| 76 | $daemon->on(request => sub ($daemon, $tx) { | ||
| 77 | my $request = $tx->req; | ||
| 78 | |||
| 79 | if ($request->url->path eq '/auth/callback') { | ||
| 80 | my $received_state = $request->url->query->param('state'); | ||
| 81 | if ($received_state ne $state) { | ||
| 82 | $tx->res->code(400); | ||
| 83 | $tx->res->body('Invalid state'); | ||
| 84 | $tx->resume; | ||
| 85 | } elsif ($self->{response_iss} and $request->url->query->param('iss') ne $self->{issuer}) { | ||
| 86 | $tx->res->code(400); | ||
| 87 | $tx->res->body('Incorrect issuer'); | ||
| 88 | $tx->resume; | ||
| 89 | } elsif (my $error = $request->url->query->param('error')) { | ||
| 90 | my $message = $request->url->query->param('error_description') // $error; | ||
| 91 | $tx->res->code(400); | ||
| 92 | $tx->res->body(xml_escape($message)); | ||
| 93 | $exception = term_escape($message); | ||
| 94 | $tx->on(finish => sub { $ioloop->stop }); | ||
| 95 | $tx->resume; | ||
| 96 | } elsif (defined($code = $request->url->query->param('code'))) { | ||
| 97 | $tx->res->code(200); | ||
| 98 | $tx->res->headers->content_type($options{message_type}) if $options{message_type}; | ||
| 99 | $tx->res->body($options{message} // 'Authorization token received, you can close this now'); | ||
| 100 | $tx->on(finish => sub { $ioloop->stop }); | ||
| 101 | $tx->resume; | ||
| 102 | } else { | ||
| 103 | $tx->res->code(400); | ||
| 104 | $tx->res->body('Missing code'); | ||
| 105 | $tx->resume; | ||
| 106 | return; | ||
| 107 | } | ||
| 108 | } else { | ||
| 109 | $tx->res->code(400); | ||
| 110 | $tx->resume; | ||
| 111 | } | ||
| 112 | }); | ||
| 113 | $daemon->start; | ||
| 114 | |||
| 115 | my ($port) = $daemon->ports->@*; | ||
| 116 | my $redirect_uri = "http://localhost:$port/auth/callback"; | ||
| 117 | my $full_target = Mojo::URL->new($self->{authorization_endpoint}); | ||
| 118 | $full_target->query->append(response_type => 'code'); | ||
| 119 | $full_target->query->append(redirect_uri => $redirect_uri); | ||
| 120 | $full_target->query->append(client_id => $client_id); | ||
| 121 | my $code_verifier = encode_base64url(random_bytes(32)); | ||
| 122 | $full_target->query->append(code_challenge => encode_base64url(sha256($code_verifier))); | ||
| 123 | $full_target->query->append(code_challenge_method => 'S256'); | ||
| 124 | my @scope = 'openid'; | ||
| 125 | push @scope, $options{scope}->@* if $options{scope}; | ||
| 126 | $full_target->query->append(scope => join ' ', @scope); | ||
| 127 | $full_target->query->append(state => $state); | ||
| 128 | my $nonce = exists $options{nonce} ? $options{nonce} : encode_base64url(random_bytes(32)); | ||
| 129 | $full_target->query->append(nonce => $nonce) if defined $nonce; | ||
| 130 | for my $name (qw/display max_age/) { | ||
| 131 | $full_target->query->append($name => $options{$name}) if defined $options{$name}; | ||
| 132 | } | ||
| 133 | $full_target->query->append(prompt => join ' ', $options{prompt}->@*) if defined $options{prompt}; | ||
| 134 | |||
| 135 | my $timeout = $options{timeout} // 60; | ||
| 136 | my $timer = $ioloop->timer($timeout, sub { | ||
| 137 | $exception = 'Timeout'; | ||
| 138 | $ioloop->stop; | ||
| 139 | }); | ||
| 140 | |||
| 141 | my $ok = open_browser($full_target); | ||
| 142 | say "Could not open browser: please open $full_target manually" if not defined $ok or $ok != 0; | ||
| 143 | |||
| 144 | $ioloop->start; | ||
| 145 | $ioloop->remove($timer); | ||
| 146 | croak $exception if $exception; | ||
| 147 | croak 'No authorization code received' unless defined $code; | ||
| 148 | |||
| 149 | my %arguments = ( | ||
| 150 | grant_type => 'authorization_code', | ||
| 151 | redirect_uri => $redirect_uri, | ||
| 152 | code => $code, | ||
| 153 | code_verifier => $code_verifier, | ||
| 154 | ); | ||
| 155 | my %headers; | ||
| 156 | my $client_secret = $options{client_secret} // ''; | ||
| 157 | if ($self->{auth_method} eq 'client_secret_post') { | ||
| 158 | $arguments{client_id} = $client_id; | ||
| 159 | $arguments{client_secret} = $client_secret; | ||
| 160 | } elsif ($self->{auth_method} eq 'client_secret_basic') { | ||
| 161 | my $auth = join ':', form_escape($client_id), form_escape($client_secret); | ||
| 162 | $headers{Authorization} = 'Basic ' . encode_base64($auth, ''); | ||
| 163 | } else { | ||
| 164 | $arguments{client_id} = $client_id; | ||
| 165 | } | ||
| 166 | my $response = $ua->post($self->{token_endpoint}, \%headers, form => \%arguments)->result; | ||
| 167 | if ($response->is_success) { | ||
| 168 | return Browser::OIDC::TokenResponse->new(parent => $self, value => $response->json, nonce => $nonce); | ||
| 169 | } else { | ||
| 170 | croak sprintf "Could not get token (%s): %s", $response->code , term_escape($response->body); | ||
| 171 | } | ||
| 172 | } | ||
| 173 | |||
| 174 | sub issuer($self) { | ||
| 175 | return $self->{issuer}; | ||
| 176 | } | ||
| 177 | |||
| 178 | sub claims_supported($self) { | ||
| 179 | return ($self->{claims_supported} // [])->@*; | ||
| 180 | } | ||
| 181 | |||
| 182 | sub scopes_supported($self) { | ||
| 183 | return ($self->{scopes_supported} // [])->@*; | ||
| 184 | } | ||
| 185 | |||
| 186 | sub jwks($self) { | ||
| 187 | return $self->{jwks} //= do { | ||
| 188 | my $response = $ua->get($self->{jwks_uri})->result; | ||
| 189 | croak "Could not fetch JSON Web Key Set" if not $response->is_success; | ||
| 190 | $response->json; | ||
| 191 | }; | ||
| 192 | } | ||
| 193 | |||
| 194 | 1; | ||
| 195 | |||
| 196 | __END__ |