| 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 Crypt::SysRandom 0.008 'random_base64url'; | ||
| 11 | use HTML::Entities 'encode_entities'; | ||
| 12 | use HTTP::Daemon; | ||
| 13 | use HTTP::Headers; | ||
| 14 | use HTTP::Response; | ||
| 15 | use HTTP::Tiny; | ||
| 16 | use JSON::MaybeXS; | ||
| 17 | use List::Util 1.33 qw/first none/; | ||
| 18 | use MIME::Base64 qw/encode_base64 encode_base64url decode_base64url/; | ||
| 19 | use URI; | ||
| 20 | use URI::Escape 'uri_escape_utf8'; | ||
| 21 | |||
| 22 | use Browser::OIDC::TokenResponse; | ||
| 23 | |||
| 24 | our $VERSION = '0.003'; | ||
| 25 | |||
| 26 | my $tiny = HTTP::Tiny->new(verify_SSL => 1); | ||
| 27 | |||
| 28 | my sub validate_url($name, $url) { | ||
| 29 | croak "$name is undefined" unless defined $url; | ||
| 30 | my $uri = URI->new($url); | ||
| 31 | croak "Invalid URL for $name" unless ($uri->scheme // '') eq 'https' && length $uri->host; | ||
| 32 | } | ||
| 33 | |||
| 34 | sub new_from_discovery($class, $target_base) { | ||
| 35 | validate_url('target_base', $target_base); | ||
| 36 | my $response = $tiny->get("$target_base/.well-known/openid-configuration"); | ||
| 37 | croak "Error: $response->{status}" if $response->{status} != 200; | ||
| 38 | my $config = decode_json($response->{content}); | ||
| 39 | croak "Error: non-matching issuer" if $config->{issuer} ne $target_base; | ||
| 40 | return $class->new_from_config($config); | ||
| 41 | } | ||
| 42 | |||
| 43 | sub new_from_config($class, $config) { | ||
| 44 | validate_url($_, $config->{$_}) for qw/issuer authorization_endpoint token_endpoint jwks_uri/; | ||
| 45 | defined $config->{$_} && validate_url($_, $config->{$_}) for qw/userinfo_endpoint/; | ||
| 46 | my $auth_methods_supported = $config->{token_endpoint_auth_methods_supported} // ['client_secret_basic']; | ||
| 47 | my %auth_methods_supported = map { $_ => 1 } $auth_methods_supported->@*; | ||
| 48 | my $auth_method = first { $auth_methods_supported{$_} } qw/client_secret_post client_secret_basic none/; | ||
| 49 | croak("Don't know how to authenticate token") unless $auth_method; | ||
| 50 | my $grant_types_supported = $config->{grant_types_supported} // ['authorization_code']; | ||
| 51 | croak "Only Authorization Code Flow is supported yet" if none { $_ eq 'authorization_code' } $grant_types_supported->@*; | ||
| 52 | my $response_types_supported = $config->{response_types_supported} // ['code']; | ||
| 53 | croak "code is required for authorization code flow" if none { $_ eq 'code' } $response_types_supported->@*; | ||
| 54 | |||
| 55 | return bless { | ||
| 56 | $config->%{qw/issuer authorization_endpoint token_endpoint userinfo_endpoint claims_supported scopes_supported jwks_uri/}, | ||
| 57 | auth_method => $auth_method, | ||
| 58 | response_iss => !!$config->{authorization_response_iss_parameter_supported}, | ||
| 59 | tiny => $tiny, | ||
| 60 | }, $class; | ||
| 61 | } | ||
| 62 | |||
| 63 | my sub form_escape($input) { | ||
| 64 | return uri_escape_utf8($input) =~ s/%20/+/gr; | ||
| 65 | } | ||
| 66 | |||
| 67 | my sub term_escape($input) { | ||
| 68 | return $input =~ s/[[:cntrl:]]//gr; | ||
| 69 | } | ||
| 70 | |||
| 71 | sub get_token($self, %options) { | ||
| 72 | my $client_id = $options{client_id} // croak 'No client id given'; | ||
| 73 | |||
| 74 | my $daemon = HTTP::Daemon->new(LocalAddr => 'localhost', Timeout => $options{timeout} // 60); | ||
| 75 | my $port = $daemon->sockport; | ||
| 76 | my $redirect_uri = "http://localhost:$port/auth/callback"; | ||
| 77 | my $full_target = URI->new($self->{authorization_endpoint}); | ||
| 78 | $full_target->query_param_append(response_type => 'code'); | ||
| 79 | $full_target->query_param_append(redirect_uri => $redirect_uri); | ||
| 80 | $full_target->query_param_append(client_id => $client_id); | ||
| 81 | my $code_verifier = random_base64url(32); | ||
| 82 | $full_target->query_param_append(code_challenge => encode_base64url(sha256($code_verifier))); | ||
| 83 | $full_target->query_param_append(code_challenge_method => 'S256'); | ||
| 84 | my @scope = 'openid'; | ||
| 85 | push @scope, $options{scope}->@* if $options{scope}; | ||
| 86 | $full_target->query_param_append(scope => join ' ', @scope); | ||
| 87 | my $state = random_base64url(16); | ||
| 88 | $full_target->query_param_append(state => $state); | ||
| 89 | my $nonce = exists $options{nonce} ? $options{nonce} : random_base64url(32); | ||
| 90 | $full_target->query_param_append(nonce => $nonce) if defined $nonce; | ||
| 91 | for my $name (qw/display max_age/) { | ||
| 92 | if (defined $options{$name}) { | ||
| 93 | $full_target->query_param_append($name => $options{$name}); | ||
| 94 | } | ||
| 95 | } | ||
| 96 | if ($options{prompt}) { | ||
| 97 | $full_target->query_param_append(prompt => join ' ', $options{prompt}->@*); | ||
| 98 | } | ||
| 99 | |||
| 100 | my $url = $full_target->canonical; | ||
| 101 | my $ok = open_browser($url); | ||
| 102 | say "Could not open browser: please open $url manually" if not defined $ok or $ok != 0; | ||
| 103 | while (1) { | ||
| 104 | my $sock = $daemon->accept or croak "Could not accept connection: $!"; | ||
| 105 | my $request = $sock->get_request or croak "Could not receive request"; | ||
| 106 | |||
| 107 | if ($request->uri->path eq '/auth/callback') { | ||
| 108 | my $received_state = $request->uri->query_param('state'); | ||
| 109 | if ($received_state ne $state) { | ||
| 110 | $sock->send_error(400, 'Invalid state'); | ||
| 111 | next; | ||
| 112 | } | ||
| 113 | |||
| 114 | if (my $error = $request->uri->query_param('error')) { | ||
| 115 | my $message = $request->uri->query_param('error_description') // $error; | ||
| 116 | $sock->send_error(400, encode_entities($message)); | ||
| 117 | croak term_escape($message); | ||
| 118 | } | ||
| 119 | |||
| 120 | my $code = $request->uri->query_param('code'); | ||
| 121 | if (not defined $code) { | ||
| 122 | $sock->send_error(400, 'Missing code'); | ||
| 123 | croak 'Missing code'; | ||
| 124 | } | ||
| 125 | |||
| 126 | if ($self->{response_iss} and $request->uri->query_param('iss') ne $self->{issuer}) { | ||
| 127 | $sock->send_error(400, 'Incorrect issuer'); | ||
| 128 | croak 'Incorrect issuer'; | ||
| 129 | } | ||
| 130 | |||
| 131 | my $message = $options{message} // 'Authorization token received, you can close this now'; | ||
| 132 | my $headers = HTTP::Headers->new; | ||
| 133 | $headers->header('content-type', $options{message_type}) if $options{message_type}; | ||
| 134 | $sock->send_response(HTTP::Response->new(200, 'OK', $headers, $message)); | ||
| 135 | close $sock; | ||
| 136 | |||
| 137 | my %arguments = ( | ||
| 138 | grant_type => 'authorization_code', | ||
| 139 | redirect_uri => $redirect_uri, | ||
| 140 | code => $code, | ||
| 141 | code_verifier => $code_verifier, | ||
| 142 | ); | ||
| 143 | my %headers; | ||
| 144 | my $client_secret = $options{client_secret} // ''; | ||
| 145 | if ($self->{auth_method} eq 'client_secret_post') { | ||
| 146 | $arguments{client_id} = $client_id; | ||
| 147 | $arguments{client_secret} = $client_secret; | ||
| 148 | } | ||
| 149 | elsif ($self->{auth_method} eq 'client_secret_post') { | ||
| 150 | my $auth = join ':', form_escape($client_id), form_escape($client_secret); | ||
| 151 | $headers{Authorization} = 'Basic ' . encode_base64($auth, ''); | ||
| 152 | } | ||
| 153 | my $response = $tiny->post_form($self->{token_endpoint}, \%arguments, { headers => \%headers }); | ||
| 154 | if ($response->{status} == 200) { | ||
| 155 | my $value = decode_json($response->{content}); | ||
| 156 | return Browser::OIDC::TokenResponse->new(parent => $self, value => $value, nonce => $nonce); | ||
| 157 | } else { | ||
| 158 | croak "Could not get token ($response->{status}): " , term_escape($response->{content}); | ||
| 159 | } | ||
| 160 | } else { | ||
| 161 | $sock->send_error(404); | ||
| 162 | close $sock; | ||
| 163 | } | ||
| 164 | } | ||
| 165 | } | ||
| 166 | |||
| 167 | sub issuer($self) { | ||
| 168 | return $self->{issuer}; | ||
| 169 | } | ||
| 170 | |||
| 171 | sub claims_supported($self) { | ||
| 172 | return $self->{claims_supported}->@*; | ||
| 173 | } | ||
| 174 | |||
| 175 | sub scopes_supported($self) { | ||
| 176 | return $self->{scopes_supported}->@*; | ||
| 177 | } | ||
| 178 | |||
| 179 | sub jwks($self) { | ||
| 180 | my $response = $tiny->get($self->{jwks_uri}); | ||
| 181 | croak "Could not fetch JSON Web Key Set" if $response->{status} != 200; | ||
| 182 | return decode_json($response->{content}); | ||
| 183 | } | ||
| 184 | |||
| 185 | 1; | ||
| 186 | |||
| 187 | __END__ |