Files
tinker_tickets/api/generate_api_key.php
T
jaredandClaude Sonnet 5 6609320c83 Restrict API keys to public-visibility tickets by default (#70)
api/tickets_api.php (both the single-ticket read and the list/triage
path) bypassed ticket visibility entirely for any 'read'-scope key,
regardless of who it was issued to or what it was for — any key got
blanket read access to Confidential and Internal ticket titles,
descriptions, and comments, with no way to scope a key more narrowly.

Added see_all_visibility to api_keys (migration 006), defaulting to
false for both new and existing keys — the prior blanket-access
behavior is what's being restricted here, so unlike scope's own
un-migrated-database fallback (which defaults toward preserving old
behavior), a missing/null value here defaults to the new, restrictive
one. An admin can opt a specific key in via a new checkbox in the API
Key Management UI when it genuinely needs the full queue.

tickets_api.php now builds a synthetic "no special access" user and
runs it through TicketModel's existing per-user visibility plumbing
(getVisibilityFilter/canUserAccessTicket) instead of a separate SQL
path, so this stays in lockstep with however visibility rules evolve
for real users. That synthetic user_id is -1, not 0: testing surfaced
that canUserAccessTicket()'s confidential-ticket check does a PHP-level
(int) cast, and (int)null === 0, so an unassigned confidential ticket's
NULL assigned_to would otherwise false-positive-match a user_id of 0.

Verified against real MariaDB with public/confidential/internal test
tickets: a public-only-scoped key's list only returns the public
ticket, and canUserAccessTicket() correctly returns false for both the
confidential ticket (unassigned, then reassigned to a real user — both
cases) and the internal one; a see_all_visibility key sees all three,
unchanged from the prior behavior. Also verified createKey()/
validateKey()'s default-false and explicit-true paths round-trip
correctly through the real DB.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117oBw2jN4kALYeS8HPq4zV
2026-09-12 01:17:53 -04:00

159 lines
5.0 KiB
PHP

<?php
// API endpoint for generating API keys (Admin only)
require_once dirname(__DIR__) . '/helpers/ErrorHandler.php';
ErrorHandler::init();
// Apply rate limiting
require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php';
RateLimitMiddleware::apply('api');
ob_start();
try {
// Load config
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/helpers/Database.php';
// Load models
require_once dirname(__DIR__) . '/models/ApiKeyModel.php';
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
// Check authentication via session
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
http_response_code(401);
throw new Exception("Authentication required");
}
// Check admin privileges
if (!isset($_SESSION['user']['is_admin']) || !$_SESSION['user']['is_admin']) {
http_response_code(403);
throw new Exception("Admin privileges required");
}
// CSRF Protection
require_once dirname(__DIR__) . '/middleware/CsrfMiddleware.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$csrfToken = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (!CsrfMiddleware::validateToken($csrfToken)) {
ob_end_clean();
http_response_code(403);
header('Content-Type: application/json');
echo json_encode([
'success' => false,
'error' => 'Invalid CSRF token',
'csrf_token' => CsrfMiddleware::getToken()
]);
exit;
}
}
// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
throw new Exception("Method not allowed");
}
// Get request data
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
http_response_code(400);
throw new Exception("Invalid request data");
}
$keyName = trim($input['key_name'] ?? '');
$expiresInDays = $input['expires_in_days'] ?? null;
$scope = $input['scope'] ?? 'read_write';
$seeAllVisibility = !empty($input['see_all_visibility']);
if (empty($keyName)) {
http_response_code(400);
throw new Exception("Key name is required");
}
// Validate scope — only the two known values are allowed
if (!in_array($scope, ['read', 'read_write'], true)) {
http_response_code(400);
throw new Exception("Invalid scope: must be 'read' or 'read_write'");
}
if (strlen($keyName) > 100) {
http_response_code(400);
throw new Exception("Key name must be 100 characters or less");
}
// Validate expires_in_days if provided
if ($expiresInDays !== null && $expiresInDays !== '') {
$expiresInDays = (int)$expiresInDays;
if ($expiresInDays < 1 || $expiresInDays > 3650) {
http_response_code(400);
throw new Exception("Expiration must be between 1 and 3650 days");
}
} else {
$expiresInDays = null;
}
// Use centralized database connection
$conn = Database::getConnection();
// Generate API key
$apiKeyModel = new ApiKeyModel($conn);
$result = $apiKeyModel->createKey($keyName, $_SESSION['user']['user_id'], $expiresInDays, $scope, $seeAllVisibility);
if (!$result['success']) {
throw new Exception($result['error'] ?? "Failed to generate API key");
}
// Log the action
$auditLog = new AuditLogModel($conn);
$auditLog->log(
$_SESSION['user']['user_id'],
'create',
'api_key',
$result['key_id'],
['key_name' => $keyName, 'expires_in_days' => $expiresInDays, 'scope' => $scope, 'see_all_visibility' => $seeAllVisibility]
);
// Clear output buffer
ob_end_clean();
// Return success with the plaintext key (shown only once)
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'api_key' => $result['api_key'],
'key_prefix' => $result['key_prefix'],
'key_id' => $result['key_id'],
'scope' => $result['scope'],
'see_all_visibility' => $result['see_all_visibility'],
'expires_at' => $result['expires_at']
]);
} catch (Exception $e) {
ob_end_clean();
header('Content-Type: application/json');
// Preserve any specific status set before the throw (401/403/400/...);
// only fall back to 500 when nothing more specific was set.
$code = http_response_code();
if (!is_int($code) || $code < 400) {
$code = 500;
}
http_response_code($code);
if ($code >= 500) {
error_log("Generate API key error: " . $e->getMessage());
echo json_encode([
'success' => false,
'error' => 'An internal error occurred'
]);
} else {
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}
}