Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 13 additions & 1 deletion docs/access-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
95 changes: 76 additions & 19 deletions includes/Api/class-auth-controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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]) {
Expand Down Expand Up @@ -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)]);
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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'];
}

/**
Expand All @@ -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,
Expand Down Expand Up @@ -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));
}
}
55 changes: 44 additions & 11 deletions includes/Api/class-base-controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
*/
Expand All @@ -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
Expand All @@ -64,26 +67,39 @@ 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;
}

// Update last used timestamp.
$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;
Expand All @@ -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);
}

Expand Down Expand Up @@ -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
Expand Down
Loading