API Keys): each acts as an agent, with that * agent's role and client access, until the day it expires. A key is only * as good as its agent - a disabled, archived or role-less one turns every * call away (api/v1/enforce_api_rbac.php). * * Shared by admin/api_keys.php, admin/modals/api/* and admin/post/api_keys.php. */ /* One key - the row with its agent's name, picture, type, status, archived and role - or null. Admin > API Keys lists them the same way. */ function apiKeyRow($api_key_id) { global $mysqli; $api_key_id = intval($api_key_id); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT api_key_id, api_key_name, api_key_secret, api_key_created_at, api_key_expire, api_key_user_id, api_key_last_used_at, user_name, user_avatar, user_type, user_status, user_archived_at, user_role_id FROM api_keys LEFT JOIN users ON user_id = api_key_user_id WHERE api_key_id = $api_key_id")); return $row ?: null; } /* * The key a call to the API came with - '' for none (api/v1/validate_api_key.php). The * X-API-Key header first: web servers write the address of every request to their access * logs, headers not, so a key sent as ?api_key= is in those logs. A JSON body's api_key, or * the address's, still works for whatever was set up that way. */ function apiKeyFromRequest() { foreach ([$_SERVER['HTTP_X_API_KEY'] ?? null, $_POST['api_key'] ?? null, $_GET['api_key'] ?? null] as $key) { if (is_string($key) && trim($key) !== '') { return trim($key); } } return ''; } /* Did this call come with a key in its address (?api_key=)? Then the web server's access log has it. */ function apiKeyInAddress() { return is_string($_GET['api_key'] ?? null) && trim($_GET['api_key']) !== ''; } /* * Whether the API still takes a key in the address - Admin > Settings > Security. Installs * that had keys when the setting came (database 3.7.0) do, so nothing using them broke; others * don't. Read here rather than with every page's settings, so the API still answers before the * update that adds it - taking it, as it always did. */ function apiKeyInAddressAccepted() { global $mysqli; static $accepted = null; if ($accepted === null) { try { $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_api_key_in_address FROM settings WHERE company_id = 1")); $accepted = !empty($row[0]); } catch (Throwable $e) { $accepted = true; } } return $accepted; } /* Note that a key came in the address, for Admin > API Keys to flag - at most once a minute, not every call. */ function apiKeyNoteAddress($api_key_id) { global $mysqli; try { mysqli_query($mysqli, "UPDATE api_keys SET api_key_address_at = NOW() WHERE api_key_id = " . intval($api_key_id) . " AND (api_key_address_at IS NULL OR api_key_address_at < NOW() - INTERVAL 1 MINUTE)"); } catch (Throwable $e) { // Before the update that adds it } } /* Has this key expired? It works until the start of its expiry date. */ function apiKeyExpired(array $row) { return (string) $row['api_key_expire'] <= date('Y-m-d'); } /* * Why a key's agent turns every call away - '' when they don't: no agent, * one who is disabled or archived, or one with no role. $role is their * roleRow() (or null). */ function apiKeyAgentProblem(array $row, $role) { $name = trim(str_replace(' (archived)', '', (string) ($row['user_name'] ?? ''))); if (!intval($row['api_key_user_id']) || $row['user_name'] === null || intval($row['user_type']) !== 1) { return 'it acts as nobody - pick an agent'; } if ($row['user_archived_at']) { return "$name is archived"; } if (intval($row['user_status']) !== 1) { return "$name is disabled"; } if (!$role) { return "$name has no role"; } return ''; } /* * A key's state as a pill - whether it works, and until when. Expired; * won't work because of its agent; expiring within two weeks; or working. * HTML. */ function apiKeyStatePill(array $row, $role) { $expire = date('M j, Y', strtotime($row['api_key_expire'])); if (apiKeyExpired($row)) { return 'Expired'; } $problem = apiKeyAgentProblem($row, $role); if ($problem !== '') { return 'Won\'t work - ' . escapeHtml($problem) . ''; } $days = (int) floor((strtotime($row['api_key_expire']) - strtotime(date('Y-m-d'))) / 86400); if ($days <= 14) { return 'Expires in ' . $days . ' day' . ($days === 1 ? '' : 's') . ''; } return 'Works until ' . $expire . ''; } /* The agents a key can act as - active ones, by name: [user_id => row with role_id]. */ function apiKeyAgents() { global $mysqli; $agents = []; $sql = mysqli_query($mysqli, "SELECT user_id, user_name, user_avatar, user_role_id FROM users WHERE user_type = 1 AND user_status = 1 AND user_archived_at IS NULL ORDER BY user_name ASC"); while ($row = mysqli_fetch_assoc($sql)) { $agents[intval($row['user_id'])] = $row; } return $agents; } /* * The New Key / Edit Key window's fields, checked - [fields, error]. * fields: name, expire (Y-m-d, after today - or the day it already has, so * an expired key can be renamed and stay expired) and user_id (an active * agent). */ function apiKeyFromInput(array $in, $current_expire = '') { $name = trim(mb_substr(strip_tags((string) ($in['name'] ?? '')), 0, 255)); if ($name === '') { return [null, 'A key needs a name.']; } $expire = (string) ($in['expire'] ?? ''); $date = DateTime::createFromFormat('!Y-m-d', $expire); if (!$date || $date->format('Y-m-d') !== $expire || $expire > '2999-12-31' || ($expire <= date('Y-m-d') && $expire !== (string) $current_expire)) { return [null, 'Pick the day it stops working - after today.']; } $user_id = intval($in['run_as_user'] ?? 0); if (!isset(apiKeyAgents()[$user_id])) { return [null, 'Pick an active agent for it to act as.']; } return [['name' => $name, 'expire' => $expire, 'user_id' => $user_id], '']; } /* * The "Act as" picker of the key windows, with what each agent can open * shown under it for the one picked (js in api_key_form). $selected: the * user_id, 0 for none. */ function apiKeyAgentFieldHtml($selected = 0) { $selected = intval($selected); $agents = apiKeyAgents(); $roles = roleRows(); $access = userClientAccess(array_keys($agents)); ob_start(); ?>