Debian Codegraph @

lemonldap-ng-common/lib/Lemonldap/NG/Common/Conf/RESTServer.pm

raw
1 package Lemonldap::NG::Common::Conf::RESTServer;
2
3 use strict;
4 use JSON 'from_json';
5 use Mouse;
6 use Lemonldap::NG::Common::Conf::Constants;
7 use Lemonldap::NG::Common::Conf::ReConstants;
8
9 our $VERSION = '2.23.0';
10
11 extends 'Lemonldap::NG::Common::Conf::AccessLib';
12
13 #######################
14 # I. PRIVATE METHODS #
15 #######################
16
17 ## @method scalar getConfKey($req, $key)
18 # Return key value
19 #
20 # Return the value of $key key in current configuration. If cfgNum is set to
21 # `latest`, get before last configuration number.
22 #
23 # Errors: set an error in $req->error and return undef if:
24 # * query does not have a cfgNum parameter (set by Common/PSGI/Router.pm)
25 # * cfgNum is not a number
26 #
27 #@param $req Lemonldap::NG::Common::PSGI::Request
28 #@param $key Key name
29 #@return keyvalue (string, int or hashref)
30 sub getConfKey {
31 my ( $self, $req, $key, @args ) = @_;
32 $self->logger->debug("Search for $key in conf");
33
34 # Verify that cfgNum has been asked
35 unless ( defined $req->params('cfgNum') ) {
36 $req->error("Missing configuration number");
37 return undef;
38 }
39 $self->logger->debug( "Cfgnum set to " . $req->params('cfgNum') );
40
41 # when 'latest' => replace by last cfgNum
42 if ( $req->params('cfgNum') eq 'latest' ) {
43 my $tmp = $self->confAcc->lastCfg;
44 $req->set_param( 'cfgNum', $tmp );
45 unless ($tmp) {
46 $req->error($Lemonldap::NG::Common::Conf::msg)
47 if ($Lemonldap::NG::Common::Conf::msg);
48 return undef;
49 }
50 }
51 elsif ( $req->params('cfgNum') !~ /^\d+$/ ) {
52 $req->error("cfgNum must be a number");
53 return undef;
54 }
55 unless (
56 defined $self->getConfByNum( scalar( $req->params('cfgNum') ), @args ) )
57 {
58 $req->error( "Configuration "
59 . $req->params('cfgNum')
60 . " is not available ("
61 . $Lemonldap::NG::Common::Conf::msg
62 . ')' );
63 return undef;
64 }
65
66 # TODO: insert default values
67 # Set an error if key is not defined
68 return $self->currentConf->{$key};
69 }
70
71 sub getConfByNum {
72 my ( $self, $cfgNum, @args ) = @_;
73 unless ( $self->currentConf
74 and %{ $self->currentConf }
75 and $cfgNum == $self->currentConf->{cfgNum} )
76 {
77 my $tmp = $self->confAcc->getConf(
78 { cfgNum => $cfgNum, raw => 1, noCache => 1, @args } );
79 return undef unless ( $tmp and ref($tmp) and %$tmp );
80 $self->currentConf($tmp);
81 }
82 return $cfgNum;
83 }
84
85 ########################
86 # II. Display methods #
87 ########################
88
89 # Values are send depending of the /path/info/. For example,
90 # /confs/1/portal to get portal value.
91
92 # This section contains several methods:
93 # - complex nodes:
94 # * complexNodesRoot() call for root queries (no subkeys) to display the list
95 # * virtualHosts()
96 # * _samlMetaDataNodes() is called by saml(IDP|RP)MetaDataNode
97 # * _oidcMetaDataNodes() is called by oidc(OP|RP)MetaDataNodes
98 # - other special nodes:
99 # * authChoiceModules()
100 # * grantSessionRules()
101 # * openIdIDPList() (old OpenID)
102 # * applicationList()
103 # - root:
104 # root query (/confs/latest for example) is redirected to metadata()
105 # - other requests:
106 # they are managed by getKey()
107 # - newRSAKey() returns a new RSA key pair if /confs/newRSAKey is called in a
108 # POST request
109 # - prx() load a request and return the content (for SAML/OIDC metadata)
110
111 # 31 - Complex subnodes
112 # ----------------
113
114 ## @method PSGI-JSON-response complexNodesRoot($req, $query, $tpl)
115 # Respond to root requests for virtual hosts and SAMLmetadata
116 #
117 #@param $req Lemonldap::NG::Common::PSGI::Request
118 #@param $query Configuration root key
119 #@param $tpl Javascript template to use (see JS/JSON generator script)
120 #@return PSGI JSON response
121 sub complexNodesRoot {
122 my ( $self, $req, $query, $tpl ) = @_;
123 $self->logger->debug("Query for $query template keys");
124
125 my $tmp = $self->getConfKey( $req, $query );
126 return $self->sendError( $req, undef, 400 ) if ( $req->error );
127
128 my @res;
129 if ( ref($tmp) ) {
130 foreach my $f ( sort keys %$tmp ) {
131 push @res,
132 {
133 id => "${tpl}s/$f",
134 title => $f,
135 type => $tpl,
136 template => $tpl
137 };
138 }
139 }
140 return $self->sendJSONresponse( $req, \@res );
141 }
142
143 # 311 - Virtual hosts
144 # -------------
145
146 ## @method PSGI-JSON-response virtualHosts($req, @path)
147 # Respond to virtualhosts sub requests
148 #
149 #@param $req Lemonldap::NG::Common::PSGI::Request
150 #@param @path words in path after `virtualhosts`
151 #@return PSGI JSON response
152 sub virtualHosts {
153 my ( $self, $req, @path ) = @_;
154
155 return $self->complexNodesRoot( $req, 'locationRules', 'virtualHost' )
156 unless (@path);
157
158 my $vh = shift @path;
159 my $query;
160 unless ( $query = shift @path ) {
161 return $self->sendError( $req,
162 'Bad request: virtualHost query must ask for a key', 400 );
163 }
164
165 # Send setDefault for new vhosts
166 return $self->sendJSONresponse( $req, { error => 'setDefault' } )
167 if ( $vh =~ /^new__/ );
168
169 # Reject unknown vhosts
170 return $self->sendError( $req, "Unknown virtualhost ($vh)", 400 )
171 unless ( defined $self->getConfKey( $req, 'locationRules' )->{$vh} );
172
173 if ( $query =~ /^(?:(?:exportedHeader|locationRule)s|post)$/ ) {
174 my ( $id, $resp ) = ( 1, [] );
175 my $vhk = eval { $self->getConfKey( $req, $query )->{$vh} } // {};
176 return $self->sendError( $req, undef, 400 ) if ( $req->error );
177 $self->logger->debug("Query for $vh/$query keys");
178
179 # Keys are ordered except 'default' which must be at the end
180 foreach my $r (
181 sort {
182 $query eq 'locationRules'
183 ? (
184 $a eq 'default'
185 ? 1
186 : ( $b eq 'default' ? -1 : $a cmp $b )
187 )
188 : $a cmp $b
189 } keys %$vhk
190 )
191 {
192 my $res = {
193 id => "virtualHosts/$vh/$query/" . $id++,
194 title => $r,
195 data => $vhk->{$r},
196 type => 'keyText',
197 };
198
199 # If rule contains a comment or an AuthLevel, split them
200 if ( $query eq 'locationRules' ) {
201 $res->{comment} = '';
202 $res->{level} = '';
203 $res->{level} = $1 if ( $r =~ s/\(\?#AuthnLevel=(-?\d+)\)// );
204 if ( $r =~ s/\(\?#(.*?)\)// ) {
205 $res->{title} = $res->{comment} = $1;
206 }
207 $res->{re} = $r;
208 $res->{type} = 'rule';
209 }
210 elsif ( $query eq 'post' ) {
211 $res->{data} = $vhk->{$r};
212 $res->{type} = 'post';
213 }
214 push @$resp, $res;
215 }
216 return $self->sendJSONresponse( $req, $resp );
217 }
218 elsif ( $query =~ qr/^$virtualHostKeys$/o ) {
219 $self->logger->debug("Query for $vh/$query key");
220
221 # TODO: verify how this is done actually
222 my $k1 = $self->getConfKey( $req, 'vhostOptions' );
223 return $self->sendError( $req, undef, 400 ) if ( $req->error );
224
225 # Default values are set by JS
226 my $res = eval { $k1->{$vh}->{$query} } // undef;
227 return $self->sendJSONresponse( $req, { value => $res } );
228 }
229 else {
230 return $self->sendError( $req, "Unknown vhost subkey ($query)", 400 );
231 }
232 }
233
234 # 312 - SAML
235 # ----
236
237 ## @method PSGI-JSON-response _samlMetaDataNode($type, $req, @path)
238 # Respond to SAML metadata subnodes
239 #
240 #@param $type `SP` or `IDP`
241 #@param $req Lemonldap::NG::Common::PSGI::Request
242 #@param @path words in path after `saml{IDP|SP}MetaDataNode`
243 #@return PSGI JSON response
244 sub _samlMetaDataNodes {
245 my ( $self, $type, $req, @path ) = @_;
246
247 return $self->complexNodesRoot( $req, "saml${type}MetaDataXML",
248 "saml${type}MetaDataNode" )
249 unless (@path);
250 my $partner = shift @path;
251 my $query = shift @path;
252 unless ($query) {
253 return $self->sendError( $req,
254 "Bad request: saml${type}MetaDataNode query must ask for a key",
255 400 );
256 }
257
258 # setDefault response for new partners
259 return $self->sendJSONresponse( $req, { error => 'setDefault' } )
260 if ( $partner =~ /^new__/ );
261
262 # Reject unknown partners
263 return $self->sendError( $req, "Unknown SAML partner ($partner)", 400 )
264 unless (
265 defined eval {
266 $self->getConfKey( $req, "saml${type}MetaDataXML" )->{$partner};
267 }
268 );
269
270 my ( $id, $resp ) = ( 1, [] );
271
272 # Return all exported attributes if asked
273 if ( $query =~ /^saml${type}MetaDataExportedAttributes$/ ) {
274 my $pk =
275 eval { $self->getConfKey( $req, $query )->{$partner} } // {};
276 return $self->sendError( $req, undef, 400 ) if ( $req->error );
277 foreach my $h ( sort keys %$pk ) {
278 push @$resp,
279 {
280 id => "saml${type}MetaDataNodes/$partner/$query/" . $id++,
281 title => $h,
282 data => [ split /;/, $pk->{$h} ],
283 type => 'samlAttribute',
284 };
285 }
286 return $self->sendJSONresponse( $req, $resp );
287 }
288 elsif ( $query eq "samlSPMetaDataMacros" ) {
289 my $pk =
290 eval { $self->getConfKey( $req, $query )->{$partner} } // {};
291 return $self->sendError( $req, undef, 400 ) if ( $req->error );
292 foreach my $h ( sort keys %$pk ) {
293 push @$resp,
294 {
295 id => "saml${type}MetaDataNodes/$partner/$query/" . $id++,
296 title => $h,
297 data => $pk->{$h},
298 type => 'keyText',
299 };
300 }
301 return $self->sendJSONresponse( $req, $resp );
302 }
303
304 # Simple root keys
305 elsif ( $query =~ /^saml${type}MetaDataXML$/ ) {
306 my $value =
307 eval { $self->getConfKey( $req, $query )->{$partner}->{$query}; }
308 // undef;
309 return $self->sendError( $req, undef, 400 ) if ( $req->error );
310 return $self->sendJSONresponse( $req, { value => $value } );
311 }
312
313 # Metadata URL
314 elsif ( $query =~ /^saml${type}MetaDataURL$/ ) {
315 my $value =
316 eval { $self->getConfKey( $req, $query )->{$partner}->{$query}; }
317 // undef;
318 return $self->sendError( $req, undef, 400 ) if ( $req->error );
319 return $self->sendJSONresponse( $req, { value => $value } );
320 }
321
322 # These regexps are generated by jsongenerator.pl and stored in
323 # Lemonldap::NG::Common::Conf::ReConstants
324 elsif (
325 $query =~ {
326 IDP => qr/^$samlIDPMetaDataNodeKeys$/o,
327 SP => qr/^$samlSPMetaDataNodeKeys$/o
328 }->{$type}
329 )
330 {
331 my $value = eval {
332 $self->getConfKey( $req, "saml${type}MetaDataOptions" )->{$partner}
333 ->{$query};
334 } // undef;
335
336 # Note that types "samlService" and "samlAssertion" will be splitted by
337 # manager.js in an array
338 return $self->sendJSONresponse( $req, { value => $value } );
339 }
340 else {
341 return $self->sendError( $req,
342 "Bad key for saml${type}MetaDataNode ($query)", 400 );
343 }
344 }
345
346 ## @method PSGI-JSON-response samlIDPMetaDataNode($req, @path)
347 # Launch _samlMetaDataNode('IDP', @_)
348 #
349 #@param $req Lemonldap::NG::Common::PSGI::Request
350 #@param @path words in path after `samlIDPMetaDataNode`
351 #@return PSGI JSON response
352 sub samlIDPMetaDataNodes {
353 my ( $self, $req, @path ) = @_;
354 return $self->_samlMetaDataNodes( 'IDP', $req, @path );
355 }
356
357 ## @method PSGI-JSON-response samlSPMetaDataNode($req, @path)
358 # Launch _samlMetaDataNode('SP', @_)
359 #
360 #@param $req Lemonldap::NG::Common::PSGI::Request
361 #@param @path words in path after `samlSPMetaDataNode`
362 #@return PSGI JSON response
363 sub samlSPMetaDataNodes {
364 my ( $self, $req, @path ) = @_;
365 return $self->_samlMetaDataNodes( 'SP', $req, @path );
366 }
367
368 # 313 - OpenID-Connect
369 # --------------
370
371 ## @method PSGI-JSON-response _oidcMetaDataNodes($type, $req, @path)
372 # Respond to OpenID-Connect metadata subnodes
373 #
374 #@param $type `OP` or `RP`
375 #@param $req Lemonldap::NG::Common::PSGI::Request
376 #@param @path words in path after `oidc{OP|RP}MetaDataNode`
377 #@return PSGI JSON response
378 sub _oidcMetaDataNodes {
379 my ( $self, $type, $req, @path ) = @_;
380
381 my $refKey =
382 ( $type eq 'RP' ? 'oidcRPMetaDataOptions' : 'oidcOPMetaDataJSON' );
383 return $self->complexNodesRoot( $req, $refKey, "oidc${type}MetaDataNode" )
384 unless (@path);
385
386 my $partner = shift @path;
387 my $query = shift @path;
388 unless ($query) {
389 return $self->sendError( $req,
390 "Bad request: oidc${type}MetaDataNode query must ask for a key",
391 400 );
392 }
393
394 # setDefault response for new partners
395 return $self->sendJSONresponse( $req, { error => 'setDefault' } )
396 if ( $partner =~ /^new__/ );
397
398 # Reject unknown partners
399 return $self->sendError( $req,
400 "Unknown OpenID-Connect partner ($partner)", 400 )
401 unless (
402 defined eval { $self->getConfKey( $req, $refKey )->{$partner}; } );
403
404 my ( $id, $resp ) = ( 1, [] );
405
406 # Handle RP Attributes
407 if ( $query eq "oidcRPMetaDataExportedVars" ) {
408 my $pk = eval { $self->getConfKey( $req, $query )->{$partner} } // {};
409 return $self->sendError( $req, undef, 400 ) if ( $req->error );
410 foreach my $h ( sort keys %$pk ) {
411
412 # Set default values for type and array
413 my $data = [ split /;/, $pk->{$h} ];
414 unless ( $data->[1] ) {
415 $data->[1] = "string";
416 }
417 unless ( $data->[2] ) {
418 $data->[2] = "auto";
419 }
420 push @$resp,
421 {
422 id => "oidc${type}MetaDataNodes/$partner/$query/" . $id++,
423 title => $h,
424 data => $data,
425 type => 'oidcAttribute',
426 };
427 }
428 return $self->sendJSONresponse( $req, $resp );
429 }
430
431 # Return all exported attributes if asked
432 elsif ( $query =~
433 /^(?:oidc${type}MetaDataExportedVars|oidcRPMetaDataOptionsExtraClaims|oidcRPMetaDataMacros|oidcRPMetaDataScopeRules)$/
434 )
435 {
436 my $pk = eval { $self->getConfKey( $req, $query )->{$partner} } // {};
437 return $self->sendError( $req, undef, 400 ) if ( $req->error );
438 foreach my $h ( sort keys %$pk ) {
439 push @$resp,
440 {
441 id => "oidc${type}MetaDataNodes/$partner/$query/" . $id++,
442 title => $h,
443 data => $pk->{$h},
444 type => 'keyText',
445 };
446 }
447 return $self->sendJSONresponse( $req, $resp );
448 }
449
450 # Long text types (OP only)
451 elsif ( $query =~ /^oidcOPMetaData(?:JSON|JWKS)$/ ) {
452 my $value =
453 eval { $self->getConfKey( $req, $query )->{$partner}; } // undef;
454 return $self->sendError( $req, undef, 400 ) if ( $req->error );
455 return $self->sendJSONresponse( $req, { value => $value } );
456 }
457
458 # Options
459 elsif (
460 $query =~ {
461 OP => qr/^$oidcOPMetaDataNodeKeys$/o,
462 RP => qr/^$oidcRPMetaDataNodeKeys$/o
463 }->{$type}
464 )
465 {
466 my $value = eval {
467 $self->getConfKey( $req, "oidc${type}MetaDataOptions" )->{$partner}
468 ->{$query};
469 } // undef;
470 return $self->sendJSONresponse( $req, { value => $value } );
471 }
472 else {
473 return $self->sendError( $req,
474 "Bad key for oidc${type}MetaDataNode ($query)", 400 );
475 }
476 }
477
478 ## @method PSGI-JSON-response oidcOPMetaDataNodes($req, @path)
479 # Launch _oidcMetaDataNodes('SP', @_)
480 #
481 #@param $req Lemonldap::NG::Common::PSGI::Request
482 #@param @path words in path after `oidcOPMetaDataNode`
483 #@return PSGI JSON response
484 sub oidcOPMetaDataNodes {
485 my ( $self, $req, @path ) = @_;
486 return $self->_oidcMetaDataNodes( 'OP', $req, @path );
487 }
488
489 ## @method PSGI-JSON-response oidcRPMetaDataNodes($req, @path)
490 # Launch _oidcMetaDataNodes('SP', @_)
491 #
492 #@param $req Lemonldap::NG::Common::PSGI::Request
493 #@param @path words in path after `oidcRPMetaDataNode`
494 #@return PSGI JSON response
495 sub oidcRPMetaDataNodes {
496 my ( $self, $req, @path ) = @_;
497 return $self->_oidcMetaDataNodes( 'RP', $req, @path );
498 }
499
500 # 314 - CAS
501 # ---
502
503 sub _casMetaDataNodes {
504 my ( $self, $type, $req, @path ) = @_;
505 my $refKey =
506 ( $type eq 'App' ? 'casAppMetaDataOptions' : 'casSrvMetaDataOptions' );
507 return $self->complexNodesRoot( $req, $refKey, "cas${type}MetaDataNode" )
508 unless (@path);
509
510 my $partner = shift @path;
511 my $query = shift @path;
512 unless ($query) {
513 return $self->sendError( $req,
514 "Bad request: cas${type}MetaDataNode query must ask for a key",
515 400 );
516 }
517
518 # setDefault response for new partners
519 return $self->sendJSONresponse( $req, { error => 'setDefault' } )
520 if ( $partner =~ /^new__/ );
521
522 # Reject unknown partners
523 return $self->sendError( $req, "Unknown CAS partner ($partner)", 400 )
524 unless (
525 defined eval { $self->getConfKey( $req, $refKey )->{$partner}; } );
526
527 my ( $id, $resp ) = ( 1, [] );
528
529 # Return all exported attributes if asked
530 if ( $query =~
531 /^(?:cas${type}MetaDataExportedVars|casSrvMetaDataOptionsProxiedServices|casAppMetaDataMacros)$/
532 )
533 {
534 my $pk = eval { $self->getConfKey( $req, $query )->{$partner} } // {};
535 return $self->sendError( $req, undef, 400 ) if ( $req->error );
536 foreach my $h ( sort keys %$pk ) {
537 push @$resp,
538 {
539 id => "cas${type}MetaDataNodes/$partner/$query/" . $id++,
540 title => $h,
541 data => $pk->{$h},
542 type => 'keyText',
543 };
544 }
545 return $self->sendJSONresponse( $req, $resp );
546 }
547
548 # Options
549 if (
550 $query =~ {
551 App => qr/^$casAppMetaDataNodeKeys$/o,
552 Srv => qr/^$casSrvMetaDataNodeKeys$/o
553 }->{$type}
554 )
555 {
556 my $value = eval {
557 $self->getConfKey( $req, "cas${type}MetaDataOptions" )->{$partner}
558 ->{$query};
559 } // undef;
560 return $self->sendJSONresponse( $req, { value => $value } );
561 }
562 else {
563 return $self->sendError( $req,
564 "Bad key for cas${type}MetaDataNode ($query)", 400 );
565 }
566 }
567
568 sub casSrvMetaDataNodes {
569 my ( $self, $req, @path ) = @_;
570 return $self->_casMetaDataNodes( 'Srv', $req, @path );
571 }
572
573 sub casAppMetaDataNodes {
574 my ( $self, $req, @path ) = @_;
575 return $self->_casMetaDataNodes( 'App', $req, @path );
576 }
577
578 # 32 - Other special nodes
579 # -------------------
580
581 # 321 - Choice authentication
582
583 ## @method PSGI-JSON-response authChoiceModules($req,$key)
584 # Returns authChoiceModules keys splitted in arrays
585 #
586 #@param $req Lemonldap::NG::Common::PSGI::Request
587 #@param key optional subkey
588 #@return PSGI JSON response
589 sub authChoiceModules {
590 my ( $self, $req, $key ) = @_;
591 my $value = $self->getConfKey( $req, 'authChoiceModules' );
592 unless ($key) {
593 my @res;
594 foreach my $k ( sort keys %$value ) {
595 my $data = [ split /;\s*/, $value->{$k} ];
596 if ( $data->[5] ) {
597 my $over;
598 eval { $over = from_json( $data->[5] ) };
599 if ($@) {
600 $self->logger->error(
601 "Bad value in choice over parameters, deleted ($@)");
602 }
603 else {
604 $data->[5] = [ map { [ $_, $over->{$_} ] } keys %{$over} ];
605 }
606 }
607 push @res,
608 {
609 id => "authChoiceModules/$k",
610 title => "$k",
611 data => $data,
612 type => 'authChoice'
613 };
614 }
615 return $self->sendJSONresponse( $req, \@res );
616 }
617 else {
618 my $r = $value->{$key} ? [ split( /;\s*/, $value->{$key} ) ] : [];
619 return $self->sendJSONresponse( $req, { value => $r } );
620 }
621 }
622
623 # 322 - Rules to grant sessions
624
625 ## @method PSGI-JSON-response grantSessionRules($req)
626 # Split grantSessionRules key=>value into 3 elements
627 #
628 #@param $req Lemonldap::NG::Common::PSGI::Request
629 #@return PSGI JSON response
630 sub grantSessionRules {
631 my ( $self, $req, $key ) = @_;
632 return $self->sendError( $req, 'Subkeys forbidden for grantSessionRules',
633 400 )
634 if ($key);
635 my $value = $self->getConfKey( $req, 'grantSessionRules' );
636 my @res;
637
638 sub _sort {
639 my $A = ( $a =~ /^.*?##(.*)$/ )[0];
640 my $B = ( $b =~ /^.*?##(.*)$/ )[0];
641 return !$A ? 1 : !$B ? -1 : $A cmp $B;
642 }
643 my $id = 0;
644 foreach my $k ( sort _sort keys %$value ) {
645 my $r = $k;
646 my $c = ( $r =~ s/^(.*)?##(.*)$/$1/ ? $2 : '' );
647 $id++;
648 push @res,
649 {
650 id => "grantSessionRules/$id",
651 title => $c || $r,
652 re => $r,
653 comment => $c,
654 data => $value->{$k},
655 type => 'grant'
656 };
657 }
658 return $self->sendJSONresponse( $req, \@res );
659 }
660
661 # 323 - (old)OpenID IDP black/white list
662
663 ##method PSGI-JSON-response openIdIDPList($req)
664 # Split openIdIDPList parameter into 2 elements
665 sub openIdIDPList {
666 my ( $self, $req, $key ) = @_;
667 return $self->sendError( $req, 'Subkeys forbidden for openIdIDPList', 400 )
668 if ($key);
669 my $value = $self->getConfKey( $req, 'openIdIDPList' );
670 $value //= '0;';
671 my ( $type, $v ) = split /;/, $value;
672 $v //= '';
673 return $self->sendJSONresponse( $req, { value => [ $type, $v ] } );
674 }
675
676 # 324 - Application for menu
677 # --------------------
678
679 ## @method PSGI-JSON-response applicationList($req, @other)
680 # Return the full menu tree
681 #
682 #@param $req Lemonldap::NG::Common::PSGI::Request
683 #@param @other words in path after `applicationList`
684 #@return PSGI JSON response
685 sub applicationList {
686 my ( $self, $req, @other ) = @_;
687 return $self->sendError( $req,
688 'There is no subkey for applicationList', 400 )
689 if (@other);
690 my $apps = $self->getConfKey( $req, 'applicationList' );
691 return $self->sendError( $req, undef, 400 ) if ( $req->error );
692 $apps = {} unless ( ref($apps) eq 'HASH' );
693 my $json = $self->_scanCatsAndApps( $apps, 'applicationList' );
694 return $self->sendJSONresponse( $req, $json );
695 }
696
697 ## @method arrayRef _scanCatsAndApps($apps)
698 # Recursive method used to build categories & applications menu
699 #
700 #@param $apps HashRef pointing to a subnode of catAndApps conf tree
701 #@return arrayRef
702 sub _scanCatsAndApps {
703 my ( $self, $apps, $baseId ) = @_;
704 my @res;
705
706 foreach my $cat (
707 sort {
708 ( $apps->{$a}->{order} || 0 ) <=> ( $apps->{$b}->{order} || 0 )
709 or $a cmp $b
710 }
711 grep { not /^(?:catname|type|order)$/ } keys %$apps
712 )
713 {
714 my $item = { id => "$baseId/$cat" };
715 if ( $apps->{$cat}->{type} eq 'category' ) {
716 $item->{title} = $apps->{$cat}->{catname};
717 $item->{type} = 'menuCat';
718 $item->{nodes} =
719 $self->_scanCatsAndApps( $apps->{$cat}, "$baseId/$cat" );
720 }
721 else {
722 $item->{title} = $apps->{$cat}->{options}->{name};
723 $item->{type} = $apps->{$cat}->{type} = 'menuApp';
724 foreach my $o (
725 grep { not /^name$/ }
726 keys %{ $apps->{$cat}->{options} }
727 )
728 {
729 $item->{data}->{$o} = $apps->{$cat}->{options}->{$o};
730 }
731 }
732 push @res, $item;
733 }
734 return \@res;
735 }
736
737 # 325 - Combination modules
738
739 # Returns raw value, just transform "over" key
740 sub combModules {
741 my ( $self, $req, $key ) = @_;
742 return $self->sendError( $req, 'Subkeys forbidden for combModules', 400 )
743 if ($key);
744 my $val = $self->getConfKey( $req, 'combModules' ) // {};
745 my $res = [];
746 foreach my $mod ( keys %$val ) {
747 my $tmp;
748 $tmp->{title} = $mod;
749 $tmp->{id} = "combModules/$mod";
750 $tmp->{type} = 'cmbModule';
751 $tmp->{data}->{$_} = $val->{$mod}->{$_} foreach (qw(type for));
752 my $over = $val->{$mod}->{over} // {};
753 $tmp->{data}->{over} = [ map { [ $_, $over->{$_} ] } keys %$over ];
754 push @$res, $tmp;
755 }
756 return $self->sendJSONresponse( $req, $res );
757 }
758
759 sub sfExtra {
760 my ( $self, $req, $key ) = @_;
761 return $self->sendError( $req, 'Subkeys forbidden for sfExtra', 400 )
762 if ($key);
763 my $val = $self->getConfKey( $req, 'sfExtra' ) // {};
764 my $res = [];
765 foreach my $mod ( keys %$val ) {
766 my $tmp;
767 $tmp->{title} = $mod;
768 $tmp->{id} = "sfExtra/$mod";
769 $tmp->{type} = 'sfExtra';
770 $tmp->{data}->{$_} = $val->{$mod}->{$_}
771 foreach (qw(type rule regrule logo level label));
772 $tmp->{data}->{register} = $val->{$mod}->{register} ? \1 : \0;
773 my $over = $val->{$mod}->{over} // {};
774 $tmp->{data}->{over} = [ map { [ $_, $over->{$_} ] } keys %$over ];
775 push @$res, $tmp;
776 }
777 return $self->sendJSONresponse( $req, $res );
778 }
779
780 ## Keys
781 sub keyNodes {
782 my ( $self, $req, @path ) = @_;
783 {
784 local $" = ",";
785 $self->logger->debug("Keynode @path");
786 }
787
788 return $self->complexNodesRoot( $req, "keys", "keyNode" ) unless (@path);
789
790 my $keyId = shift @path;
791 my $query = shift @path;
792
793 unless ($query) {
794 return $self->sendError( $req,
795 "Bad request: keyNodes query must ask for a key", 400 );
796 }
797
798 # setDefault response for new keyIds
799 return $self->sendError( $req, 'setDefault', 200 )
800 if ( $keyId =~ /^new__/ );
801
802 # Reject unknown keyIds
803 return $self->sendError( $req, "Unknown key ID ($keyId)", 400 )
804 unless ( defined eval { $self->getConfKey( $req, 'keys' )->{$keyId}; } );
805
806 my ( $id, $resp ) = ( 1, [] );
807
808 my $value =
809 eval { $self->getConfKey( $req, "keys" )->{$keyId}->{$query}; } // undef;
810 return $self->sendJSONresponse( $req, { value => $value } );
811 }
812
813 # 33 - Root queries
814 # -----------
815
816 ## @method PSGI-JSON-response metadata($req)
817 # Respond to `/conf/:cfgNum` requests by sending configuration metadata
818 #
819 # NB: if `full=1` is set in the query, configuration is returned directly in
820 # JSON
821 #
822 #@param $req Lemonldap::NG::Common::PSGI::Request
823 #@return PSGI JSON response
824 sub metadata {
825 my ( $self, $req ) = @_;
826 if ( $req->params('full') and $req->params('full') !~ NO ) {
827 my $c = $self->getConfKey( $req, 'cfgNum' );
828 return $self->sendError( $req, undef, 400 ) if ( $req->error );
829 if ( my $userid = $self->_userId($req) ) {
830 $self->auditLog(
831 $req,
832 message => (
833 'User ' . $userid . ' ask for full configuration ' . $c
834 ),
835 code => "CONFIG_DOWNLOADED",
836 user => $userid,
837 cfgNum => $c
838 );
839 }
840 else {
841 $self->auditLog(
842 $req,
843 message => "REST request to get full configuration $c",
844 code => "CONFIG_DOWNLOADED",
845 cfgNum => $c
846 );
847 }
848 return $self->sendJSONresponse(
849 $req,
850 $self->currentConf,
851 pretty => 1,
852 headers => [
853 'Content-Disposition' => "Attachment; filename=lmConf-$c.json"
854 ],
855 );
856 }
857 elsif ( my $oidc = $req->params('oidcMetadata')
858 or $req->params('samlMetadata') )
859 {
860 my $c = $self->getConfKey( $req, 'cfgNum' );
861 my $type = $oidc ? 'OIDC' : 'SAML';
862 return $self->sendError( $req, undef, 400 ) if ( $req->error );
863 if ( $self->can('userId') ) {
864 $self->userLogger->notice( 'User '
865 . $self->userId($req)
866 . " ask for $type metadata "
867 . $c );
868 }
869 else {
870 $self->logger->info("REST request to get $type metadata $c");
871 }
872 if ($oidc) {
873 require Lemonldap::NG::Common::OpenIDConnect::Metadata;
874 my $path = $self->currentConf->{issuerDBOpenIDConnectPath};
875 $path =~ s#^.*?(\w+).*?$#$1/#;
876 return $self->sendJSONresponse(
877 $req,
878 Lemonldap::NG::Common::OpenIDConnect::Metadata->metadataDoc(
879 $self->currentConf->{oidcServiceMetaDataIssuer}
880 || $self->p->portal,
881 $self->currentConf,
882 $path,
883 ),
884 pretty => 1,
885 headers => [
886 'content-Type' => 'application/json',
887 'Content-Disposition' =>
888 "Attachment; filename=openid-configuration.json"
889 ],
890 );
891 }
892 else {
893 require Lemonldap::NG::Common::Conf::SAML::Metadata;
894 if ( my $metadata =
895 Lemonldap::NG::Common::Conf::SAML::Metadata->new() )
896 {
897 my $s =
898 $metadata->serviceToXML(
899 { %{ $self->currentConf }, portal => $self->p->portal },
900 'all' );
901 return $self->p->sendTextResponse( $req, $s,
902 type => "application/xml; charset=utf-8" );
903 }
904 return $self->p->sendError( $req, 'Unable to build Metadata', 500 );
905 }
906 }
907 else {
908 my $res = {};
909 $res->{cfgNum} = $self->getConfKey( $req, 'cfgNum' );
910 return $self->sendError( $req, undef, 400 ) if ( $req->error );
911 return $self->sendError( $req, "Configuration without cfgNum", 500 )
912 unless ( defined $res->{cfgNum} );
913 foreach my $key (qw(cfgAuthor cfgDate cfgAuthorIP cfgLog cfgVersion)) {
914 $res->{$key} = $self->getConfKey( $req, $key );
915 }
916
917 # Find next and previous conf
918 my @a = $self->confAcc->available;
919 my $id = -1;
920 my ($ind) = map { $id++; $_ == $res->{cfgNum} ? ($id) : () } @a;
921 if ($ind) {
922 my $prevNum = $a[ $ind - 1 ];
923 my $prevConf =
924 $self->confAcc->getConf(
925 { cfgNum => $prevNum, raw => 1, noCache => 1 } );
926 $res->{prev} = {
927 cfgNum => $prevNum,
928 cfgLog => $prevConf->{cfgLog}
929 };
930 }
931 if ( defined $ind and $ind < $#a ) {
932 my $nextNum = $a[ $ind + 1 ];
933 my $nextConf =
934 $self->confAcc->getConf(
935 { cfgNum => $nextNum, raw => 1, noCache => 1 } );
936 $res->{next} = {
937 cfgNum => $nextNum,
938 cfgLog => $nextConf->{cfgLog}
939 };
940 }
941 if ( my $userid = $self->_userId($req) ) {
942 $self->auditLog(
943 $req,
944 code => "CONFIG_GET_METADATA",
945 user => $userid,
946 cfgNum => $res->{cfgNum},
947 message => (
948 'User '
949 . $userid
950 . ' ask for configuration metadata ('
951 . $res->{cfgNum} . ')'
952 )
953 );
954 }
955 else {
956 $self->auditLog(
957 $req,
958 code => "CONFIG_GET_METADATA",
959 cfgNum => $res->{cfgNum},
960 message =>
961 "REST request to get configuration metadata ($res->{cfgNum})",
962 );
963 }
964 return $self->sendJSONresponse( $req, $res );
965 }
966 }
967
968 # 34 - Other values
969 # ------------
970
971 ## @method PSGI-JSON-response getKey($req, $key, $subkey)
972 # Return the value of a root key of current configuration
973 #
974 #@param $req Lemonldap::NG::Common::PSGI::Request
975 #@param $key Name of key requested
976 #@param $subkey Subkey for hash values
977 #@return PSGI JSON response
978 sub getKey {
979 my ( $self, $req, $key, $subkey ) = @_;
980 unless ($key) {
981 return $self->metadata($req);
982 }
983 if ( my $userid = $self->_userId($req) ) {
984 $self->auditLog(
985 $req,
986 code => "CONFIG_GET_KEY",
987 message => ( 'User ' . $userid . " asks for key $key" ),
988 user => $userid,
989 key => $key,
990 );
991 }
992 else {
993 $self->auditLog(
994 $req,
995 code => "CONFIG_GET_KEY",
996 message => ("REST request to get configuration key $key"),
997 key => $key,
998 );
999 }
1000 my $value = $self->getConfKey( $req, $key );
1001 return $self->sendError( $req, undef, 400 ) if ( $req->error );
1002
1003 # When "hash"
1004 if ( $key =~ qr/^$simpleHashKeys$/o ) {
1005 return $self->sendJSONresponse( $req, { error => 'setDefault' } )
1006 unless defined($value);
1007
1008 # If a hash key is asked return its value
1009 if ($subkey) {
1010 return $self->sendJSONresponse( $req,
1011 { value => $value->{$subkey} // undef, } );
1012 }
1013
1014 # else return the list of keys
1015 my @res;
1016 foreach my $k ( sort keys %$value ) {
1017 push @res,
1018 {
1019 id => "$key/$k",
1020 title => "$k",
1021 data => $value->{$k},
1022 type => 'keyText'
1023 };
1024 }
1025 return $self->sendJSONresponse( $req, \@res );
1026 }
1027 elsif ( $key =~ qr/^$doubleHashKeys$/o ) {
1028 my @res;
1029 $value ||= {};
1030 foreach my $host ( sort keys %$value ) {
1031 my @tmp;
1032 foreach my $k ( sort keys %{ $value->{$host} } ) {
1033 push @tmp, { k => $k, v => $value->{$host}->{$k} };
1034 }
1035 push @res, { k => $host, h => \@tmp };
1036 }
1037 return $self->sendJSONresponse( $req, { value => \@res } );
1038 }
1039
1040 # When scalar
1041 return $self->sendError( $req, "Key $key is not a hash", 400 )
1042 if ($subkey);
1043 return $self->sendJSONresponse( $req, { error => 'setDefault' } )
1044 unless defined($value);
1045 return $self->sendJSONresponse( $req, { value => $value } );
1046
1047 # TODO authParam key
1048 }
1049
1050 sub _userId {
1051 my ( $self, $req ) = @_;
1052 if ( $self->can('p') and $self->p->can('userId') ) {
1053 return $self->p->userId($req);
1054 }
1055 return;
1056 }
1057
1058 1;