| 1 | package Langertha::Knarr::Admin; | ||
| 2 | # ABSTRACT: Admin routes that deliver, rotate and drop a routing setup layered over Knarr's own, in memory only | ||
| 3 | our $VERSION = '1.103'; | ||
| 4 | use Moose; | ||
| 5 | use Carp qw( croak ); | ||
| 6 | use Digest::SHA qw( sha256 ); | ||
| 7 | use JSON::MaybeXS; | ||
| 8 | use Log::Any qw( $log ); | ||
| 9 | use POSIX (); | ||
| 10 | use Storable qw( dclone ); | ||
| 11 | use Try::Tiny; | ||
| 12 | use Langertha::Knarr::Config; | ||
| 13 | use Langertha::Knarr::Tracing; | ||
| 14 | |||
| 15 | |||
| 16 | my @ROUTES = ( | ||
| 17 | { method => 'GET', path => '/knarr/admin/status', action => 'admin_status' }, | ||
| 18 | { method => 'PUT', path => '/knarr/admin/config', action => 'admin_put_config' }, | ||
| 19 | { method => 'DELETE', path => '/knarr/admin/config', action => 'admin_delete_config' }, | ||
| 20 | { method => 'PATCH', path => '/knarr/admin/keys', action => 'admin_patch_keys' }, | ||
| 21 | ); | ||
| 22 | |||
| 23 | # Config keys that only take effect at start, named in a refusal; any other | ||
| 24 | # key a push may not set is counted, not echoed. | ||
| 25 | my @PROCESS_KEYS = qw( | ||
| 26 | listen workers logging admin_key remote_config public_url | ||
| 27 | ollama_compat_version a2a token_auth routes | ||
| 28 | ); | ||
| 29 | |||
| 30 | # Actions that read a body. | ||
| 31 | my %WITH_BODY = ( admin_put_config => 1, admin_patch_keys => 1 ); | ||
| 32 | |||
| 33 | around BUILDARGS => sub { | ||
| 34 | my ( $orig, $class, @args ) = @_; | ||
| 35 | my $args = $class->$orig(@args); | ||
| 36 | my $key = delete $args->{key}; | ||
| 37 | my $min = Langertha::Knarr::Config->admin_key_min_length; | ||
| 38 | croak __PACKAGE__.": key must be a string of at least $min characters" | ||
| 39 | unless defined $key && !ref $key && length $key >= $min; | ||
| 40 | $args->{_key_digest} = sha256( $class->_bytes($key) ); | ||
| 41 | return $args; | ||
| 42 | }; | ||
| 43 | |||
| 44 | has _key_digest => ( | ||
| 45 | is => 'ro', | ||
| 46 | required => 1, | ||
| 47 | ); | ||
| 48 | |||
| 49 | has stack => ( | ||
| 50 | is => 'ro', | ||
| 51 | required => 1, | ||
| 52 | writer => '_set_stack', | ||
| 53 | ); | ||
| 54 | |||
| 55 | has _boot_stack => ( | ||
| 56 | is => 'ro', | ||
| 57 | init_arg => undef, | ||
| 58 | writer => '_set_boot_stack', | ||
| 59 | ); | ||
| 60 | |||
| 61 | has remote_config => ( | ||
| 62 | is => 'ro', | ||
| 63 | isa => 'Bool', | ||
| 64 | default => 0, | ||
| 65 | ); | ||
| 66 | |||
| 67 | has configured => ( | ||
| 68 | is => 'ro', | ||
| 69 | init_arg => undef, | ||
| 70 | writer => '_set_configured', | ||
| 71 | ); | ||
| 72 | |||
| 73 | has generation => ( | ||
| 74 | is => 'ro', | ||
| 75 | init_arg => undef, | ||
| 76 | default => 0, | ||
| 77 | writer => '_set_generation', | ||
| 78 | ); | ||
| 79 | |||
| 80 | has applied_at => ( | ||
| 81 | is => 'ro', | ||
| 82 | init_arg => undef, | ||
| 83 | writer => '_set_applied_at', | ||
| 84 | ); | ||
| 85 | |||
| 86 | # The delivered layer (a HashRef of runtime keys) or undef: only in RAM. | ||
| 87 | has _push => ( | ||
| 88 | is => 'ro', | ||
| 89 | init_arg => undef, | ||
| 90 | writer => '_set_push', | ||
| 91 | ); | ||
| 92 | |||
| 93 | has max_body => ( | ||
| 94 | is => 'ro', | ||
| 95 | isa => 'Int', | ||
| 96 | default => 1_048_576, | ||
| 97 | ); | ||
| 98 | |||
| 99 | has free_failures => ( | ||
| 100 | is => 'ro', | ||
| 101 | isa => 'Int', | ||
| 102 | default => 2, | ||
| 103 | ); | ||
| 104 | |||
| 105 | has max_lockout => ( | ||
| 106 | is => 'ro', | ||
| 107 | isa => 'Int', | ||
| 108 | default => 300, | ||
| 109 | ); | ||
| 110 | |||
| 111 | # Wrong-key requests by peer address: { count, last, until }. | ||
| 112 | has _failures => ( | ||
| 113 | is => 'ro', | ||
| 114 | default => sub { {} }, | ||
| 115 | ); | ||
| 116 | |||
| 117 | has _json => ( | ||
| 118 | is => 'ro', | ||
| 119 | default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) }, | ||
| 120 | ); | ||
| 121 | |||
| 122 | sub BUILD { | ||
| 123 | my ($self) = @_; | ||
| 124 | $self->_set_boot_stack( $self->stack ); | ||
| 125 | $self->_set_configured( $self->_boot_configured ); | ||
| 126 | $self->_set_applied_at( $self->_now ); | ||
| 127 | } | ||
| 128 | |||
| 129 | sub config_class { 'Langertha::Knarr::Config' } | ||
| 130 | |||
| 131 | sub routes { map { { %$_ } } @ROUTES } | ||
| 132 | |||
| 133 | sub _now { time } | ||
| 134 | |||
| 135 | sub _bytes { | ||
| 136 | my ($self, $string) = @_; | ||
| 137 | utf8::encode($string) if utf8::is_utf8($string); | ||
| 138 | return $string; | ||
| 139 | } | ||
| 140 | |||
| 141 | # Whether the start layer alone can serve: it holds a routing setup, or | ||
| 142 | # remote_config is off (a config that must name its models). | ||
| 143 | sub _boot_configured { | ||
| 144 | my ($self) = @_; | ||
| 145 | return 1 unless $self->remote_config; | ||
| 146 | return $self->_boot_routable ? 1 : 0; | ||
| 147 | } | ||
| 148 | |||
| 149 | sub _boot_routable { | ||
| 150 | my ($self) = @_; | ||
| 151 | my $config = $self->_boot_stack->config; | ||
| 152 | return 1 if eval { %{ $config->models } }; | ||
| 153 | return 1 if eval { $config->default_engine }; | ||
| 154 | return 1 if eval { %{ $config->passthrough } }; | ||
| 155 | return 0; | ||
| 156 | } | ||
| 157 | |||
| 158 | # 'file', 'env' (a config not read from a file) or undef: no start layer. | ||
| 159 | sub _boot_layer { | ||
| 160 | my ($self) = @_; | ||
| 161 | my $config = $self->_boot_stack->config; | ||
| 162 | return 'file' if $config->can('has_file') && $config->has_file; | ||
| 163 | return $self->_boot_routable ? 'env' : undef; | ||
| 164 | } | ||
| 165 | |||
| 166 | sub is_key { | ||
| 167 | my ($self, $candidate) = @_; | ||
| 168 | return 0 unless defined $candidate && !ref $candidate && length $candidate; | ||
| 169 | # Digests of equal length, compared without an early exit: the time does | ||
| 170 | # not depend on how much of the key was right. | ||
| 171 | my $given = sha256( $self->_bytes($candidate) ); | ||
| 172 | my $want = $self->_key_digest; | ||
| 173 | my $diff = 0; | ||
| 174 | $diff |= ord( substr $given, $_, 1 ) ^ ord( substr $want, $_, 1 ) for 0 .. 31; | ||
| 175 | return $diff ? 0 : 1; | ||
| 176 | } | ||
| 177 | |||
| 178 | sub handle { | ||
| 179 | my ($self, %args) = @_; | ||
| 180 | my $action = $args{action} // ''; | ||
| 181 | my $peer = defined $args{peer} && length $args{peer} ? $args{peer} : 'unknown'; | ||
| 182 | |||
| 183 | if ( my $wait = $self->_locked_for($peer) ) { | ||
| 184 | return $self->_answer( 429, 'too many requests without the admin key, try again later', | ||
| 185 | [ 'Retry-After' => $wait ] ); | ||
| 186 | } | ||
| 187 | unless ( $self->_authorized( $args{request} ) ) { | ||
| 188 | $self->_record_failure($peer); | ||
| 189 | return $self->_answer( 401, 'unauthorized' ); | ||
| 190 | } | ||
| 191 | delete $self->_failures->{$peer}; | ||
| 192 | |||
| 193 | return $self->_answer( 501, 'the admin routes need a single-process server:' | ||
| 194 | . ' every process holds its own setup in memory (psgi.multiprocess is set)' ) | ||
| 195 | if $args{multiprocess}; | ||
| 196 | |||
| 197 | my $body = ''; | ||
| 198 | if ( $WITH_BODY{$action} ) { | ||
| 199 | my $max = $self->max_body; | ||
| 200 | return $self->_answer( 413, "the request body may be at most $max bytes" ) | ||
| 201 | if ( $args{content_length} // 0 ) > $max; | ||
| 202 | $body = $args{body} ? $args{body}->() : ''; | ||
| 203 | $body = '' unless defined $body; | ||
| 204 | return $self->_answer( 413, "the request body may be at most $max bytes" ) | ||
| 205 | if length $body > $max; | ||
| 206 | } | ||
| 207 | |||
| 208 | my $method = '_'.$action; | ||
| 209 | return $self->_answer( 404, 'no such admin route' ) unless $self->can($method); | ||
| 210 | my @answer; | ||
| 211 | try { | ||
| 212 | @answer = $self->$method( $args{knarr}, $body ); | ||
| 213 | } catch { | ||
| 214 | # Whatever died here may carry a piece of the body: logged without it. | ||
| 215 | $log->errorf( "Admin request %s failed: %s", $action, | ||
| 216 | $self->_scrub( $self->_first_line($_), $self->_doc_or_undef($body) ) ); | ||
| 217 | @answer = $self->_answer( 500, 'the admin request failed' ); | ||
| 218 | }; | ||
| 219 | return @answer; | ||
| 220 | } | ||
| 221 | |||
| 222 | sub status { | ||
| 223 | my ($self) = @_; | ||
| 224 | my $config = $self->stack->config; | ||
| 225 | my $configured = $self->configured; | ||
| 226 | my $models = $configured ? eval { $config->models } || {} : {}; | ||
| 227 | my $default = $configured ? eval { $config->default_engine } : undef; | ||
| 228 | my $upstreams = $configured ? eval { $config->passthrough } || {} : {}; | ||
| 229 | my $at = $self->applied_at; | ||
| 230 | my $base = $self->_boot_layer; | ||
| 231 | return { | ||
| 232 | generation => $self->generation + 0, | ||
| 233 | applied_at => POSIX::strftime( '%Y-%m-%dT%H:%M:%SZ', gmtime $at ), | ||
| 234 | applied_at_epoch => $at + 0, | ||
| 235 | layers => [ ( $base ? ($base) : () ), ( $self->_push ? ('push') : () ) ], | ||
| 236 | configured => $configured ? JSON::MaybeXS->true : JSON::MaybeXS->false, | ||
| 237 | remote_config => $self->remote_config ? JSON::MaybeXS->true : JSON::MaybeXS->false, | ||
| 238 | models => [ sort keys %$models ], | ||
| 239 | default_engine => $default ? JSON::MaybeXS->true : JSON::MaybeXS->false, | ||
| 240 | passthrough => [ sort keys %$upstreams ], | ||
| 241 | ( $self->stack->authorizer | ||
| 242 | ? ( token_auth => $self->_token_auth_status ) : () ), | ||
| 243 | }; | ||
| 244 | } | ||
| 245 | |||
| 246 | # token_auth on: the backend and whether the store has a connection right | ||
| 247 | # now. Never the dsn, user, password, relation or channel, and nothing of a | ||
| 248 | # token (k82). | ||
| 249 | sub _token_auth_status { | ||
| 250 | my ($self) = @_; | ||
| 251 | my $stack = $self->stack; | ||
| 252 | my $store = $stack->token_store; | ||
| 253 | return { | ||
| 254 | backend => $stack->config->token_auth->{backend}, | ||
| 255 | connected => ( $store && $store->available ? JSON::MaybeXS->true : JSON::MaybeXS->false ), | ||
| 256 | }; | ||
| 257 | } | ||
| 258 | |||
| 259 | #### Actions | ||
| 260 | |||
| 261 | sub _admin_status { | ||
| 262 | my ($self) = @_; | ||
| 263 | return $self->_answer( 200, $self->status ); | ||
| 264 | } | ||
| 265 | |||
| 266 | sub _admin_put_config { | ||
| 267 | my ($self, $knarr, $body) = @_; | ||
| 268 | my ( $doc, $error ) = $self->_decode($body); | ||
| 269 | return $self->_refuse($error) unless $doc; | ||
| 270 | return $self->_refuse('the setup must be a JSON object') unless ref $doc eq 'HASH'; | ||
| 271 | # A pushed setup carries its keys literally. An api_key_env would hand the | ||
| 272 | # start environment's secrets to whatever url the same push names. | ||
| 273 | if ( my @env = $self->_env_key_refs($doc) ) { | ||
| 274 | return $self->_refuse( 'api_key_env is not accepted in a delivered setup (' | ||
| 275 | . join( ', ', @env ) . '); deliver the key itself as api_key' ); | ||
| 276 | } | ||
| 277 | # A pushed langfuse url travels with its own keys: merged key by key, a url | ||
| 278 | # alone would receive the config file's Langfuse keys (Basic auth). | ||
| 279 | if ( ref $doc->{langfuse} eq 'HASH' && exists $doc->{langfuse}{url} ) { | ||
| 280 | my $lf = $doc->{langfuse}; | ||
| 281 | return $self->_refuse('langfuse.url is accepted only together with' | ||
| 282 | . ' langfuse.public_key and langfuse.secret_key in the same push' ) | ||
| 283 | unless defined $lf->{public_key} && length $lf->{public_key} | ||
| 284 | && defined $lf->{secret_key} && length $lf->{secret_key}; | ||
| 285 | } | ||
| 286 | my %runtime = map { $_ => 1 } $self->config_class->runtime_keys; | ||
| 287 | if ( my @other = grep { !$runtime{$_} } sort keys %$doc ) { | ||
| 288 | my %process = map { $_ => 1 } @PROCESS_KEYS; | ||
| 289 | my @named = grep { $process{$_} } @other; | ||
| 290 | my $unknown = @other - @named; | ||
| 291 | return $self->_refuse( 'only the routing setup can be set at runtime (' | ||
| 292 | . join( ', ', $self->config_class->runtime_keys ) . ')' | ||
| 293 | . ( @named ? '; '.join( ', ', @named ).' take effect only at start' : '' ) | ||
| 294 | . ( $unknown ? "; $unknown unknown key(s)" : '' ) ); | ||
| 295 | } | ||
| 296 | return $self->_install_runtime( $knarr, dclone($doc), 'replaced' ); | ||
| 297 | } | ||
| 298 | |||
| 299 | # Names of the model/default entries of a pushed setup that carry api_key_env. | ||
| 300 | sub _env_key_refs { | ||
| 301 | my ($self, $doc) = @_; | ||
| 302 | my @found; | ||
| 303 | my $models = ref $doc->{models} eq 'HASH' ? $doc->{models} : {}; | ||
| 304 | for my $name ( sort keys %$models ) { | ||
| 305 | my $def = $models->{$name}; | ||
| 306 | push @found, "models.$name" if ref $def eq 'HASH' && exists $def->{api_key_env}; | ||
| 307 | } | ||
| 308 | push @found, 'default' if ref $doc->{default} eq 'HASH' && exists $doc->{default}{api_key_env}; | ||
| 309 | return @found; | ||
| 310 | } | ||
| 311 | |||
| 312 | sub _admin_patch_keys { | ||
| 313 | my ($self, $knarr, $body) = @_; | ||
| 314 | return $self->_answer( 409, 'there is no setup to change keys in;' | ||
| 315 | . ' deliver one with PUT /knarr/admin/config' ) unless $self->configured; | ||
| 316 | my ( $doc, $error ) = $self->_decode($body); | ||
| 317 | return $self->_refuse($error) unless $doc; | ||
| 318 | return $self->_refuse('the body must be a JSON object of name: key pairs') | ||
| 319 | unless ref $doc eq 'HASH' && %$doc; | ||
| 320 | |||
| 321 | # Names are looked up in both layers; the key lands in the push layer. | ||
| 322 | my $push = dclone( $self->_push // {} ); | ||
| 323 | my $seen = $self->_layered($push); | ||
| 324 | my $models = ref $seen->{models} eq 'HASH' ? $seen->{models} : {}; | ||
| 325 | my $default = ref $seen->{default} eq 'HASH' ? $seen->{default} : undef; | ||
| 326 | my ( $bad, $unknown, $ambiguous ) = ( 0, 0, 0 ); | ||
| 327 | for my $name ( sort keys %$doc ) { | ||
| 328 | my $key = $doc->{$name}; | ||
| 329 | unless ( defined $key && !ref $key && length $key ) { $bad++; next } | ||
| 330 | my $def = ref $models->{$name} eq 'HASH' ? $models->{$name} : undef; | ||
| 331 | my $is_default = 0; | ||
| 332 | if ( $name eq 'default' && $default ) { | ||
| 333 | if ($def) { $ambiguous++; next } | ||
| 334 | ( $def, $is_default ) = ( $default, 1 ); | ||
| 335 | } | ||
| 336 | unless ($def) { $unknown++; next } | ||
| 337 | my $copy = dclone($def); | ||
| 338 | $copy->{api_key} = $key; | ||
| 339 | delete $copy->{api_key_env}; | ||
| 340 | if ($is_default) { $push->{default} = $copy } | ||
| 341 | else { $push->{models}{$name} = $copy } | ||
| 342 | } | ||
| 343 | my @problems; | ||
| 344 | push @problems, "$bad key(s) not a non-empty string" if $bad; | ||
| 345 | push @problems, "$unknown name(s) neither a model under models: nor default" if $unknown; | ||
| 346 | push @problems, "'default' names both a model and the default engine" if $ambiguous; | ||
| 347 | return $self->_refuse( 'no key changed: '.join( '; ', @problems ) ) if @problems; | ||
| 348 | return $self->_install_runtime( $knarr, $push, 'keys changed' ); | ||
| 349 | } | ||
| 350 | |||
| 351 | sub _admin_delete_config { | ||
| 352 | my ($self, $knarr) = @_; | ||
| 353 | my $boot = $self->_boot_stack; | ||
| 354 | my $stack = $boot->with_config( $boot->config )->build; | ||
| 355 | $self->_install( $knarr, $stack, | ||
| 356 | push => undef, | ||
| 357 | configured => $self->_boot_configured, | ||
| 358 | ); | ||
| 359 | $log->infof( "Admin: delivered setup dropped, generation %d, %s", | ||
| 360 | $self->generation, $self->configured ? 'back to the start setup' : 'no setup' ); | ||
| 361 | return $self->_answer( 200, $self->status ); | ||
| 362 | } | ||
| 363 | |||
| 364 | #### Applying | ||
| 365 | |||
| 366 | # The start layer's data with the push layer over it (see Layers). Nothing | ||
| 367 | # of either is modified. | ||
| 368 | sub _layered { | ||
| 369 | my ($self, $push) = @_; | ||
| 370 | my %data = %{ $self->_boot_stack->config->data }; | ||
| 371 | # remote_config describes how this process started, not the layered setup: | ||
| 372 | # that one is checked like any config that must name its models. | ||
| 373 | $data{remote_config} = 0; | ||
| 374 | for my $key ( sort keys %{ $push || {} } ) { | ||
| 375 | my ( $mine, $theirs ) = ( $data{$key}, $push->{$key} ); | ||
| 376 | if ( ( $key eq 'models' || $key eq 'langfuse' ) | ||
| 377 | && ref $mine eq 'HASH' && ref $theirs eq 'HASH' ) { | ||
| 378 | $data{$key} = { %$mine, %$theirs }; | ||
| 379 | } | ||
| 380 | else { | ||
| 381 | $data{$key} = $theirs; | ||
| 382 | } | ||
| 383 | } | ||
| 384 | return \%data; | ||
| 385 | } | ||
| 386 | |||
| 387 | sub tracing_class { 'Langertha::Knarr::Tracing' } | ||
| 388 | |||
| 389 | # A pushed (or patched) push layer on top of the start layer: validated, | ||
| 390 | # built and installed, or refused with 400 and nothing changed. | ||
| 391 | sub _install_runtime { | ||
| 392 | my ($self, $knarr, $push, $what) = @_; | ||
| 393 | my $config = $self->config_class->new( data => $self->_layered($push) ); | ||
| 394 | |||
| 395 | my @errors = eval { $config->validate }; | ||
| 396 | push @errors, $self->_first_line($@) if $@; | ||
| 397 | push @errors, 'proxy_api_key must differ from the admin key' | ||
| 398 | if !@errors && $config->has_proxy_api_key && $self->is_key( $config->proxy_api_key ); | ||
| 399 | return $self->_refuse( join( '; ', @errors ), $push ) if @errors; | ||
| 400 | |||
| 401 | # A delivered langfuse section brings its own tracing; without one the | ||
| 402 | # start layer's tracing stays. | ||
| 403 | my @over; | ||
| 404 | if ( exists $push->{langfuse} ) { | ||
| 405 | my $tracing = eval { $self->tracing_class->new( config => $config ) }; | ||
| 406 | return $self->_refuse( 'langfuse: '.$self->_first_line($@), $push ) unless $tracing; | ||
| 407 | @over = ( tracing => $tracing->_enabled ? $tracing : undef ); | ||
| 408 | } | ||
| 409 | |||
| 410 | my $stack = $self->_boot_stack->with_config( $config, @over ); | ||
| 411 | @errors = $self->_build_errors($stack); | ||
| 412 | return $self->_refuse( join( '; ', @errors ), $push ) if @errors; | ||
| 413 | |||
| 414 | $self->_install( $knarr, $stack, push => $push, configured => 1 ); | ||
| 415 | $log->infof( "Admin: setup %s, generation %d, %d model(s)%s", $what, | ||
| 416 | $self->generation, scalar keys %{ $config->models }, | ||
| 417 | $config->default_engine ? ' and a default engine' : '' ); | ||
| 418 | return $self->_answer( 200, $self->status ); | ||
| 419 | } | ||
| 420 | |||
| 421 | # Builds the stack and every engine it names now, so a setup that cannot | ||
| 422 | # serve is refused instead of failing on its first request. | ||
| 423 | sub _build_errors { | ||
| 424 | my ($self, $stack) = @_; | ||
| 425 | return 'the setup cannot be built: '.$self->_first_line($@) | ||
| 426 | unless eval { $stack->build; 1 }; | ||
| 427 | my $config = $stack->config; | ||
| 428 | my $router = $stack->router; | ||
| 429 | my @errors; | ||
| 430 | for my $name ( sort keys %{ $config->models } ) { | ||
| 431 | next if eval { $router->resolve( $name, skip_default => 1 ); 1 }; | ||
| 432 | push @errors, "Model '$name': ".$self->_first_line($@); | ||
| 433 | } | ||
| 434 | if ( $config->default_engine ) { | ||
| 435 | push @errors, 'Default: '.$self->_first_line($@) | ||
| 436 | unless eval { $router->resolve(undef); 1 }; | ||
| 437 | } | ||
| 438 | return @errors; | ||
| 439 | } | ||
| 440 | |||
| 441 | # One step, no event loop turn in between: every request after it sees the | ||
| 442 | # new stack, every request before it keeps the old one. | ||
| 443 | sub _install { | ||
| 444 | my ($self, $knarr, $stack, %meta) = @_; | ||
| 445 | $knarr->_apply_stack($stack) if $knarr; | ||
| 446 | $self->_set_stack($stack); | ||
| 447 | $self->_set_configured( $meta{configured} ? 1 : 0 ); | ||
| 448 | $self->_set_push( $meta{push} ); | ||
| 449 | $self->_set_generation( $self->generation + 1 ); | ||
| 450 | $self->_set_applied_at( $self->_now ); | ||
| 451 | return; | ||
| 452 | } | ||
| 453 | |||
| 454 | #### Keys and lockouts | ||
| 455 | |||
| 456 | sub _authorized { | ||
| 457 | my ($self, $req) = @_; | ||
| 458 | return 0 unless $req; | ||
| 459 | my $value = $req->header('Authorization'); | ||
| 460 | return 0 unless defined $value; | ||
| 461 | $value =~ s/\A\s+|\s+\z//g; | ||
| 462 | return 0 unless $value =~ s/\ABearer\s+//i; | ||
| 463 | return $self->is_key($value); | ||
| 464 | } | ||
| 465 | |||
| 466 | sub _locked_for { | ||
| 467 | my ($self, $peer) = @_; | ||
| 468 | my $entry = $self->_failures->{$peer} or return 0; | ||
| 469 | my $wait = ( $entry->{until} // 0 ) - $self->_now; | ||
| 470 | return $wait > 0 ? POSIX::ceil($wait) : 0; | ||
| 471 | } | ||
| 472 | |||
| 473 | sub _record_failure { | ||
| 474 | my ($self, $peer) = @_; | ||
| 475 | my $now = $self->_now; | ||
| 476 | my $table = $self->_failures; | ||
| 477 | $self->_prune_failures($now) if keys %$table >= 10_000; | ||
| 478 | my $entry = $table->{$peer}; | ||
| 479 | $entry = $table->{$peer} = { count => 0, until => 0 } | ||
| 480 | if !$entry || $entry->{last} < $now - 3600; | ||
| 481 | $entry->{count}++; | ||
| 482 | $entry->{last} = $now; | ||
| 483 | my $over = $entry->{count} - $self->free_failures; | ||
| 484 | if ( $over > 0 ) { | ||
| 485 | my $secs = 2 ** ( $over > 20 ? 20 : $over - 1 ); | ||
| 486 | $secs = $self->max_lockout if $secs > $self->max_lockout; | ||
| 487 | $entry->{until} = $now + $secs; | ||
| 488 | } | ||
| 489 | $log->warnf( "Admin: refused a request from %s without the admin key (%d in a row)", | ||
| 490 | $peer, $entry->{count} ); | ||
| 491 | return; | ||
| 492 | } | ||
| 493 | |||
| 494 | # Bounded memory: forget what no longer locks anyone out, and when that is | ||
| 495 | # not enough, everything that does not lock right now. | ||
| 496 | sub _prune_failures { | ||
| 497 | my ($self, $now) = @_; | ||
| 498 | my $table = $self->_failures; | ||
| 499 | for my $peer ( keys %$table ) { | ||
| 500 | my $entry = $table->{$peer}; | ||
| 501 | delete $table->{$peer} if $entry->{until} <= $now && $entry->{last} < $now - 3600; | ||
| 502 | } | ||
| 503 | return if keys %$table < 10_000; | ||
| 504 | delete $table->{$_} for grep { $table->{$_}{until} <= $now } keys %$table; | ||
| 505 | return; | ||
| 506 | } | ||
| 507 | |||
| 508 | #### Answers | ||
| 509 | |||
| 510 | sub _answer { | ||
| 511 | my ($self, $status, $content, $headers) = @_; | ||
| 512 | my $data = ref $content ? $content : { error => { message => $content } }; | ||
| 513 | my @pairs = ( [ 'Cache-Control', 'no-store' ] ); | ||
| 514 | my @extra = @{ $headers || [] }; | ||
| 515 | push @pairs, [ splice @extra, 0, 2 ] while @extra; | ||
| 516 | return ( $status, 'application/json', $self->_json->encode($data), \@pairs ); | ||
| 517 | } | ||
| 518 | |||
| 519 | sub _refuse { | ||
| 520 | my ($self, $message, $doc) = @_; | ||
| 521 | $message = $self->_scrub( $message, $doc ); | ||
| 522 | $log->warnf( "Admin: change refused: %s", $message ); | ||
| 523 | return $self->_answer( 400, $message ); | ||
| 524 | } | ||
| 525 | |||
| 526 | # A parse error of JSON::XS & co. quotes the text around the error -- part | ||
| 527 | # of a key, possibly. Neither the answer nor the log gets it. | ||
| 528 | sub _decode { | ||
| 529 | my ($self, $body) = @_; | ||
| 530 | return ( undef, 'the request body is empty' ) unless defined $body && length $body; | ||
| 531 | my $doc = eval { $self->_json->decode($body) }; | ||
| 532 | return ( undef, 'the request body is not valid JSON' ) if $@ || !defined $doc; | ||
| 533 | return ($doc); | ||
| 534 | } | ||
| 535 | |||
| 536 | sub _doc_or_undef { | ||
| 537 | my ($self, $body) = @_; | ||
| 538 | return unless defined $body && length $body; | ||
| 539 | my $doc = eval { $self->_json->decode($body) }; | ||
| 540 | return $doc; | ||
| 541 | } | ||
| 542 | |||
| 543 | # Every string value of the delivered document, four characters or more, | ||
| 544 | # is taken out of a message -- a key in the wrong place (default: "sk-...") | ||
| 545 | # would otherwise come back in the error that names the place. | ||
| 546 | sub _scrub { | ||
| 547 | my ($self, $text, $doc) = @_; | ||
| 548 | return $text unless defined $doc; | ||
| 549 | my %seen; | ||
| 550 | my @values = sort { length $b <=> length $a } grep { length >= 4 && !$seen{$_}++ } | ||
| 551 | $self->_leaves($doc); | ||
| 552 | $text =~ s/\Q$_\E/[redacted]/g for @values; | ||
| 553 | return $text; | ||
| 554 | } | ||
| 555 | |||
| 556 | sub _leaves { | ||
| 557 | my ($self, $data) = @_; | ||
| 558 | return map { $self->_leaves($_) } values %$data if ref $data eq 'HASH'; | ||
| 559 | return map { $self->_leaves($_) } @$data if ref $data eq 'ARRAY'; | ||
| 560 | return if ref $data || !defined $data; | ||
| 561 | return "$data"; | ||
| 562 | } | ||
| 563 | |||
| 564 | sub _first_line { | ||
| 565 | my ($self, $err) = @_; | ||
| 566 | ( my $text = "$err" ) =~ s/\n.*//s; | ||
| 567 | $text =~ s/\s+at \S+ line \d+\.?\s*\z//; | ||
| 568 | return $text; | ||
| 569 | } | ||
| 570 | |||
| 571 | __PACKAGE__->meta->make_immutable; | ||
| 572 | 1; | ||
| 573 | |||
| 574 | __END__ |