Bug 23146: Unit tests
[koha-equinox.git] / t / db_dependent / api / v1 / oauth.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 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;
21 use Test::MockModule;
22 use Test::Mojo;
23
24 use MIME::Base64;
25 use Module::Load::Conditional qw(can_load);
26
27 use Koha::ApiKeys;
28 use Koha::Database;
29 use Koha::Patrons;
30
31 use t::lib::Mocks;
32 use t::lib::TestBuilder;
33
34 my $t = Test::Mojo->new('Koha::REST::V1');
35 my $schema  = Koha::Database->new->schema;
36 my $builder = t::lib::TestBuilder->new();
37
38 if ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) {
39     plan tests => 2;
40 }
41 else {
42     plan skip_all => 'Net::OAuth2::AuthorizationServer not available';
43 }
44
45 subtest '/oauth/token tests' => sub {
46
47     plan tests => 10;
48
49     t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 0);
50
51     # Missing parameter grant_type
52     $t->post_ok('/api/v1/oauth/token')
53         ->status_is(400);
54
55     # Wrong grant type
56     $t->post_ok('/api/v1/oauth/token', form => { grant_type => 'password' })
57         ->status_is(400)
58         ->json_is({error => 'Unimplemented grant type'});
59
60     t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 1);
61
62     # No client_id/client_secret
63     $t->post_ok('/api/v1/oauth/token', form => { grant_type => 'client_credentials' })
64         ->status_is(403)
65         ->json_is({error => 'unauthorized_client'});
66
67     subtest 'Client credentials in body' => sub {
68
69         plan tests => 19;
70
71         run_oauth_tests( 'body' );
72     };
73
74     subtest 'Client credentials in Authorization header' => sub {
75
76
77         plan tests => 19;
78
79         run_oauth_tests( 'header' );
80     };
81 };
82
83 subtest 'Net::OAuth2::AuthorizationServer missing tests' => sub {
84
85     plan tests => 10;
86
87     my $load_conditional = Test::MockModule->new('Module::Load::Conditional');
88
89     # Enable the client credentials grant syspref
90     t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 1 );
91
92     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 2**4 } });
93     my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store;
94
95     my $form_data = {
96         grant_type    => 'client_credentials',
97         client_id     => $api_key->client_id,
98         client_secret => $api_key->secret
99     };
100
101     $t->post_ok( '/api/v1/oauth/token', form => $form_data )->status_is(200)
102       ->json_is( '/expires_in' => 3600 )->json_is( '/token_type' => 'Bearer' )
103       ->json_has('/access_token');
104
105     my $access_token = $t->tx->res->json->{access_token};
106
107     $load_conditional->mock( 'can_load', sub { return 0; } );
108
109     my $tx = $t->ua->build_tx( GET => '/api/v1/patrons' );
110     $tx->req->headers->authorization("Bearer $access_token");
111     $t->request_ok($tx)
112       ->status_is(403);
113
114     $t->post_ok( '/api/v1/oauth/token', form => $form_data )
115       ->status_is(400)
116       ->json_is( { error => 'Unimplemented grant type' } );
117
118 };
119
120 sub run_oauth_tests {
121     my ( $test_case ) = @_;
122
123     $schema->storage->txn_begin;
124
125     my $patron = $builder->build_object({
126         class => 'Koha::Patrons',
127         value  => {
128             flags => 0 # no permissions
129         },
130     });
131
132     my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store;
133
134     t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 1 );
135
136     my $formData;
137     my $client_id     = $api_key->client_id;
138     my $client_secret = $api_key->secret;
139
140     if ( $test_case eq 'header' ) {
141
142         $formData = { grant_type => 'client_credentials' };
143
144         $t->post_ok("//$client_id:$client_secret@/api/v1/oauth/token", form => $formData)
145           ->status_is(200)
146           ->json_is('/expires_in' => 3600)
147           ->json_is('/token_type' => 'Bearer')
148           ->json_has('/access_token');
149     } else {
150
151         $formData = {
152             grant_type    => 'client_credentials',
153             client_id     => $api_key->client_id,
154             client_secret => $api_key->secret
155         };
156
157         $t->post_ok('/api/v1/oauth/token', form => $formData)
158           ->status_is(200)
159           ->json_is('/expires_in' => 3600)
160           ->json_is('/token_type' => 'Bearer')
161           ->json_has('/access_token');
162     }
163
164     my $access_token = $t->tx->res->json->{access_token};
165
166     # Without access token, it returns 401
167     $t->get_ok('/api/v1/patrons')->status_is(401);
168
169     # With access token, but without permissions, it returns 403
170     my $tx = $t->ua->build_tx(GET => '/api/v1/patrons');
171     $tx->req->headers->authorization("Bearer $access_token");
172     $t->request_ok($tx)->status_is(403);
173
174     # With access token and permissions, it returns 200
175     $patron->flags(2**4)->store;
176     $tx = $t->ua->build_tx(GET => '/api/v1/patrons');
177     $tx->req->headers->authorization("Bearer $access_token");
178     $t->request_ok($tx)->status_is(200);
179
180     # expire token
181     my $token = Koha::OAuthAccessTokens->find($access_token);
182     $token->expires( time - 1 )->store;
183     $tx = $t->ua->build_tx( GET => '/api/v1/patrons' );
184     $tx->req->headers->authorization("Bearer $access_token");
185     $t->request_ok($tx)
186       ->status_is(401);
187
188     # revoke key
189     $api_key->active(0)->store;
190
191     if ( $test_case eq 'header' ) {
192         $t->post_ok("//$client_id:$client_secret@/api/v1/oauth/token", form => $formData)
193           ->status_is(403)
194           ->json_is({ error => 'unauthorized_client' });
195     } else {
196         $t->post_ok('/api/v1/oauth/token', form => $formData)
197           ->status_is(403)
198           ->json_is({ error => 'unauthorized_client' });
199     }
200
201     # disable client credentials grant
202    t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 0);
203
204     # enable API key
205     $api_key->active(1)->store;
206
207     # Wrong grant type
208     if ( $test_case eq 'header' ) {
209         $t->post_ok("//$client_id:$client_secret@/api/v1/oauth/token", form => $formData )
210           ->status_is(400)
211           ->json_is({ error => 'Unimplemented grant type' });
212     }
213     else {
214         $t->post_ok('/api/v1/oauth/token', form => $formData )
215           ->status_is(400)
216           ->json_is({ error => 'Unimplemented grant type' });
217     }
218
219     $schema->storage->txn_rollback;
220 }