View | Details | Raw Unified | Return to bug 18137
Collapse All | Expand All

(-)a/Koha/REST/V1.pm (-236 / +5 lines)
Lines 51-294 sub startup { Link Here
51
        $self->secrets([$secret_passphrase]);
51
        $self->secrets([$secret_passphrase]);
52
    }
52
    }
53
53
54
    $self->plugin(Swagger2 => {
54
    $self->plugin(OpenAPI => {
55
        url => $self->home->rel_file("api/v1/swagger/swagger.json"),
55
        url => $self->home->rel_file("api/v1/swagger/swagger.json"),
56
        validate => 1,
56
        route => $self->routes->under('/api/v1')->to('Auth#under'),
57
        spec_path => '/spec'
57
        allow_invalid_ref => 1, # required by our spec because $ref directly under
58
                                # Paths-, Parameters-, Definitions- & Info-object
59
                                # is not allowed by the OpenAPI specification.
58
    });
60
    });
59
}
61
}
60
62
61
=head3 authenticate_api_request
62
63
Validates authentication and allows access if authorization is not required or
64
if authorization is required and user has required permissions to access.
65
66
This subroutine is called before every request to API.
67
68
=cut
69
70
sub authenticate_api_request {
71
    my ($next, $c, $action_spec) = @_;
72
73
    my ($session, $user);
74
    my $cookie = $c->cookie('CGISESSID');
75
    # Mojo doesn't use %ENV the way CGI apps do
76
    # Manually pass the remote_address to check_auth_cookie
77
    my $remote_addr = $c->tx->remote_address;
78
    my ($status, $sessionID) = check_cookie_auth(
79
                                            $cookie, undef,
80
                                            { remote_addr => $remote_addr });
81
    if ($status eq "ok") {
82
        $session = get_session($sessionID);
83
        $user = Koha::Patrons->find($session->param('number'));
84
        $c->stash('koha.user' => $user);
85
    }
86
    else {
87
        return $c->render_swagger(
88
            { error => "Authentication failure." },
89
            {},
90
            401
91
        ) if $cookie and $action_spec->{'x-koha-authorization'};
92
    }
93
94
95
    # Then check the parameters
96
    my @query_errors = validate_query_parameters( $c, $action_spec );
97
98
    # We do not need any authorization
99
    unless ( $action_spec->{'x-koha-authorization'} ) {
100
        return @query_errors
101
            ? $c->render_swagger({}, \@query_errors, 400)
102
            : $next->($c);
103
    }
104
105
    unless ($user) {
106
        return $c->render_swagger({ error => "Authentication required." },{},401);
107
    }
108
109
    my $authorization = $action_spec->{'x-koha-authorization'};
110
    my $permissions = $authorization->{'permissions'};
111
112
    # Check if the user is authorized
113
    if ( C4::Auth::haspermission($user->userid, $permissions)
114
        or allow_owner($c, $authorization, $user)
115
        or allow_guarantor($c, $authorization, $user) ) {
116
117
        # Return the query errors if exist
118
        return $c->render_swagger({}, \@query_errors, 400) if @query_errors;
119
120
        # Everything is ok
121
        return $next->($c)
122
    }
123
124
    return $c->render_swagger(
125
        { error => "Authorization failure. Missing required permission(s).",
126
          required_permissions => $permissions },
127
        {},
128
        403
129
    );
130
}
131
132
sub validate_query_parameters {
133
    my ( $c, $action_spec ) = @_;
134
135
    # Check for malformed query parameters
136
    my @errors;
137
    my %valid_parameters = map { ( $_->{in} eq 'query' ) ? ( $_->{name} => 1 ) : () } @{ $action_spec->{parameters} };
138
    my $existing_params = $c->req->query_params->to_hash;
139
    for my $param ( keys %{$existing_params} ) {
140
        push @errors, { path => "/query/" . $param, message => 'Malformed query string' } unless exists $valid_parameters{$param};
141
    }
142
    return @errors;
143
}
144
145
146
=head3 allow_owner
147
148
Allows access to object for its owner.
149
150
There are endpoints that should allow access for the object owner even if they
151
do not have the required permission, e.g. access an own reserve. This can be
152
achieved by defining the operation as follows:
153
154
"/holds/{reserve_id}": {
155
    "get": {
156
        ...,
157
        "x-koha-authorization": {
158
            "allow-owner": true,
159
            "permissions": {
160
                "borrowers": "1"
161
            }
162
        }
163
    }
164
}
165
166
=cut
167
168
sub allow_owner {
169
    my ($c, $authorization, $user) = @_;
170
171
    return unless $authorization->{'allow-owner'};
172
173
    return check_object_ownership($c, $user) if $user and $c;
174
}
175
176
=head3 allow_guarantor
177
178
Same as "allow_owner", but checks if the object is owned by one of C<$user>'s
179
guarantees.
180
181
=cut
182
183
sub allow_guarantor {
184
    my ($c, $authorization, $user) = @_;
185
186
    if (!$c || !$user || !$authorization || !$authorization->{'allow-guarantor'}){
187
        return;
188
    }
189
190
    my $guarantees = $user->guarantees->as_list;
191
    foreach my $guarantee (@{$guarantees}) {
192
        return 1 if check_object_ownership($c, $guarantee);
193
    }
194
}
195
196
=head3 check_object_ownership
197
198
Determines ownership of an object from request parameters.
199
200
As introducing an endpoint that allows access for object's owner; if the
201
parameter that will be used to determine ownership is not already inside
202
$parameters, add a new subroutine that checks the ownership and extend
203
$parameters to contain a key with parameter_name and a value of a subref to
204
the subroutine that you created.
205
206
=cut
207
208
sub check_object_ownership {
209
    my ($c, $user) = @_;
210
211
    return if not $c or not $user;
212
213
    my $parameters = {
214
        accountlines_id => \&_object_ownership_by_accountlines_id,
215
        borrowernumber  => \&_object_ownership_by_borrowernumber,
216
        checkout_id     => \&_object_ownership_by_checkout_id,
217
        reserve_id      => \&_object_ownership_by_reserve_id,
218
    };
219
220
    foreach my $param ( keys %{ $parameters } ) {
221
        my $check_ownership = $parameters->{$param};
222
        if ($c->stash($param)) {
223
            return &$check_ownership($c, $user, $c->stash($param));
224
        }
225
        elsif ($c->param($param)) {
226
            return &$check_ownership($c, $user, $c->param($param));
227
        }
228
        elsif ($c->req->json && $c->req->json->{$param}) {
229
            return 1 if &$check_ownership($c, $user, $c->req->json->{$param});
230
        }
231
    }
232
}
233
234
=head3 _object_ownership_by_accountlines_id
235
236
Finds a Koha::Account::Line-object by C<$accountlines_id> and checks if it
237
belongs to C<$user>.
238
239
=cut
240
241
sub _object_ownership_by_accountlines_id {
242
    my ($c, $user, $accountlines_id) = @_;
243
244
    my $accountline = Koha::Account::Lines->find($accountlines_id);
245
    return $accountline && $user->borrowernumber == $accountline->borrowernumber;
246
}
247
248
=head3 _object_ownership_by_borrowernumber
249
250
Compares C<$borrowernumber> to currently logged in C<$user>.
251
252
=cut
253
254
sub _object_ownership_by_borrowernumber {
255
    my ($c, $user, $borrowernumber) = @_;
256
257
    return $user->borrowernumber == $borrowernumber;
258
}
259
260
=head3 _object_ownership_by_checkout_id
261
262
First, attempts to find a Koha::Checkout-object by C<$issue_id>. If we find one,
263
compare its borrowernumber to currently logged in C<$user>. However, if an issue
264
is not found, attempt to find a Koha::Old::Checkout-object instead and compare its
265
borrowernumber to currently logged in C<$user>.
266
267
=cut
268
269
sub _object_ownership_by_checkout_id {
270
    my ($c, $user, $issue_id) = @_;
271
272
    my $issue = Koha::Checkouts->find($issue_id);
273
    $issue = Koha::Old::Checkouts->find($issue_id) unless $issue;
274
    return $issue && $issue->borrowernumber
275
            && $user->borrowernumber == $issue->borrowernumber;
276
}
277
278
=head3 _object_ownership_by_reserve_id
279
280
Finds a Koha::Hold-object by C<$reserve_id> and checks if it
281
belongs to C<$user>.
282
283
TODO: Also compare against old_reserves
284
285
=cut
286
287
sub _object_ownership_by_reserve_id {
288
    my ($c, $user, $reserve_id) = @_;
289
290
    my $reserve = Koha::Holds->find($reserve_id);
291
    return $reserve && $user->borrowernumber == $reserve->borrowernumber;
292
}
293
294
1;
63
1;
(-)a/Koha/REST/V1/Auth.pm (+329 lines)
Line 0 Link Here
1
package Koha::REST::V1::Auth;
2
3
# Copyright Koha-Suomi Oy 2017
4
#
5
# This file is part of Koha.
6
#
7
# Koha is free software; you can redistribute it and/or modify it under the
8
# terms of the GNU General Public License as published by the Free Software
9
# Foundation; either version 3 of the License, or (at your option) any later
10
# version.
11
#
12
# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License along
17
# with Koha; if not, write to the Free Software Foundation, Inc.,
18
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20
use Modern::Perl;
21
22
use Mojo::Base 'Mojolicious::Controller';
23
24
use C4::Auth qw( check_cookie_auth get_session haspermission );
25
26
use Koha::Patrons;
27
28
use Koha::Exceptions;
29
use Koha::Exceptions::Authentication;
30
use Koha::Exceptions::Authorization;
31
32
use Scalar::Util qw( blessed );
33
use Try::Tiny;
34
35
=head3 under
36
37
This subroutine is called before every request to API.
38
39
=cut
40
41
sub under {
42
    my $c = shift->openapi->valid_input or return;;
43
44
    my $status = 0;
45
    try {
46
47
        $status = authenticate_api_request($c);
48
49
    } catch {
50
        unless (blessed($_)) {
51
            return $c->render(
52
                status => 500,
53
                json => { error => 'Something went wrong, check the logs.' }
54
            );
55
        }
56
        if ($_->isa('Koha::Exceptions::UnderMaintenance')) {
57
            return $c->render(status => 503, json => { error => $_->error });
58
        }
59
        elsif ($_->isa('Koha::Exceptions::Authentication::SessionExpired')) {
60
            return $c->render(status => 401, json => { error => $_->error });
61
        }
62
        elsif ($_->isa('Koha::Exceptions::Authentication::Required')) {
63
            return $c->render(status => 401, json => { error => $_->error });
64
        }
65
        elsif ($_->isa('Koha::Exceptions::Authentication')) {
66
            return $c->render(status => 500, json => { error => $_->error });
67
        }
68
        elsif ($_->isa('Koha::Exceptions::BadParameter')) {
69
            return $c->render(status => 400, json => $_->error );
70
        }
71
        elsif ($_->isa('Koha::Exceptions::Authorization::Unauthorized')) {
72
            return $c->render(status => 403, json => {
73
                error => $_->error,
74
                required_permissions => $_->required_permissions,
75
            });
76
        }
77
        elsif ($_->isa('Koha::Exceptions')) {
78
            return $c->render(status => 500, json => { error => $_->error });
79
        }
80
        else {
81
            return $c->render(
82
                status => 500,
83
                json => { error => 'Something went wrong, check the logs.' }
84
            );
85
        }
86
    };
87
88
    return $status;
89
}
90
91
=head3 authenticate_api_request
92
93
Validates authentication and allows access if authorization is not required or
94
if authorization is required and user has required permissions to access.
95
96
=cut
97
98
sub authenticate_api_request {
99
    my ( $c ) = @_;
100
101
    my $spec = $c->match->endpoint->pattern->defaults->{'openapi.op_spec'};
102
    my $authorization = $spec->{'x-koha-authorization'};
103
    my $cookie = $c->cookie('CGISESSID');
104
    my ($session, $user);
105
    # Mojo doesn't use %ENV the way CGI apps do
106
    # Manually pass the remote_address to check_auth_cookie
107
    my $remote_addr = $c->tx->remote_address;
108
    my ($status, $sessionID) = check_cookie_auth(
109
                                            $cookie, undef,
110
                                            { remote_addr => $remote_addr });
111
    if ($status eq "ok") {
112
        $session = get_session($sessionID);
113
        $user = Koha::Patrons->find($session->param('number'));
114
        $c->stash('koha.user' => $user);
115
    }
116
    elsif ($status eq "maintenance") {
117
        Koha::Exceptions::UnderMaintenance->throw(
118
            error => 'System is under maintenance.'
119
        );
120
    }
121
    elsif ($status eq "expired" and $authorization) {
122
        Koha::Exceptions::Authentication::SessionExpired->throw(
123
            error => 'Session has been expired.'
124
        );
125
    }
126
    elsif ($status eq "failed" and $authorization) {
127
        Koha::Exceptions::Authentication::Required->throw(
128
            error => 'Authentication failure.'
129
        );
130
    }
131
    elsif ($authorization) {
132
        Koha::Exceptions::Authentication->throw(
133
            error => 'Unexpected authentication status.'
134
        );
135
    }
136
137
    # We do not need any authorization
138
    unless ($authorization) {
139
        # Check the parameters
140
        validate_query_parameters( $c, $spec );
141
        return 1;
142
    }
143
144
    my $permissions = $authorization->{'permissions'};
145
    # Check if the user is authorized
146
    if ( haspermission($user->userid, $permissions)
147
        or allow_owner($c, $authorization, $user)
148
        or allow_guarantor($c, $authorization, $user) ) {
149
150
        validate_query_parameters( $c, $spec );
151
152
        # Everything is ok
153
        return 1;
154
    }
155
156
    Koha::Exceptions::Authorization::Unauthorized->throw(
157
        error => "Authorization failure. Missing required permission(s).",
158
        required_permissions => $permissions,
159
    );
160
}
161
sub validate_query_parameters {
162
    my ( $c, $action_spec ) = @_;
163
164
    # Check for malformed query parameters
165
    my @errors;
166
    my %valid_parameters = map { ( $_->{in} eq 'query' ) ? ( $_->{name} => 1 ) : () } @{ $action_spec->{parameters} };
167
    my $existing_params = $c->req->query_params->to_hash;
168
    for my $param ( keys %{$existing_params} ) {
169
        push @errors, { path => "/query/" . $param, message => 'Malformed query string' } unless exists $valid_parameters{$param};
170
    }
171
172
    Koha::Exceptions::BadParameter->throw(
173
        error => \@errors
174
    ) if @errors;
175
}
176
177
178
=head3 allow_owner
179
180
Allows access to object for its owner.
181
182
There are endpoints that should allow access for the object owner even if they
183
do not have the required permission, e.g. access an own reserve. This can be
184
achieved by defining the operation as follows:
185
186
"/holds/{reserve_id}": {
187
    "get": {
188
        ...,
189
        "x-koha-authorization": {
190
            "allow-owner": true,
191
            "permissions": {
192
                "borrowers": "1"
193
            }
194
        }
195
    }
196
}
197
198
=cut
199
200
sub allow_owner {
201
    my ($c, $authorization, $user) = @_;
202
203
    return unless $authorization->{'allow-owner'};
204
205
    return check_object_ownership($c, $user) if $user and $c;
206
}
207
208
=head3 allow_guarantor
209
210
Same as "allow_owner", but checks if the object is owned by one of C<$user>'s
211
guarantees.
212
213
=cut
214
215
sub allow_guarantor {
216
    my ($c, $authorization, $user) = @_;
217
218
    if (!$c || !$user || !$authorization || !$authorization->{'allow-guarantor'}){
219
        return;
220
    }
221
222
    my $guarantees = $user->guarantees->as_list;
223
    foreach my $guarantee (@{$guarantees}) {
224
        return 1 if check_object_ownership($c, $guarantee);
225
    }
226
}
227
228
=head3 check_object_ownership
229
230
Determines ownership of an object from request parameters.
231
232
As introducing an endpoint that allows access for object's owner; if the
233
parameter that will be used to determine ownership is not already inside
234
$parameters, add a new subroutine that checks the ownership and extend
235
$parameters to contain a key with parameter_name and a value of a subref to
236
the subroutine that you created.
237
238
=cut
239
240
sub check_object_ownership {
241
    my ($c, $user) = @_;
242
243
    return if not $c or not $user;
244
245
    my $parameters = {
246
        accountlines_id => \&_object_ownership_by_accountlines_id,
247
        borrowernumber  => \&_object_ownership_by_borrowernumber,
248
        checkout_id     => \&_object_ownership_by_checkout_id,
249
        reserve_id      => \&_object_ownership_by_reserve_id,
250
    };
251
252
    foreach my $param ( keys %{ $parameters } ) {
253
        my $check_ownership = $parameters->{$param};
254
        if ($c->stash($param)) {
255
            return &$check_ownership($c, $user, $c->stash($param));
256
        }
257
        elsif ($c->param($param)) {
258
            return &$check_ownership($c, $user, $c->param($param));
259
        }
260
        elsif ($c->match->stack->[-1]->{$param}) {
261
            return &$check_ownership($c, $user, $c->match->stack->[-1]->{$param});
262
        }
263
        elsif ($c->req->json && $c->req->json->{$param}) {
264
            return 1 if &$check_ownership($c, $user, $c->req->json->{$param});
265
        }
266
    }
267
}
268
269
=head3 _object_ownership_by_accountlines_id
270
271
Finds a Koha::Account::Line-object by C<$accountlines_id> and checks if it
272
belongs to C<$user>.
273
274
=cut
275
276
sub _object_ownership_by_accountlines_id {
277
    my ($c, $user, $accountlines_id) = @_;
278
279
    my $accountline = Koha::Account::Lines->find($accountlines_id);
280
    return $accountline && $user->borrowernumber == $accountline->borrowernumber;
281
}
282
283
=head3 _object_ownership_by_borrowernumber
284
285
Compares C<$borrowernumber> to currently logged in C<$user>.
286
287
=cut
288
289
sub _object_ownership_by_borrowernumber {
290
    my ($c, $user, $borrowernumber) = @_;
291
292
    return $user->borrowernumber == $borrowernumber;
293
}
294
295
=head3 _object_ownership_by_checkout_id
296
297
First, attempts to find a Koha::Checkout-object by C<$issue_id>. If we find one,
298
compare its borrowernumber to currently logged in C<$user>. However, if an issue
299
is not found, attempt to find a Koha::Old::Checkout-object instead and compare its
300
borrowernumber to currently logged in C<$user>.
301
302
=cut
303
304
sub _object_ownership_by_checkout_id {
305
    my ($c, $user, $issue_id) = @_;
306
307
    my $issue = Koha::Checkouts->find($issue_id);
308
    $issue = Koha::Old::Checkouts->find($issue_id) unless $issue;
309
    return $issue && $issue->borrowernumber
310
            && $user->borrowernumber == $issue->borrowernumber;
311
}
312
313
=head3 _object_ownership_by_reserve_id
314
315
Finds a Koha::Hold-object by C<$reserve_id> and checks if it
316
belongs to C<$user>.
317
318
TODO: Also compare against old_reserves
319
320
=cut
321
322
sub _object_ownership_by_reserve_id {
323
    my ($c, $user, $reserve_id) = @_;
324
325
    my $reserve = Koha::Holds->find($reserve_id);
326
    return $reserve && $user->borrowernumber == $reserve->borrowernumber;
327
}
328
329
1;
(-)a/t/db_dependent/api/v1/auth.t (-1 / +116 lines)
Line 0 Link Here
0
- 
1
#!/usr/bin/env perl
2
3
# This file is part of Koha.
4
#
5
# Koha is free software; you can redistribute it and/or modify it under the
6
# terms of the GNU General Public License as published by the Free Software
7
# Foundation; either version 3 of the License, or (at your option) any later
8
# version.
9
#
10
# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License along
15
# with Koha; if not, write to the Free Software Foundation, Inc.,
16
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18
use Modern::Perl;
19
20
use Test::More tests => 1;
21
use Test::Mojo;
22
use Test::Warn;
23
24
use t::lib::TestBuilder;
25
use t::lib::Mocks;
26
27
use C4::Auth;
28
use Koha::Database;
29
30
my $schema  = Koha::Database->new->schema;
31
my $builder = t::lib::TestBuilder->new;
32
33
# FIXME: sessionStorage defaults to mysql, but it seems to break transaction handling
34
# this affects the other REST api tests
35
t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
36
37
my $remote_address = '127.0.0.1';
38
my $t              = Test::Mojo->new('Koha::REST::V1');
39
my $tx;
40
41
subtest 'under() tests' => sub {
42
    plan tests => 15;
43
44
    $schema->storage->txn_begin;
45
46
    my ($borrowernumber, $session_id) = create_user_and_session();
47
48
    # 401 (no authentication)
49
    $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
50
    $tx->req->env( { REMOTE_ADDR => $remote_address } );
51
    $t->request_ok($tx)
52
      ->status_is(401)
53
      ->json_is('/error', 'Authentication failure.');
54
55
    # 403 (no permission)
56
    $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
57
    $tx->req->cookies(
58
        { name => 'CGISESSID', value => $session_id } );
59
    $tx->req->env( { REMOTE_ADDR => $remote_address } );
60
    $t->request_ok($tx)
61
      ->status_is(403)
62
      ->json_is('/error', 'Authorization failure. Missing required permission(s).');
63
64
    # 401 (session expired)
65
    my $session = C4::Auth::get_session($session_id);
66
    $session->delete;
67
    $session->flush;
68
    $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
69
    $tx->req->cookies(
70
        { name => 'CGISESSID', value => $session_id } );
71
    $tx->req->env( { REMOTE_ADDR => $remote_address } );
72
    $t->request_ok($tx)
73
      ->status_is(401)
74
      ->json_is('/error', 'Session has been expired.');
75
76
    # 503 (under maintenance & pending update)
77
    t::lib::Mocks::mock_preference('Version', 1);
78
    $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
79
    $tx->req->env( { REMOTE_ADDR => $remote_address } );
80
    $t->request_ok($tx)
81
      ->status_is(503)
82
      ->json_is('/error', 'System is under maintenance.');
83
84
    # 503 (under maintenance & database not installed)
85
    t::lib::Mocks::mock_preference('Version', undef);
86
    $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
87
    $tx->req->env( { REMOTE_ADDR => $remote_address } );
88
    $t->request_ok($tx)
89
      ->status_is(503)
90
      ->json_is('/error', 'System is under maintenance.');
91
92
    $schema->storage->txn_rollback;
93
};
94
95
sub create_user_and_session {
96
    my $user = $builder->build(
97
        {
98
            source => 'Borrower',
99
            value  => {
100
                flags => 0
101
            }
102
        }
103
    );
104
105
    # Create a session for the authorized user
106
    my $session = C4::Auth::get_session('');
107
    $session->param( 'number',   $user->{borrowernumber} );
108
    $session->param( 'id',       $user->{userid} );
109
    $session->param( 'ip',       '127.0.0.1' );
110
    $session->param( 'lasttime', time() );
111
    $session->flush;
112
113
    return ( $user->{borrowernumber}, $session->id );
114
}
115
116
1;

Return to bug 18137