blib/lib/App/Netdisco/Web/AuthN.pm untested

filter: Statementstmt 0.0% 0 / 151 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 100 MC/DCmcdc 0.0% 0 / 57 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 398 CC 5 SCAR 23.3
CC
5
Cov
0%
_get_delegated_authn_user
30.0
safe_return_url
2.0
_api_unauthorized
2.0
CRAP 10.2
1 package App::Netdisco::Web::AuthN;
2  
3 use Dancer ':syntax';
4 use Dancer::Plugin::DBIC;
5 use Dancer::Plugin::Auth::Extensible;
6 use Dancer::Plugin::Swagger;
7  
8 use App::Netdisco; # a safe noop but needed for standalone testing
9 use App::Netdisco::Util::Token 'random_token';
10 use App::Netdisco::Util::Web 'request_is_api';
11 use MIME::Base64;
12 use Try::Tiny;
13 use URI::Based;
14  
15 # path_query drops a scheme and host, but leaves a leading "//" intact, and a
16 # browser reads that as a host rather than a path.
17 sub safe_return_url {
18 my $back = (scalar URI::Based->new(shift)->path_query) || '/';
19 $back =~ s{^/+}{/};
20 return $back;
21 }
22  
23 # ensure that regardless of where the user is redirected, we have a link
24 # back to the page they requested. The login page is excluded along with the
25 # front page: it is the one path a user leaves by using it, so returning them
26 # to it after a successful login is never what they wanted.
27 hook 'before' => sub {
28 params->{return_url} ||= ((request->path ne uri_for('/')->path
29 and request->path ne uri_for('/login')->path)
30 ? request->uri : uri_for(setting('web_home'))->path);
31 };
32  
33 # try to find a valid username according to headers
34 # or configuration settings
35 sub _get_delegated_authn_user {
36 my $username = undef;
37  
38 if (setting('trust_x_remote_user')
39 and scalar request->header('X-REMOTE_USER')
40 and length scalar request->header('X-REMOTE_USER')) {
41  
42 ($username = scalar request->header('X-REMOTE_USER')) =~ s/@[^@]*$//;
43 }
44 elsif (setting('trust_remote_user')
45 and defined $ENV{REMOTE_USER}
46 and length $ENV{REMOTE_USER}) {
47  
48 ($username = $ENV{REMOTE_USER}) =~ s/@[^@]*$//;
49 }
50 # this works for API calls, too
51 elsif (setting('no_auth')) {
52 $username = 'guest';
53 }
54  
55 return unless $username;
56  
57 # from the internals of Dancer::Plugin::Auth::Extensible
58 my $provider = Dancer::Plugin::Auth::Extensible::auth_provider('users');
59  
60 # may synthesize a user if validate_remote_user=false
61 return $provider->get_user_details($username);
62 }
63  
64 # send_error from inside a before hook sets the status, but its body never
65 # reaches the client, so an API client refused there got an empty 401 and no
66 # reason. halt carries the body through.
67 sub _api_unauthorized {
68 my $error = shift;
69 status 401;
70 content_type 'application/json';
71 return halt(to_json { error => $error, return_url => param('return_url') });
72 }
73  
74 # Dancer will create a session if it sees its own cookie. For the API and also
75 # various auto login options we need to bootstrap the session instead. If no
76 # auth data passed, then the hook simply returns, no session is set, and the
77 # user is redirected to login page.
78 hook 'before' => sub {
79 my $theme_by_name = qr{\A\Q@{[ uri_for('/theme/')->path ]}\E[A-Za-z0-9_-]+\.css\z};
80  
81 # return if request is for endpoints not requiring a session
82 return if (
83 request->path eq uri_for('/login')->path
84 or request->path eq uri_for('/logout')->path
85 or request->path eq uri_for('/swagger.json')->path
86 or request->path eq uri_for('/theme.css')->path
87 or request->path =~ $theme_by_name
88 or index(request->path, uri_for('/swagger-ui')->path) == 0
89 or (setting('health_path') and request->path eq uri_for(setting('health_path'))->path)
90 or (setting('metrics_path') and request->path eq uri_for(setting('metrics_path'))->path)
91 );
92  
93 # Dancer will issue a cookie to the client which could be returned and
94 # cause API calls to succeed without passing token. Kill the session.
95 session->destroy if request_is_api;
96  
97 # ...otherwise, we can short circuit if Dancer reads its cookie OK
98 return if session('logged_in_user');
99  
100 my $delegated = _get_delegated_authn_user();
101  
102 # this ordering allows override of delegated authN if given creds
103  
104 # protect against delegated authN config but no valid user
105 if ((not $delegated) and
106 (setting('trust_x_remote_user') or setting('trust_remote_user'))) {
107 session->destroy;
108 request->path_info('/');
109 }
110 # API calls must conform strictly to path and header requirements
111 elsif (request_is_api and request->header('Authorization')) {
112 # from the internals of Dancer::Plugin::Auth::Extensible
113 my $provider = Dancer::Plugin::Auth::Extensible::auth_provider('users');
114  
115 my $token = request->header('Authorization');
116 my $user = $provider->validate_api_token($token)
117 or return _api_unauthorized('invalid or expired token');
118  
119 session(logged_in_user => $user->username);
120 session(logged_in_user_realm => 'users');
121 }
122 elsif ($delegated) {
123 session(logged_in_user => $delegated->username);
124 session(logged_in_user_realm => 'users');
125 }
126 else {
127 # An API request with no credentials is answered here. The handler for
128 # '/' tells the API apart by the Accept header alone, so a client that
129 # sent none got the login page as HTML, with a 200 and a JSON
130 # Content-Type, and took that for success.
131 return _api_unauthorized('not authorized') if request_is_api;
132  
133 # user has no AuthN - force to handler for '/'
134 request->path_info('/');
135 }
136 };
137  
138 # override default login_handler so we can log access in the database
139 swagger_path {
140 description => 'Obtain an API Key',
141 tags => ['General'],
142 path => (setting('url_base') ? setting('url_base')->with('/login')->path : '/login'),
143 parameters => [],
144 responses => { default => { examples => {
145 'application/json' => { api_key => 'cc9d5c02d8898e5728b7d7a0339c0785' } } },
146 },
147 },
148 post '/login' => sub {
149 my $api = ((request->accept and request->accept =~ m/(?:json|javascript)/) ? true : false);
150  
151 # from the internals of Dancer::Plugin::Auth::Extensible
152 my $provider = Dancer::Plugin::Auth::Extensible::auth_provider('users');
153  
154 # get authN data from BasicAuth header used by API, put into params
155 my $authheader = request->header('Authorization');
156 if (defined $authheader and $authheader =~ /^Basic (.*)$/i) {
157 my ($u, $p) = split(m/:/, (MIME::Base64::decode($1) || ":"));
158 params->{username} = $u;
159 params->{password} = $p;
160 }
161  
162 # validate authN
163 my ($success, $realm) = authenticate_user(param('username'),param('password'));
164  
165 # or try to get user from somewhere else
166 my $delegated = _get_delegated_authn_user();
167  
168 if (($success and not
169 # protect against delegated authN config but no valid user (then must ignore params)
170 (not $delegated and (setting('trust_x_remote_user') or setting('trust_remote_user'))))
171 or $delegated) {
172  
173 # this ordering allows override of delegated user if given creds
174 my $user = ($success ? $provider->get_user_details(param('username'))
175 : $delegated);
176  
177 session logged_in_user => $user->username;
178 session logged_in_fullname => ($user->fullname || '');
179 session logged_in_user_realm => ($realm || 'users');
180  
181 schema('netdisco')->resultset('UserLog')->create({
182 username => session('logged_in_user'),
183 userip => request->remote_address,
184 event => (sprintf 'Login (%s)', ($api ? 'API' : 'WebUI')),
185 details => param('return_url'),
186 });
187 $user->update({ last_on => \'LOCALTIMESTAMP' });
188  
189 if ($api) {
190 header('Content-Type' => 'application/json');
191  
192 my $body = try { from_json(request->body) } catch { {} };
193 my $want_permanent = $body->{permanent} && setting('allow_permanent_tokens');
194 my $token_acl = $body->{token_acl};
195  
196 $user->update({
197 token_from => time,
198 token_no_expire => ($want_permanent ? \"true" : \"false"),
199 ($token_acl ? (token_acl => $token_acl) : ()),
200 ($provider->validate_api_token($user->token)
201 ? () : (token => random_token())),
202 })->discard_changes();
203  
204 return to_json {
205 api_key => $user->token,
206 permanent => ($user->token_no_expire ? \1 : \0),
207 ($user->token_acl
208 ? (token_acl => $user->token_acl) : ()),
209 };
210 }
211  
212 redirect safe_return_url(param('return_url'));
213 }
214 else {
215 # invalidate session cookie
216 session->destroy;
217  
218 schema('netdisco')->resultset('UserLog')->create({
219 username => param('username'),
220 userip => request->remote_address,
221 event => (sprintf 'Login Failure (%s)', ($api ? 'API' : 'WebUI')),
222 details => param('return_url'),
223 });
224  
225 if ($api) {
226 header('Content-Type' => 'application/json');
227 status('unauthorized');
228 return to_json { error => 'authentication failed' };
229 }
230  
231 vars->{login_failed}++;
232 forward uri_for('/login'),
233 { login_failed => 1, return_url => param('return_url') },
234 { method => 'GET' };
235 }
236 };
237  
238 # ugh, *puke*, but D::P::Swagger has no way to set this with swagger_path
239 # must be after the path is declared, above.
240 Dancer::Plugin::Swagger->instance->doc
241 ->{paths}->{ (setting('url_base') ? setting('url_base')->with('/login')->path : '/login') }
242 ->{post}->{security}->[0]->{BasicAuth} = [];
243  
244 # we override the default login_handler, so logout has to be handled as well
245 swagger_path {
246 description => 'Destroy user API Key and session cookie',
247 tags => ['General'],
248 path => (setting('url_base') ? setting('url_base')->with('/logout')->path : '/logout'),
249 parameters => [],
250 responses => { default => { examples => { 'application/json' => {} } } },
251 },
252 get '/logout' => sub {
253 my $api = ((request->accept and request->accept =~ m/(?:json|javascript)/) ? true : false);
254  
255 # clear out API token
256 my $user = schema('netdisco')->resultset('User')
257 ->find({ username => session('logged_in_user')});
258 $user->update({token => undef, token_from => undef})->discard_changes()
259 if $user and $user->in_storage;
260  
261 # invalidate session cookie
262 session->destroy;
263  
264 schema('netdisco')->resultset('UserLog')->create({
265 username => session('logged_in_user'),
266 userip => request->remote_address,
267 event => (sprintf 'Logout (%s)', ($api ? 'API' : 'WebUI')),
268 details => '',
269 });
270  
271 if ($api) {
272 header('Content-Type' => 'application/json');
273 return to_json {};
274 }
275  
276 redirect uri_for(setting('web_home'))->path;
277 };
278  
279 # require_role answers a valid token that lacks the role with a 302 to the
280 # denied page. An API client cannot tell that from a broken token or a moved
281 # endpoint, and one that follows it gets an answer from a page it never asked
282 # for while the request it made did nothing. The token was fine and the role
283 # was missing, which is what 403 means, so answer that before the plugin
284 # redirects. An invalid token is still 401, from the before hook above.
285 hook permission_denied => sub {
286 send_error('insufficient role for this endpoint', 403) if request_is_api;
287 };
288  
289 # user redirected here when require_role does not succeed
290 any qr{^/(?:login(?:/denied)?)?} => sub {
291 my $api = ((request->accept and request->accept =~ m/(?:json|javascript)/) ? true : false);
292  
293 if ($api) {
294 header('Content-Type' => 'application/json');
295 status('unauthorized');
296 return to_json {
297 error => 'not authorized',
298 return_url => param('return_url'),
299 };
300 }
301 elsif (request->header('HX-Request')) {
302 # htmx sends HX-Request and not X-Requested-With, so without this branch
303 # an expired session answers a pane with the whole login page and 200,
304 # and htmx swaps that into the pane. HX-Redirect takes the browser to
305 # the login page instead.
306 #
307 # The return_url the before hook computed is the pane's own path, which
308 # is a fragment and not somewhere to send a reader after login. htmx
309 # carries the address bar in HX-Current-URL, which is where they were.
310 my $back = request->header('HX-Current-URL') || param('return_url');
311 header('HX-Redirect' =>
312 uri_for('/login', { return_url => $back })->path_query);
313 status('unauthorized');
314 return '';
315 }
316 elsif (defined request->header('X-Requested-With')
317 and request->header('X-Requested-With') eq 'XMLHttpRequest') {
318 status('unauthorized');
319 return '<div class="col-md-2 alert alert-danger"><i class="fas fa-ban"></i> Error: unauthorized.</div>';
320 }
321 else {
322 template 'index', {
323 return_url => param('return_url')
324 }, { layout => 'main' };
325 }
326 };
327  
328 true;