blib/lib/Lemonldap/NG/Portal/Plugins/SOAPServer.pm untested

filter: Statementstmt 0.0% 0 / 231 Branchbran 0.0% 0 / 62 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 364 CC 29 SCAR 28.8
CC
29
Cov
0%
isAuthorizedURI
42.0
init
30.0
getCookies
30.0
CRAP 17.8
1 # Session server plugin for SOAP call
2 #
3 # This plugin adds the following entry points:
4 # * POST /sessions , methods: getCookies getAttributes isAuthorizedURI
5 # * POST /adminSessions, methods: getAttributes setAttributes isAuthorizedURI
6 # newSession deleteSession getCipheredToken
7 # get_key_from_all_sessions
8 # * POST /config , methods: getConfig lastCfg
9 #
10 # There is no conflict with REST server, they can be used together
11  
12 package Lemonldap::NG::Portal::Plugins::SOAPServer;
13  
14 use strict;
15 use Mouse;
16 use Lemonldap::NG::Portal::Main::Constants qw(
17 PE_OK
18 PE_FORMEMPTY
19 URIRE
20 );
21  
22 our $VERSION = '2.23.0';
23  
24 extends qw(
25 Lemonldap::NG::Portal::Main::Plugin
26 Lemonldap::NG::Common::Conf::AccessLib
27 );
28  
29 has server => ( is => 'rw' );
30 has configStorage => (
31 is => 'ro',
32 lazy => 1,
33 default => sub {
34 $_[0]->{p}->HANDLER->localConfig->{configStorage};
35 }
36 );
37 has exportedAttr => (
38 is => 'rw',
39 lazy => 1,
40 default => sub {
41 my $conf = $_[0]->{conf};
42 if ( $conf->{exportedAttr} and $conf->{exportedAttr} !~ /^\s*\+/ ) {
43 return [ split /\s+/, $conf->{exportedAttr} ];
44 }
45 else {
46 my @attributes = (
47 'authenticationLevel', 'groups',
48 'ipAddr', '_startTime',
49 '_utime', '_lastSeen',
50 '_session_id', '_session_kind',
51 );
52 if ( my $exportedAttr = $conf->{exportedAttr} ) {
53 $exportedAttr =~ s/^\s*\+\s+//;
54 @attributes = ( @attributes, split( /\s+/, $exportedAttr ) );
55  
56 # Convert @attributes into hash to remove duplicates
57 my %attributes = map( { $_ => 1 } @attributes );
58 return '[' . join( ',', keys %attributes ) . ']';
59 }
60  
61 # Convert @attributes into hash to remove duplicates
62 my %attributes = map( { $_ => 1 } @attributes );
63 %attributes = (
64 %attributes,
65 %{ $conf->{exportedVars} },
66 %{ $conf->{macros} },
67 );
68  
69 return [ sort keys %attributes ];
70 }
71 }
72 );
73  
74 ########
75 # WSDL #
76 ########
77  
78 has wsdl => (
79 is => 'ro',
80 lazy => 1,
81 default => sub {
82 my ($self) = @_;
83 my @cookies = ( $self->conf->{cookieName} );
84 push @cookies, $self->conf->{cookieName} . 'http'
85 if ( $self->conf->{securedCookie} >= 2 );
86 my $cookieList = join "\n",
87 map { "<element name='$_' type='xsd:string'></element>" } @cookies;
88  
89 my $attrList = join "\n", map {
90 "<element name='$_' type='xsd:string' nillable='true'></element>"
91 } @{ $self->exportedAttr };
92 my $resp = join( '', <DATA> );
93 close DATA;
94 $resp =~ s/\$cookieList/$cookieList/g;
95 $resp =~ s/\$attrList/$attrList/g;
96 $resp =~ s/\$portal/$self->p->buildUrl/ge;
97 return $resp;
98 }
99 );
100  
101 # INITIALIZATION
102  
103 sub init {
104 my ($self) = @_;
105 eval {
106 require Lemonldap::NG::Common::PSGI::SOAPServer;
107 require Lemonldap::NG::Common::PSGI::SOAPService;
108 };
109 if ($@) {
110 $self->error($@);
111 return 0;
112 }
113 $self->server( Lemonldap::NG::Common::PSGI::SOAPServer->new );
114 if ( $self->conf->{soapSessionServer} ) {
115 $self->addUnauthRoute(
116 sessions => { '*' => 'unauthSessions' },
117 ['POST']
118 )
119  
120 ->addUnauthRoute(
121 adminSessions => 'unauthAdminSessions',
122 ['POST']
123 )
124  
125 ->addAuthRoute(
126 sessions => { '*' => 'badSoapRequest' },
127 ['POST']
128 )
129  
130 ->addAuthRoute(
131 adminSessions => { '*' => 'badSoapRequest' },
132 ['POST']
133 );
134 }
135 if ( $self->conf->{soapConfigServer} ) {
136 $self->addUnauthRoute( config => { '*' => 'config' }, ['POST'] )
137 ->addAuthRoute( config => { '*' => 'badSoapRequest' }, ['POST'] );
138 }
139 if ( $self->conf->{wsdlServer} ) {
140 $self->addUnauthRoute( 'portal.wsdl' => 'getWsdl', ['GET'] )
141 ->addAuthRoute( 'portal.wsdl' => 'getWsdl', ['GET'] );
142 }
143  
144 return 1;
145 }
146  
147 # SOAP DISPATCHERS
148 sub unauthSessions {
149 my ( $self, $req ) = @_;
150 return $self->dispatch_to( $req,
151 qw(error getCookies getAttributes isAuthorizedURI getMenuApplications)
152 );
153 }
154  
155 sub unauthAdminSessions {
156 my ( $self, $req ) = @_;
157 return $self->dispatch_to(
158 $req,
159 qw(getCookies getAttributes isAuthorizedURI getMenuApplications
160 newSession setAttributes deleteSession getCipheredToken
161 get_key_from_all_sessions)
162 );
163 }
164  
165 sub config {
166 my ( $self, $req ) = @_;
167 return $self->dispatch_to( $req, qw(getConfig lastCfg) );
168 }
169  
170 sub badSoapRequest {
171 my ( $self, $req ) = @_;
172 return $self->p->sendError( $req, 'Bad request', 400 );
173 }
174  
175 # Private dispatcher
176 sub dispatch_to {
177 my ( $self, $req, @functions ) = @_;
178 unless ( $req->env->{HTTP_SOAPACTION} ) {
179 return $self->p->sendError( $req, 'SOAP requests only', 400 );
180 }
181 return $self->server->dispatch_to(
182 Lemonldap::NG::Common::PSGI::SOAPService->new(
183 $self, $req, @functions
184 )
185 )->handle($req);
186 }
187  
188 # RESPONSE METHODS
189  
190 # Called in SOAP context, returns cookies in an array.
191 # This subroutine works only for portals working with user and password
192  
193 sub getWsdl {
194 my ( $self, $req ) = @_;
195 return $self->p->sendTextResponse( $req, $self->wsdl,
196 type => 'application/wsdl+xml' );
197 }
198  
199 sub error {
200 my ( $self, $no, $lang ) = @_;
201 return "Error $no";
202 }
203  
204 =begin WSDL
205  
206 _IN user $string User name
207 _IN password $string Password
208 _RETURN $getCookiesResponse Response
209  
210 =end WSDL
211  
212 =cut
213  
214 sub getCookies {
215 my ( $self, $req, $user, $password, $sessionid ) = @_;
216 $self->logger->debug("SOAP authentication request for $user");
217  
218 $req->{user} = $user;
219 $req->data->{password} = $password;
220 if ($sessionid) {
221 $req->{id} = $sessionid;
222 $req->{force} = 1;
223 }
224  
225 $req->{error} = PE_OK;
226  
227 # User and password are required
228 unless ( $req->{user} && $req->data->{password} ) {
229 $req->{error} = PE_FORMEMPTY;
230 }
231  
232 # Launch process
233 else {
234 $req->steps( [
235 qw(getUser authenticate setAuthSessionInfo),
236 @{ $self->p->betweenAuthAndData },
237 $self->p->sessionData,
238 @{ $self->p->afterData },
239 $self->p->validSession,
240 @{ $self->p->endAuth },
241 ]
242 );
243 $req->{error} = $self->p->process($req);
244 $self->logger->debug(
245 "SOAP authentication result for $user: code $req->{error}");
246 $self->p->updateSession($req);
247 }
248 my @tmp = ();
249 push @tmp, SOAP::Data->name( errorCode => $req->{error} );
250 my @cookies = ();
251 unless ( $req->{error} ) {
252 for ( my $i = 0 ; $i < @{ $req->respHeaders } ; $i += 2 ) {
253 if ( $req->respHeaders->[$i] eq 'Set-Cookie' ) {
254 my ( $k, $v ) =
255 ( $req->respHeaders->[ $i + 1 ] =~ /^(\w+)\s*=\s*([^;]*)/ );
256 push @cookies, SOAP::Data->name( $k, $v )->type("string");
257 }
258 }
259 }
260 push @tmp, SOAP::Data->name( cookies => \SOAP::Data->value(@cookies) );
261 my $res = SOAP::Data->name( session => \SOAP::Data->value(@tmp) );
262  
263 #TODO: updateStatus
264 #$self->p->updateStatus($req);
265 return $res;
266 }
267  
268 # Return attributes of the session identified by $id.
269 # @param $id Cookie value
270  
271 =begin WSDL
272  
273 _IN id $string Cookie value
274 _RETURN $getAttributesResponse Response
275  
276 =end WSDL
277  
278 =cut
279  
280 sub getAttributes {
281 my ( $self, $req, $id ) = @_;
282 die 'id is required' unless ($id);
283  
284 my $session =
285 $self->p->getApacheSession( $id, kind => '', hashStore => 0, );
286  
287 my @tmp = ();
288 unless ($session) {
289 $self->userLogger->notice(
290 "SOAP attributes request: session $id not found");
291 push @tmp, SOAP::Data->name( error => 1 )->type('int');
292 }
293 else {
294 my $wtt = $session->data->{ $self->conf->{whatToTrace} };
295 $self->userLogger->info(
296 "SOAP attributes request for " . ( $wtt ? $wtt : $id ) );
297 push @tmp, SOAP::Data->name( error => 0 )->type('int');
298 push @tmp,
299 SOAP::Data->name(
300 attributes => _buildSoapHash(
301 $session->data,
302 ( (
303 $session->{_session_kind}
304 and $session->{_session_kind} eq 'SSO'
305 )
306 ? ( @{ $self->exportedAttr } )
307 : ()
308 )
309 )
310 );
311 }
312 my $res = SOAP::Data->name( session => \SOAP::Data->value(@tmp) );
313 return $res;
314 }
315  
316 # Update data in the session referenced by $id
317 # @param $id Id of the session
318 # @param $args data to store
319  
320 =begin WSDL
321  
322 _IN id $string Cookie value
323 _RETURN $setAttributesResponse Response
324  
325 =end WSDL
326  
327 =cut
328  
329 sub setAttributes {
330 my ( $self, $req, $id, $args ) = @_;
331 die 'id is required' unless ($id);
332  
333 my $infos = {};
334 %$infos = %$args;
335  
336 my $session =
337 $self->p->getApacheSession( $id, info => $infos, hashStore => 0 );
338  
339 unless ($session) {
340 $self->logger->warn("Session $id does not exists ($@)");
341 return 0;
342 }
343  
344 $self->logger->debug("SOAP request to update session $id");
345  
346 return 1;
347 }
348  
349 # Return Lemonldap::NG configuration. Warning, this is not a well formed
350 # SOAP::Data object so it can be difficult to read by other languages than
351 # Perl. It's not really a problem since this function is written to be read by
352 # Lemonldap::NG components and is not designed to be shared.
353  
354 sub getConfig {
355 my ( $self, $req, $id ) = @_;
356 my $conf = $self->confAcc->getConf( { raw => 1, cfgNum => $id } )
357 or die("No configuration available");
358 return $conf;
359 }
360  
361 # SOAP method that return the last configuration number.
362 # Call Lemonldap::NG::Common::Conf::lastCfg().
363  
364 sub lastCfg {
365 my $self = shift;
366 return $self->confAcc->lastCfg;
367 }
368  
369 # Store a new session.
370  
371 sub newSession {
372 my ( $self, $req, $args ) = @_;
373  
374 $args ||= {};
375 my $infos = {};
376 %$infos = %$args;
377 $infos->{_utime} = time();
378  
379 my $session = $self->p->getApacheSession( undef, info => $infos );
380  
381 unless ($session) {
382 $self->logger->error("Unable to create session");
383 return 0;
384 }
385  
386 $self->logger->debug(
387 "SOAP request create a new session (" . $session->id . ")" );
388  
389 return SOAP::Data->name( attributes => _buildSoapHash( $session->data ) );
390 }
391  
392 # Deletes an existing session
393  
394 sub deleteSession {
395 my ( $self, $req, $id ) = @_;
396 die('id parameter is required') unless ($id);
397  
398 my $session = $self->p->getApacheSession( $id, kind => '' );
399  
400 return 0 unless ($session);
401  
402 $self->logger->debug("SOAP request to delete session $id");
403  
404 return $self->p->_deleteSession( $req, $session );
405 }
406  
407 # Returns key from all sessions
408  
409 sub getCipheredToken {
410 my ( $self, $req ) = @_;
411 require Lemonldap::NG::Portal::Lib::OneTimeToken;
412 return $self->conf->{cipher}->encrypt(
413 Lemonldap::NG::Portal::Lib::OneTimeToken->new(
414 { p => $self->p, conf => $self->conf, timeout => 5 }
415 )->createToken()
416 );
417 }
418  
419 sub get_key_from_all_sessions {
420 my $self = shift;
421 my $req = shift;
422 my $token = shift;
423  
424 # Verify that token is valid (must be unciphered by client)
425 require Lemonldap::NG::Portal::Lib::OneTimeToken;
426 unless (
427 Lemonldap::NG::Portal::Lib::OneTimeToken->new(
428 { p => $self->p, conf => $self->conf }
429 )->getToken($token)
430 )
431 {
432 die SOAP::Fault->faultcode('Server.Custom')->faultstring('Bad token');
433 }
434 my $moduleOptions = $self->conf->{globalStorageOptions} || {};
435 $moduleOptions->{backend} = $self->conf->{globalStorage};
436 require Lemonldap::NG::Common::Apache::Session;
437  
438 no strict 'refs';
439 return Lemonldap::NG::Common::Apache::Session->get_key_from_all_sessions(
440 $moduleOptions, @_ );
441 }
442  
443 # Check user's authorization for uri.
444 # @param $id Id of the session
445 # @param $uri URL string
446  
447 =begin WSDL
448  
449 _IN id $string Cookie value
450 _IN uri $string URI to test
451 _RETURN $isAuthorizedURIResponse Response
452  
453 =end WSDL
454  
455 =cut
456  
457 sub isAuthorizedURI {
458 my ( $self, $req, $id, $url ) = @_;
459 die 'id is required' unless ($id);
460 die 'uri is required' unless ($url);
461 my ( $host, $uri );
462 if ( $url =~ URIRE ) {
463 ( $host, $uri ) = ( $3 . ( $4 ? ":$4" : '' ), $5 );
464 $uri = $self->p->HANDLER->canonicalUri($uri);
465 }
466 else {
467 die 'Bad uri';
468 }
469  
470 # Get user session.
471 my $session = $self->p->getApacheSession($id);
472  
473 unless ($session) {
474 $self->logger->warn("Session $id does not exists");
475 return 0;
476 }
477  
478 $req->{sessionInfo} = $session->data;
479 my $r =
480 $self->p->HANDLER->grant( $req, $req->{sessionInfo}, $uri, undef, $host );
481  
482 return $r;
483 }
484  
485 # @param $id Id of the session
486  
487 #######################
488 # Private subroutines #
489 #######################
490  
491 ##@fn private SOAP::Data _buildSoapHash()
492 # Serialize a hashref into SOAP::Data. Types are fixed to "string".
493 # @return SOAP::Data serialized data
494 sub _buildSoapHash {
495 my ( $h, @keys ) = @_;
496 my @tmp = ();
497 @keys = keys %$h unless (@keys);
498 foreach (@keys) {
499 if ( ref( $h->{$_} ) eq 'ARRAY' ) {
500 push @tmp, SOAP::Data->name( $_, @{ $h->{$_} } );
501 }
502 elsif ( ref( $h->{$_} ) ) {
503 push @tmp, SOAP::Data->name( $_ => _buildSoapHash( $h->{$_} ) );
504 }
505 else {
506 push @tmp, SOAP::Data->name( $_, $h->{$_} )->type('string')
507 if ( defined( $h->{$_} ) );
508 }
509 }
510 return \SOAP::Data->value(@tmp);
511 }
512  
513 1;
514  
515 __DATA__