diff --git a/CHANGELOG.md b/CHANGELOG.md index ccc7418..dfc3153 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Security +- Signing in through `POST /wp-json/escalated/v1/auth/login` (or `auth/register`) no longer gives every user a full-access API token. Escalated admins get `*`, other staff `agent`, and everyone else a `customer` token that only works on the routes about their own account (`auth/me`, `auth/profile`, `auth/refresh`, `auth/logout`). +- Every staff API route now checks that the token's owner is still Escalated staff, whatever the visibility setting. Before, the check ran only with department visibility or account scoping on. +- `auth/refresh` keeps the token's name, abilities and expiry instead of issuing a new full-access token without an expiry. + +### Upgrading +- No migrations. Tokens issued by `auth/login` before this release to users who are not staff stop working on the staff routes; revoke them on the API tokens screen if you want them gone. A token whose owner is not staff is now refused with 403 `User no longer has agent access.` (was 401). Agents who sign in through `auth/login` get an `agent` token, so they no longer reach the admin routes that way; an admin can still issue a `*` or `admin` token to them on the API tokens screen. + +### Fixed +- An API request counts once against the rate limit; requests were counted twice, halving the configured limit. + ## [1.6.13] - 2026-11-25 ### Upgrading - No migrations. **Required: schedule the recurring jobs.** Add a system cron job that runs WP-Cron every minute (`* * * * * wp cron event run --due-now --path=/path/to/wordpress`); a quiet site, or one with `DISABLE_WP_CRON` and no cron job, otherwise runs no SLA checks, escalation rules, automations or snooze wake-ups. Escalated now warns admins when they have not run for 15 minutes. See docs/operations.md. diff --git a/docs/access-control.md b/docs/access-control.md index 2797a78..a7c9af9 100644 --- a/docs/access-control.md +++ b/docs/access-control.md @@ -262,9 +262,21 @@ the way escalated-laravel's API does. A token is issued with one or more of: | Ability | Reaches | |---|---| -| `agent` | the agent routes: tickets (list, show, create, reply, note, status, priority, assign, tags, follow, macros, actions, merge, split, snooze), agents, departments, tags, canned responses, macros, dashboard, saved views, chat, events, attachments, `auth/*`, `admin/two-factor` | +| `agent` | the agent routes: tickets (list, show, create, reply, note, status, priority, assign, tags, follow, macros, actions, merge, split, snooze), agents, departments, tags, canned responses, macros, dashboard, saved views, chat, events, attachments, `auth/validate`, `admin/two-factor` | | `admin` | the admin routes: `DELETE tickets/{ref}`, `automations`, `admin/api-tokens` | | `*` | both | +| `customer` | only the routes about the token's own account: `auth/me`, `auth/profile`, `auth/refresh`, `auth/logout` (any valid token reaches these) | + +Every agent and admin route also checks that the token's owner is still +Escalated staff (an admin, or a user with `escalated_ticket_view`), whatever +the visibility setting; a token whose owner is not is answered 403 +`User no longer has agent access.` + +`POST auth/login` and `POST auth/register` (the mobile app's password sign-in) +issue a token named `flutter-app` with the user's role: `*` for Escalated +admins, `agent` for other staff and `customer` for everyone else. +`auth/refresh` replaces the token with one of the same name, abilities and +expiry. An admin-only token cannot reach the agent routes; give a token both `agent` and `admin` (or `*`) for both. A valid token without the ability is answered diff --git a/includes/Api/class-auth-controller.php b/includes/Api/class-auth-controller.php index 592e2dc..8afe2ab 100644 --- a/includes/Api/class-auth-controller.php +++ b/includes/Api/class-auth-controller.php @@ -7,11 +7,17 @@ * credentials with wp_authenticate() and issues an Escalated API token; the * token-authenticated endpoints reuse the Bearer-token machinery in * Base_Controller. Mirrors the /auth contract of the other backends. + * + * The token a login or registration issues carries the user's Escalated + * role: `*` for Escalated admins, `agent` for other staff, and `customer` + * for everyone else. A customer token only reaches the routes about its own + * account (me, profile, refresh, logout); the staff routes refuse it. */ namespace Escalated\Api; use Escalated\Models\ApiToken; +use Escalated\Services\TicketAccess; use WP_REST_Request; use WP_REST_Server; @@ -30,16 +36,17 @@ class Auth_Controller extends Base_Controller public function register_routes(): void { $public = '__return_true'; - $authed = [$this, 'token_permissions_check']; + $staff = [$this, 'token_permissions_check']; + $own = [$this, 'self_token_permissions_check']; $routes = [ - ['validate', WP_REST_Server::CREATABLE, 'validate_token', $authed], + ['validate', WP_REST_Server::CREATABLE, 'validate_token', $staff], ['login', WP_REST_Server::CREATABLE, 'login', $public], ['register', WP_REST_Server::CREATABLE, 'register', $public], - ['logout', WP_REST_Server::CREATABLE, 'logout', $authed], - ['refresh', WP_REST_Server::CREATABLE, 'refresh', $authed], - ['me', WP_REST_Server::READABLE, 'me', $authed], - ['profile', WP_REST_Server::EDITABLE, 'update_profile', $authed], + ['logout', WP_REST_Server::CREATABLE, 'logout', $own], + ['refresh', WP_REST_Server::CREATABLE, 'refresh', $own], + ['me', WP_REST_Server::READABLE, 'me', $own], + ['profile', WP_REST_Server::EDITABLE, 'update_profile', $own], ]; foreach ($routes as [$path, $methods, $callback, $permission]) { @@ -145,7 +152,7 @@ public function register(WP_REST_Request $request) */ public function me(WP_REST_Request $request) { - $user = get_userdata($this->check_token_permission($request)); + $user = get_userdata($this->check_token_permission($request, 'self')); return $this->success(['user' => $this->user_payload($user)]); } @@ -158,7 +165,7 @@ public function me(WP_REST_Request $request) */ public function update_profile(WP_REST_Request $request) { - $user_id = $this->check_token_permission($request); + $user_id = $this->check_token_permission($request, 'self'); $args = ['ID' => $user_id]; if ($request->get_param('display_name') !== null) { @@ -195,17 +202,53 @@ public function logout(WP_REST_Request $request) } /** - * Issue a fresh token and revoke the current one. + * Issue a fresh token and revoke the current one. The new token keeps + * the current one's name, abilities and expiry. * * @param WP_REST_Request $request The incoming request. - * @return \WP_REST_Response + * @return \WP_REST_Response|\WP_Error */ public function refresh(WP_REST_Request $request) { - $user = get_userdata($this->check_token_permission($request)); - $this->revoke_request_token($request); + $user = get_userdata($this->check_token_permission($request, 'self')); + $current = $this->request_token($request); - return $this->success($this->issue_token_response($user)); + if (! $user || ! $current) { + return $this->token_error(); + } + + $abilities = json_decode((string) $current->abilities, true); + $created = ApiToken::create_token($user->ID, (string) $current->name, is_array($abilities) ? $abilities : []); + + if ($created && ! empty($current->expires_at)) { + ApiToken::update($created['record']->id, ['expires_at' => $current->expires_at]); + } + + ApiToken::delete($current->id); + + return $this->success([ + 'token' => $created ? $created['token'] : null, + 'user' => $this->user_payload($user), + ]); + } + + /** + * The abilities a password login gives a user: `*` for Escalated + * admins, `agent` for other staff, `customer` for everyone else. + * + * @param \WP_User $user + */ + private function login_abilities($user): array + { + if (TicketAccess::is_admin((int) $user->ID)) { + return ['*']; + } + + if (TicketAccess::is_staff((int) $user->ID)) { + return ['agent']; + } + + return ['customer']; } /** @@ -215,7 +258,7 @@ public function refresh(WP_REST_Request $request) */ private function issue_token_response($user): array { - $created = ApiToken::create_token($user->ID, 'flutter-app'); + $created = ApiToken::create_token($user->ID, 'flutter-app', $this->login_abilities($user)); return [ 'token' => $created ? $created['token'] : null, @@ -244,14 +287,28 @@ private function user_payload($user): array * @param WP_REST_Request $request The incoming request. */ private function revoke_request_token(WP_REST_Request $request): void + { + $record = $this->request_token($request); + + if ($record) { + ApiToken::delete($record->id); + } + } + + /** + * The token record carried by the request's Authorization header. + * + * @param WP_REST_Request $request The incoming request. + * @return object|null + */ + private function request_token(WP_REST_Request $request) { $header = (string) $request->get_header('Authorization'); - if ($header !== '' && str_starts_with($header, 'Bearer ')) { - $record = ApiToken::find_by_token(substr($header, 7)); - if ($record) { - ApiToken::delete($record->id); - } + if ($header === '' || ! str_starts_with($header, 'Bearer ')) { + return null; } + + return ApiToken::find_by_token(substr($header, 7)); } } diff --git a/includes/Api/class-base-controller.php b/includes/Api/class-base-controller.php index bbf7501..ca5d57f 100644 --- a/includes/Api/class-base-controller.php +++ b/includes/Api/class-base-controller.php @@ -8,6 +8,7 @@ use Escalated\Models\ApiToken; use Escalated\Models\Setting; +use Escalated\Services\TicketAccess; use WP_Error; use WP_REST_Controller; use WP_REST_Request; @@ -24,8 +25,8 @@ abstract class Base_Controller extends WP_REST_Controller /** * Why the last check_token_permission() call failed: 'ability' when the - * token is valid but may not call the route (answered 403), otherwise - * 'token' (answered 401). + * token is valid but may not call the route, 'staff' when its owner is no + * longer an agent (both answered 403), otherwise 'token' (answered 401). * * @var string|null */ @@ -39,7 +40,9 @@ abstract class Base_Controller extends WP_REST_Controller * * @param WP_REST_Request $request The incoming request. * @param string $level 'agent' (default) or 'admin', as escalated-laravel's - * route groups; see ApiToken::allows(). + * route groups (see ApiToken::allows()), or 'self' + * for the routes about the token's own account, + * which any valid token may call. * @return int|null The authenticated user ID, or null on failure. */ protected function check_token_permission(WP_REST_Request $request, string $level = 'agent'): ?int @@ -64,14 +67,31 @@ protected function check_token_permission(WP_REST_Request $request, string $leve } // Check the token may call a route of this level. - if (! ApiToken::allows($token_record, $level, $request->get_method(), (string) $request->get_route())) { + if ($level !== 'self' && ! ApiToken::allows($token_record, $level, $request->get_method(), (string) $request->get_route())) { $this->token_failure = 'ability'; return null; } - // Rate limiting. - if (! $this->check_rate_limit($token_record->token)) { + $user_id = (int) $token_record->user_id; + + if (! get_userdata($user_id)) { + return null; + } + + // Staff routes need an owner who is still staff, whatever the token's + // abilities and the visibility setting say. Admin routes are further + // gated by the token's `admin` ability and, with roles and + // permissions on, by the owner's permissions (AccessEnforcer). + if ($level !== 'self' && ! TicketAccess::is_staff($user_id)) { + $this->token_failure = 'staff'; + + return null; + } + + // Rate limiting, once per request: handlers that re-check the token + // after the permission callback do not count again. + if (TicketAccess::token_user($request) === null && ! $this->check_rate_limit($token_record->token)) { return null; } @@ -79,11 +99,7 @@ protected function check_token_permission(WP_REST_Request $request, string $leve $ip = $request->get_header('X-Forwarded-For') ?? ($_SERVER['REMOTE_ADDR'] ?? ''); ApiToken::update_last_used($token_record->id, $ip); - $user_id = (int) $token_record->user_id; - if (\Escalated\Services\TicketAccess::enabled() && ! \Escalated\Services\TicketAccess::is_staff($user_id)) { - return null; - } - \Escalated\Services\TicketAccess::token_actor($request, $user_id); + TicketAccess::token_actor($request, $user_id); $this->token_failure = null; return $user_id; @@ -99,6 +115,10 @@ protected function token_error(): WP_Error return $this->error('escalated_forbidden', __('Insufficient permissions.', 'escalated'), 403); } + if ($this->token_failure === 'staff') { + return $this->error('escalated_forbidden', __('User no longer has agent access.', 'escalated'), 403); + } + return $this->error('escalated_unauthorized', __('Invalid or expired API token.', 'escalated'), 401); } @@ -138,6 +158,19 @@ public function token_permissions_check(WP_REST_Request $request) return $this->check_token_permission($request) === null ? $this->token_error() : true; } + /** + * Permission callback for the routes about the token's own account + * (auth/me, profile, refresh, logout): any valid token, including the + * customer tokens the password login gives non-staff users. + * + * @param WP_REST_Request $request The incoming request. + * @return bool|WP_Error True if authorized, WP_Error otherwise. + */ + public function self_token_permissions_check(WP_REST_Request $request) + { + return $this->check_token_permission($request, 'self') === null ? $this->token_error() : true; + } + /** * Permission callback for admin routes: a valid Bearer token with the * `admin` (or `*`) ability. An agent-only token is refused, as is an diff --git a/tests/Test_Api_Token_Owner.php b/tests/Test_Api_Token_Owner.php new file mode 100644 index 0000000..856af86 --- /dev/null +++ b/tests/Test_Api_Token_Owner.php @@ -0,0 +1,210 @@ +admin_id = self::factory()->user->create(['role' => 'administrator']); + + global $wp_rest_server; + $this->server = $wp_rest_server = new WP_REST_Server; + do_action('rest_api_init'); + } + + public function tear_down(): void + { + global $wp_rest_server; + $wp_rest_server = null; + parent::tear_down(); + } + + private function user(string $role, string $login): int + { + return self::factory()->user->create([ + 'role' => $role, + 'user_login' => $login, + 'user_pass' => 'secret123', + 'user_email' => $login.'@example.com', + ]); + } + + private function login(string $login): array + { + $request = new WP_REST_Request('POST', '/escalated/v1/auth/login'); + $request->set_param('username', $login); + $request->set_param('password', 'secret123'); + $response = $this->server->dispatch($request); + $this->assertSame(200, $response->get_status()); + + return $response->get_data(); + } + + private function token_for(int $user_id, array $abilities, ?string $expires_at = null): string + { + $created = ApiToken::create_token($user_id, 'test', $abilities); + if ($expires_at !== null) { + ApiToken::update($created['record']->id, ['expires_at' => $expires_at]); + } + + return $created['token']; + } + + private function call(string $method, string $route, string $token): WP_REST_Response + { + $request = new WP_REST_Request($method, '/escalated/v1/'.$route); + $request->set_header('Authorization', 'Bearer '.$token); + + return $this->server->dispatch($request); + } + + private function ticket(): object + { + return (new \Escalated\Services\TicketService)->create($this->admin_id, [ + 'subject' => 'Owner check', + 'description' => 'Ticket for token owner checks.', + 'priority' => 'medium', + ]); + } + + private function abilities(string $plain): array + { + return json_decode((string) ApiToken::find_by_token($plain)->abilities, true); + } + + public function test_login_gives_a_non_staff_user_a_customer_token(): void + { + $this->user('subscriber', 'sub1'); + + $token = $this->login('sub1')['token']; + + $this->assertSame(['customer'], $this->abilities($token)); + } + + public function test_login_gives_staff_their_staff_abilities(): void + { + $this->user('escalated_agent', 'agent1'); + $this->user('escalated_admin', 'admin1'); + + $this->assertSame(['agent'], $this->abilities($this->login('agent1')['token'])); + $this->assertSame(['*'], $this->abilities($this->login('admin1')['token'])); + } + + public function test_login_token_of_a_non_staff_user_cannot_read_or_delete_tickets(): void + { + $ticket = $this->ticket(); + $this->user('subscriber', 'sub2'); + $token = $this->login('sub2')['token']; + + $this->assertSame(403, $this->call('GET', 'tickets', $token)->get_status()); + $this->assertSame(403, $this->call('GET', 'tickets/'.$ticket->reference, $token)->get_status()); + $this->assertSame(403, $this->call('DELETE', 'tickets/'.$ticket->reference, $token)->get_status()); + $this->assertNotNull(Ticket::find((int) $ticket->id)); + } + + public function test_customer_token_still_reaches_its_own_account_routes(): void + { + $this->user('subscriber', 'sub3'); + $token = $this->login('sub3')['token']; + + $me = $this->call('GET', 'auth/me', $token); + $this->assertSame(200, $me->get_status()); + $this->assertSame('sub3@example.com', $me->get_data()['user']['email']); + + $refreshed = $this->call('POST', 'auth/refresh', $token); + $this->assertSame(200, $refreshed->get_status()); + $new_token = $refreshed->get_data()['token']; + $this->assertSame(['customer'], $this->abilities($new_token)); + $this->assertNull(ApiToken::find_by_token($token)); + + $this->assertSame(200, $this->call('POST', 'auth/logout', $new_token)->get_status()); + $this->assertNull(ApiToken::find_by_token($new_token)); + } + + public function test_full_token_of_a_non_staff_owner_is_refused_on_staff_routes(): void + { + $ticket = $this->ticket(); + $subscriber = $this->user('subscriber', 'sub4'); + $token = $this->token_for($subscriber, ['*']); + + $this->assertSame(403, $this->call('GET', 'tickets', $token)->get_status()); + $this->assertSame(403, $this->call('DELETE', 'tickets/'.$ticket->reference, $token)->get_status()); + $this->assertNotNull(Ticket::find((int) $ticket->id)); + } + + public function test_token_stops_working_on_staff_routes_once_the_owner_is_no_longer_staff(): void + { + $agent = $this->user('escalated_agent', 'agent2'); + $token = $this->login('agent2')['token']; + $this->assertSame(200, $this->call('GET', 'tickets', $token)->get_status()); + + (new WP_User($agent))->set_role('subscriber'); + + $this->assertSame(403, $this->call('GET', 'tickets', $token)->get_status()); + } + + public function test_an_agent_login_token_cannot_call_admin_routes(): void + { + $ticket = $this->ticket(); + $this->user('escalated_agent', 'agent3'); + $token = $this->login('agent3')['token']; + + $this->assertSame(200, $this->call('GET', 'tickets', $token)->get_status()); + $this->assertSame(403, $this->call('DELETE', 'tickets/'.$ticket->reference, $token)->get_status()); + $this->assertSame(403, $this->call('GET', 'automations', $token)->get_status()); + $this->assertNotNull(Ticket::find((int) $ticket->id)); + + $this->user('escalated_admin', 'admin3'); + $admin_token = $this->login('admin3')['token']; + $this->assertSame(200, $this->call('DELETE', 'tickets/'.$ticket->reference, $admin_token)->get_status()); + } + + public function test_refresh_keeps_the_token_abilities_and_expiry(): void + { + $expires = gmdate('Y-m-d H:i:s', time() + DAY_IN_SECONDS); + $token = $this->token_for($this->admin_id, ['agent'], $expires); + + $response = $this->call('POST', 'auth/refresh', $token); + + $this->assertSame(200, $response->get_status()); + $record = ApiToken::find_by_token($response->get_data()['token']); + $this->assertSame(['agent'], json_decode((string) $record->abilities, true)); + $this->assertSame($expires, $record->expires_at); + } + + public function test_each_request_counts_once_against_the_rate_limit(): void + { + Setting::set('api_rate_limit', 2); + $token = $this->token_for($this->admin_id, ['*']); + + $this->assertSame(200, $this->call('GET', 'tags', $token)->get_status()); + $this->assertSame(200, $this->call('GET', 'tags', $token)->get_status()); + $this->assertNotSame(200, $this->call('GET', 'tags', $token)->get_status()); + } + + public function test_expired_token_cannot_be_refreshed(): void + { + $token = $this->token_for($this->admin_id, ['*'], gmdate('Y-m-d H:i:s', time() - 60)); + + $this->assertSame(401, $this->call('POST', 'auth/refresh', $token)->get_status()); + } +} diff --git a/tests/Test_Ticket_Visibility.php b/tests/Test_Ticket_Visibility.php index e98abb1..3f5e173 100644 --- a/tests/Test_Ticket_Visibility.php +++ b/tests/Test_Ticket_Visibility.php @@ -281,7 +281,7 @@ public function test_anonymous_api_uses_token_owner_and_nonstaff_token_is_reject $this->assertSame([$this->visible], array_map('intval', array_column($response->get_data()['items'], 'id'))); $subscriber = self::factory()->user->create(['role' => 'subscriber']); Escalated::db()->update(Escalated::table('api_tokens'), ['user_id' => $subscriber], ['token' => hash('sha256', $this->token)]); - $this->assertSame(401, $this->server->dispatch($request)->get_status()); + $this->assertSame(403, $this->server->dispatch($request)->get_status()); } public function test_notifications_recheck_fresh_ticket_after_recipient_filter(): void