Bug 23019: (QA follow-up) fix test fiule permissions
[koha.git] / t / db_dependent / api / v1 / auth_authenticate_api_request.t
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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 3;
21 use Test::Mojo;
22
23 use Module::Load::Conditional qw(can_load);
24
25 use Koha::ApiKeys;
26 use Koha::Database;
27 use Koha::Patrons;
28
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
31
32 my $t = Test::Mojo->new('Koha::REST::V1');
33 my $schema  = Koha::Database->new->schema;
34 my $builder = t::lib::TestBuilder->new();
35
36 my $remote_address = '127.0.0.1';
37 my $tx;
38
39 # FIXME: CGI::Session::Driver::DBI explicitly sets AutoCommit=1 [1] which breaks the rollback in out tests.
40 # Until we change into some other library, set SessionStorage to 'tmp'
41 # [1] https://metacpan.org/source/CGI::Session::Driver::DBI#L28
42 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
43
44 subtest 'token-based tests' => sub {
45
46     if ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) {
47         plan tests => 14;
48     }
49     else {
50         plan skip_all => 'Net::OAuth2::AuthorizationServer not available';
51     }
52
53     $schema->storage->txn_begin;
54
55     my $patron = $builder->build_object({
56         class => 'Koha::Patrons',
57         value  => { flags => 1 },
58     });
59
60     t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 1);
61
62     my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store;
63
64     my $formData = {
65         grant_type    => 'client_credentials',
66         client_id     => $api_key->client_id,
67         client_secret => $api_key->secret
68     };
69     $t->post_ok('/api/v1/oauth/token', form => $formData)
70         ->status_is(200)
71         ->json_is('/expires_in' => 3600)
72         ->json_is('/token_type' => 'Bearer')
73         ->json_has('/access_token');
74
75     my $access_token = $t->tx->res->json->{access_token};
76
77     my $stash;
78     my $interface;
79     my $userenv;
80
81     my $tx = $t->ua->build_tx(GET => '/api/v1/acquisitions/orders');
82     $tx->req->headers->authorization("Bearer $access_token");
83     $tx->req->headers->header( 'x-koha-embed' => 'fund' );
84
85     $t->app->hook(after_dispatch => sub {
86         $stash     = shift->stash;
87         $interface = C4::Context->interface;
88         $userenv   = C4::Context->userenv;
89     });
90
91     # With access token and permissions, it returns 200
92     #$patron->flags(2**4)->store;
93     $t->request_ok($tx)->status_is(200);
94
95     my $user = $stash->{'koha.user'};
96     ok( defined $user, 'The \'koha.user\' object is defined in the stash') and
97     is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and
98     is( $user->borrowernumber, $patron->borrowernumber, 'The stashed user is the right one' );
99     is( $userenv->{number}, $patron->borrowernumber, 'userenv set correctly' );
100     is( $interface, 'api', "Interface correctly set to \'api\'" );
101
102     my $embed = $stash->{'koha.embed'};
103     ok( defined $embed, 'The embed hashref is generated and stashed' );
104     is_deeply( $embed, { fund => {} }, 'The embed data structure is correct' );
105
106     $schema->storage->txn_rollback;
107 };
108
109 subtest 'cookie-based tests' => sub {
110
111     plan tests => 8;
112
113     $schema->storage->txn_begin;
114
115     my ( $borrowernumber, $session_id ) = create_user_and_session({ authorized => 1 });
116
117     $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
118     $tx->req->cookies( { name => 'CGISESSID', value => $session_id } );
119     $tx->req->env( { REMOTE_ADDR => $remote_address } );
120
121     my $stash;
122     my $interface;
123     my $userenv;
124
125     $t->app->hook(after_dispatch => sub {
126         $stash     = shift->stash;
127         $interface = C4::Context->interface;
128         $userenv   = C4::Context->userenv;
129     });
130
131     $t->request_ok($tx)->status_is(200);
132
133     my $user = $stash->{'koha.user'};
134     ok( defined $user, 'The \'koha.user\' object is defined in the stash') and
135     is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and
136     is( $user->borrowernumber, $borrowernumber, 'The stashed user is the right one' );
137     is( $userenv->{number}, $borrowernumber, 'userenv set correctly' );
138     is( $interface, 'api', "Interface correctly set to \'api\'" );
139
140     subtest 'logged-out tests' => sub {
141         plan tests => 3;
142
143         # Generate an anonymous session
144         my $session = C4::Auth::get_session('');
145         $session->param( 'ip',          $remote_address );
146         $session->param( 'lasttime',    time() );
147         $session->param( 'sessiontype', 'anon' );
148         $session->flush;
149
150         my $tx = $t->ua->build_tx( GET => '/api/v1/libraries' );
151         $tx->req->cookies({ name => 'CGISESSID', value => $session->id });
152         $tx->req->env({ REMOTE_ADDR => $remote_address });
153
154         $t->request_ok($tx)
155           ->status_is( 401, 'Anonymous session on permission protected resource returns 401' )
156           ->json_is( { error => 'Authentication failure.' } );
157     };
158
159     $schema->storage->txn_rollback;
160 };
161
162 subtest 'anonymous requests to public API' => sub {
163
164     plan tests => 4;
165
166     $schema->storage->txn_begin;
167
168     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
169
170     my $password = 'AbcdEFG123';
171     my $userid   = 'tomasito';
172     # Add a patron
173     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
174     $patron->set_password({ password => $password });
175     # Add a biblio
176     my $biblio_id = $builder->build_sample_biblio()->biblionumber;
177
178     # Enable the public API
179     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
180     # Disable anonymous requests on the public namespace
181     t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 0 );
182
183     $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' })
184       ->status_is( 401, 'Unauthorized anonymous attempt to access a resource' );
185
186     # Disable anonymous requests on the public namespace
187     t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 1 );
188
189     $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' })
190       ->status_is( 200, 'Successfull anonymous access to a resource' );
191
192     $schema->storage->txn_rollback;
193 };
194
195 sub create_user_and_session {
196
197     my $args  = shift;
198     my $flags = ( $args->{authorized} ) ? 16 : 0;
199
200     my $user = $builder->build(
201         {
202             source => 'Borrower',
203             value  => {
204                 flags => $flags
205             }
206         }
207     );
208
209     # Create a session for the authorized user
210     my $session = C4::Auth::get_session('');
211     $session->param( 'number',   $user->{borrowernumber} );
212     $session->param( 'id',       $user->{userid} );
213     $session->param( 'ip',       '127.0.0.1' );
214     $session->param( 'lasttime', time() );
215     $session->flush;
216
217     return ( $user->{borrowernumber}, $session->id );
218 }