feat: integrate Bugtracker module, UpdateService enhancements & Token hierarchy

This commit is contained in:
Deploymentcenter Bot
2026-08-06 12:45:58 +02:00
parent 70b35f7b8b
commit d71f90cdfc
28 changed files with 3494 additions and 32 deletions
@@ -0,0 +1,9 @@
# Bugtracker Protected Management API (.htaccess Security Layer)
# Allows authenticated API token requests or session-authenticated admin users
Satisfy Any
Allow from all
<IfModule mod_authz_core.c>
Require all granted
</IfModule>
+193
View File
@@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../../../../../src/Core/Auth.php';
require_once __DIR__ . '/../../../../../src/Core/Db.php';
require_once __DIR__ . '/../../../../../src/Core/TokenManager.php';
require_once __DIR__ . '/../../../../../src/Modules/Bugtracker/BugRepo.php';
use Deploymentcenter\Core\Auth;
use Deploymentcenter\Core\Db;
use Deploymentcenter\Core\TokenManager;
use Deploymentcenter\Modules\Bugtracker\BugRepo;
header('Content-Type: application/json; charset=utf-8');
try {
$config = require __DIR__ . '/../../../../../config/config.php';
$db = Db::connect($config['db']);
// Authenticate Request (Session OR Token)
$isAuthenticated = false;
$authorName = 'admin';
if (Auth::isLoggedIn()) {
$isAuthenticated = true;
$authorName = $_SESSION['dc_username'] ?? 'admin';
} else {
$headers = getallheaders();
$token = $headers['X-Agent-Token'] ?? $headers['x-agent-token'] ?? null;
if (!$token && !empty($headers['Authorization'])) {
if (preg_match('/Bearer\s+(.+)/i', $headers['Authorization'], $matches)) {
$token = trim($matches[1]);
}
}
if ($token) {
$tokenMgr = new TokenManager($db);
$tokenInfo = $tokenMgr->validateToken($token, 'bugtracker:manage');
if ($tokenInfo) {
$isAuthenticated = true;
$authorName = 'agent:' . ($tokenInfo['name'] ?? $tokenInfo['token_id']);
}
}
}
if (!$isAuthenticated) {
http_response_code(401);
echo json_encode(['status' => 'error', 'message' => 'Unauthorized: Valid Session or Bearer Token with scope bugtracker:manage required']);
exit;
}
$repo = new BugRepo($db);
$uri = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true) ?: $_POST;
// Parse sub-route if any
$path = parse_url($uri, PHP_URL_PATH);
$action = $_GET['action'] ?? null;
// Handle Item Detail/Comment/Resolve via ID in URL or query params
$itemId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$itemId && preg_match('/\/manage\/items\/(\d+)/', $path, $m)) {
$itemId = (int)$m[1];
}
// Sub-actions
if ($action === 'stats' || str_ends_with($path, '/stats')) {
echo json_encode(['status' => 'success', 'stats' => $repo->getStats()], JSON_PRETTY_PRINT);
exit;
}
if ($action === 'resolve' || str_contains($path, '/resolve')) {
if ($method !== 'POST') {
http_response_code(405);
echo json_encode(['status' => 'error', 'message' => 'POST required for resolve']);
exit;
}
if (!$itemId) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Missing item ID']);
exit;
}
$build = !empty($input['resolved_in_build']) ? trim($input['resolved_in_build']) : 'v1.0.0';
$notes = !empty($input['resolution_notes']) ? trim($input['resolution_notes']) : null;
$author = !empty($input['author']) ? trim($input['author']) : $authorName;
$ok = $repo->resolveItem($itemId, $build, $notes, $author);
if ($ok) {
echo json_encode(['status' => 'success', 'message' => "Item #{$itemId} resolved in build {$build}"]);
} else {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Failed to resolve item']);
}
exit;
}
if ($action === 'comment' || str_contains($path, '/comments')) {
if ($method !== 'POST') {
http_response_code(405);
echo json_encode(['status' => 'error', 'message' => 'POST required for comment']);
exit;
}
if (!$itemId) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Missing item ID']);
exit;
}
$comment = !empty($input['comment']) ? trim($input['comment']) : '';
if (empty($comment)) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Comment cannot be empty']);
exit;
}
$author = !empty($input['author']) ? trim($input['author']) : $authorName;
$actionTaken = !empty($input['action_taken']) ? trim($input['action_taken']) : 'commented';
$meta = isset($input['meta']) && is_array($input['meta']) ? $input['meta'] : null;
$comm = $repo->addComment($itemId, $author, $comment, $actionTaken, $meta);
echo json_encode(['status' => 'success', 'comment' => $comm]);
exit;
}
if ($action === 'status' || str_contains($path, '/status')) {
if ($method !== 'POST') {
http_response_code(405);
echo json_encode(['status' => 'error', 'message' => 'POST required for status change']);
exit;
}
if (!$itemId) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Missing item ID']);
exit;
}
$status = !empty($input['status']) ? trim($input['status']) : 'open';
$notes = !empty($input['notes']) ? trim($input['notes']) : null;
$author = !empty($input['author']) ? trim($input['author']) : $authorName;
$ok = $repo->updateStatus($itemId, $status, $notes, $author);
if ($ok) {
echo json_encode(['status' => 'success', 'message' => "Status for #{$itemId} updated to {$status}"]);
} else {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid status']);
}
exit;
}
// Detail View of a single item
if ($itemId > 0 && $method === 'GET') {
$details = $repo->getItemDetails($itemId);
if (!$details) {
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Item not found']);
exit;
}
echo json_encode(['status' => 'success', 'item' => $details], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
exit;
}
// Default: List Items
$filters = [
'project_slug' => $_GET['project_slug'] ?? $_GET['project'] ?? 'all',
'environment' => $_GET['environment'] ?? $_GET['env'] ?? 'all',
'type' => $_GET['type'] ?? 'all',
'status' => $_GET['status'] ?? 'all',
'severity' => $_GET['severity'] ?? 'all',
'search' => $_GET['search'] ?? $_GET['q'] ?? '',
];
$items = $repo->getItems($filters);
echo json_encode([
'status' => 'success',
'count' => count($items),
'filters' => $filters,
'items' => $items,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
} catch (Throwable $t) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Manage API Error: ' . $t->getMessage()]);
}
+82
View File
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../../../../src/Core/Db.php';
require_once __DIR__ . '/../../../../src/Core/TokenManager.php';
require_once __DIR__ . '/../../../../src/Modules/Bugtracker/BugRepo.php';
use Deploymentcenter\Core\Db;
use Deploymentcenter\Core\TokenManager;
use Deploymentcenter\Modules\Bugtracker\BugRepo;
header('Content-Type: application/json; charset=utf-8');
// Allow CORS for public ingest
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Agent-Token');
header('Access-Control-Allow-Methods: POST, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['status' => 'error', 'message' => 'Method Not Allowed']);
exit;
}
$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true) ?: $_POST;
if (empty($data)) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Empty request body or invalid JSON']);
exit;
}
try {
$config = require __DIR__ . '/../../../../config/config.php';
$db = Db::connect($config['db']);
// Optional Token Verification (if provided)
$headers = getallheaders();
$token = $headers['X-Agent-Token'] ?? $headers['x-agent-token'] ?? null;
if (!$token && !empty($headers['Authorization'])) {
if (preg_match('/Bearer\s+(.+)/i', $headers['Authorization'], $matches)) {
$token = trim($matches[1]);
}
}
if ($token) {
$tokenMgr = new TokenManager($db);
$valid = $tokenMgr->validateToken($token, 'bugtracker:report', $data['environment'] ?? null);
if (!$valid) {
http_response_code(401);
echo json_encode(['status' => 'error', 'message' => 'Invalid, revoked or unauthorized Token for bugtracker:report']);
exit;
}
}
$repo = new BugRepo($db);
$result = $repo->reportItem($data);
echo json_encode([
'status' => 'success',
'item_id' => $result['id'],
'is_new' => $result['is_new'],
'occurrence_count' => $result['occurrence_count'],
'error_hash' => $result['error_hash'],
'type' => $result['type'],
'environment' => $result['environment'],
'message' => $result['is_new']
? ($result['type'] === 'bug' ? 'New bug reported successfully.' : 'New feature request submitted.')
: 'Recurring bug count updated.',
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
} catch (Throwable $t) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Failed to log report: ' . $t->getMessage()]);
}
+77
View File
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../../../../src/Core/Db.php';
require_once __DIR__ . '/../../../../src/Core/TokenManager.php';
use Deploymentcenter\Core\Db;
use Deploymentcenter\Core\TokenManager;
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['status' => 'error', 'message' => 'Method Not Allowed']);
exit;
}
// Extract Master Token from Headers
$headers = getallheaders();
$masterToken = $headers['X-Master-Token'] ?? $headers['x-master-token'] ?? null;
if (!$masterToken && !empty($headers['Authorization'])) {
if (preg_match('/Bearer\s+(.+)/i', $headers['Authorization'], $matches)) {
$masterToken = trim($matches[1]);
}
}
$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true) ?: $_POST;
if (!$masterToken && !empty($data['master_token'])) {
$masterToken = trim($data['master_token']);
}
if (!$masterToken) {
http_response_code(401);
echo json_encode(['status' => 'error', 'message' => 'Missing Master Token in X-Master-Token header or Authorization Bearer header']);
exit;
}
try {
$config = require __DIR__ . '/../../../../config/config.php';
$db = Db::connect($config['db']);
$tokenMgr = new TokenManager($db);
$name = !empty($data['client_name']) ? trim($data['client_name']) : (!empty($data['name']) ? trim($data['name']) : 'Auto-Provisioned Agent Sub-Token');
$instanceIdentity = !empty($data['instance_id']) ? trim($data['instance_id']) : (!empty($data['hostname']) ? trim($data['hostname']) : null);
$requestedScopes = isset($data['scopes']) && is_array($data['scopes']) ? $data['scopes'] : [];
$environment = !empty($data['environment']) ? trim($data['environment']) : 'all';
$subTokenData = $tokenMgr->provisionSubToken(
$masterToken,
$name,
$instanceIdentity,
$requestedScopes,
$environment
);
echo json_encode([
'status' => 'success',
'sub_token' => $subTokenData['raw_token'],
'token_id' => $subTokenData['token_id'],
'name' => $subTokenData['name'],
'scopes' => $subTokenData['scopes'],
'environment' => $subTokenData['environment'],
'type' => 'sub',
'created_at' => date('Y-m-d H:i:s'),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
} catch (InvalidArgumentException $e) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
} catch (Throwable $t) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Internal server error: ' . $t->getMessage()]);
}
+39 -2
View File
@@ -25,15 +25,51 @@ try {
$updateMgr = new UpdateManager($pdo);
// Read JSON body for POST requests if available
$inputData = [];
if ($method === 'POST') {
$raw = file_get_contents('php://input');
if (!empty($raw)) {
$inputData = json_decode($raw, true) ?? [];
}
}
$action = $_REQUEST['action'] ?? $inputData['action'] ?? '';
// Action: Publish Release (from Packager CLI)
if ($action === 'publish_release' && $method === 'POST') {
$product = $inputData['product_slug'] ?? $_POST['product_slug'] ?? '';
$version = $inputData['version'] ?? $_POST['version'] ?? '';
$channel = $inputData['channel'] ?? $_POST['channel'] ?? 'prod';
$url = $inputData['download_url'] ?? $_POST['download_url'] ?? '';
$hash = $inputData['sha256_hash'] ?? $_POST['sha256_hash'] ?? null;
$gitCommit = $inputData['git_commit'] ?? $_POST['git_commit'] ?? null;
$sizeBytes = (int)($inputData['size_bytes'] ?? $_POST['size_bytes'] ?? 0);
$notes = $inputData['release_notes'] ?? $_POST['release_notes'] ?? null;
$isCritical= !empty($inputData['is_critical']) || !empty($_POST['is_critical']);
if (empty($product) || empty($version) || empty($url)) {
sendResponse(['error' => 'Bad Request', 'message' => 'Missing required fields: product_slug, version, download_url'], 400);
}
$ok = $updateMgr->addRelease($product, $version, $channel, $notes, $url, $hash, $gitCommit, $sizeBytes, null, $isCritical);
if ($ok) {
sendResponse(['status' => 'success', 'message' => "Release v{$version} published for {$product} ({$channel})."]);
} else {
sendResponse(['error' => 'Database Error', 'message' => 'Failed to store release.'], 500);
}
}
if (str_ends_with($uri, '/check') && ($method === 'GET' || $method === 'POST')) {
$product = $_REQUEST['product'] ?? $_REQUEST['product_slug'] ?? '';
$version = $_REQUEST['version'] ?? $_REQUEST['current_version'] ?? '0.0.0';
$channel = $_REQUEST['channel'] ?? 'prod';
if (empty($product)) {
sendResponse(['error' => 'Bad Request', 'message' => 'Parameter "product" is required.'], 400);
}
$latest = $updateMgr->checkUpdate($product, $version);
$latest = $updateMgr->checkUpdate($product, $version, $channel);
if ($latest) {
sendResponse([
'update_available' => true,
@@ -49,7 +85,8 @@ try {
if (str_ends_with($uri, '/releases') && $method === 'GET') {
$product = $_GET['product'] ?? null;
$releases = $updateMgr->getReleases($product);
$channel = $_GET['channel'] ?? null;
$releases = $updateMgr->getReleases($product, $channel);
sendResponse(['count' => count($releases), 'releases' => $releases]);
}