Richiesta: "AI deve sapere i contenuti dei dati a cui ha accesso l'utente". - AIService::orgDataSnapshotBlock($orgId): aggregati LIVE dell'org (compliance score, rischi aperti per livello + top 5, incidenti aperti, asset attivi/rilevanti NIS2, fornitori critici scoperti, NC aperte, formazione, policy per stato). Query con colonne reali (riuso DashboardController), ognuna in try/catch (degrada, non rompe). - Iniettato in askWithRag SOLO se org_data_ok. - SICUREZZA multi-tenant: AiController verifica membership in user_organizations (super_admin bypassa) → org_data_ok; scope rigoroso organization_id → niente leak cross-org da X-Organization-Id falsificato. PRIVACY: niente nome/fatturato (anonimizz.). Smoke: con membership ARIA cita score 80% + 14 rischi (org 996003); senza membership nega l'accesso ai dati. php-fpm reload. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
101 lines
4.0 KiB
PHP
101 lines
4.0 KiB
PHP
<?php
|
|
/**
|
|
* NIS2 Agile - AI Assistant Controller (ARIA)
|
|
*
|
|
* Endpoint dell'assistente conversazionale AI usato dal FAB "ARIA" (common.js).
|
|
* Usa AIService::askWithRag() -> RAG su Knowledge Base (incl. fonti normative
|
|
* certe ingerite, scope SYSTEM) + grounding con citazioni.
|
|
*/
|
|
|
|
require_once __DIR__ . '/BaseController.php';
|
|
require_once __DIR__ . '/../services/AIService.php';
|
|
require_once __DIR__ . '/../services/RateLimitService.php';
|
|
|
|
class AiController extends BaseController
|
|
{
|
|
/**
|
|
* POST /api/ai/ask
|
|
* Body: { question: string, history?: array }
|
|
* Risposta: { answer, sources, rag_used }
|
|
*/
|
|
public function ask(): void
|
|
{
|
|
$this->requireAuth();
|
|
|
|
$question = trim((string) $this->getParam('question', ''));
|
|
if ($question === '') {
|
|
$this->jsonError('Domanda mancante', 422, 'QUESTION_REQUIRED');
|
|
}
|
|
if (mb_strlen($question) > 2000) {
|
|
$this->jsonError('Domanda troppo lunga (max 2000 caratteri)', 422, 'QUESTION_TOO_LONG');
|
|
}
|
|
|
|
// Rate limit per utente (riusa la soglia AI configurata)
|
|
$userId = $this->getCurrentUserId();
|
|
$rlKey = "ai_ask:{$userId}";
|
|
if (defined('RATE_LIMIT_AI')) {
|
|
RateLimitService::check($rlKey, RATE_LIMIT_AI);
|
|
RateLimitService::increment($rlKey);
|
|
}
|
|
|
|
$user = $this->getCurrentUser() ?? [];
|
|
// Pagina corrente (facoltativa) inviata dal frontend, per dare ad ARIA
|
|
// contesto sulla schermata da cui l'utente sta scrivendo (ticket #424).
|
|
$page = mb_substr(trim((string) $this->getParam('page', '')), 0, 120);
|
|
// pageId canonico + testo dell'help "?" della pagina (allineamento ARIA↔Help).
|
|
$pageId = mb_substr(trim((string) $this->getParam('page_id', '')), 0, 40);
|
|
$pageHelp = mb_substr(trim((string) $this->getParam('page_help', '')), 0, 2500);
|
|
$userContext = [
|
|
'user_id' => $userId,
|
|
'organization_id' => $this->getCurrentOrgId(), // può essere null
|
|
'consulting_firm_id' => $user['consulting_firm_id'] ?? null,
|
|
'page' => $page,
|
|
'page_id' => $pageId,
|
|
'page_help' => $pageHelp,
|
|
];
|
|
|
|
// Membership verificata → ARIA può iniettare lo snapshot DATI dell'org
|
|
// (anti-spoof X-Organization-Id; super_admin bypassa, come da modello ruoli).
|
|
$orgId = (int) ($userContext['organization_id'] ?? 0);
|
|
$userContext['org_data_ok'] = false;
|
|
if ($orgId > 0) {
|
|
if (($user['role'] ?? '') === 'super_admin') {
|
|
$userContext['org_data_ok'] = true;
|
|
} else {
|
|
$member = Database::fetchOne(
|
|
'SELECT 1 FROM user_organizations WHERE user_id = ? AND organization_id = ?',
|
|
[$userId, $orgId]
|
|
);
|
|
$userContext['org_data_ok'] = (bool) $member;
|
|
}
|
|
}
|
|
|
|
try {
|
|
$aiService = new AIService();
|
|
$result = $aiService->askWithRag($question, $userContext);
|
|
|
|
// Audit best-effort (non blocca la risposta)
|
|
try {
|
|
$aiService->logInteraction(
|
|
(int) ($userContext['organization_id'] ?? 0),
|
|
(int) ($userId ?? 0),
|
|
'qa',
|
|
mb_substr($question, 0, 200),
|
|
mb_substr((string) ($result['answer'] ?? ''), 0, 500),
|
|
);
|
|
} catch (Throwable $e) {
|
|
error_log('[AiController::ask] logInteraction failed: ' . $e->getMessage());
|
|
}
|
|
|
|
$this->jsonSuccess([
|
|
'answer' => $result['answer'] ?? '',
|
|
'sources' => $result['sources'] ?? [],
|
|
'rag_used' => $result['rag_used'] ?? false,
|
|
]);
|
|
} catch (Throwable $e) {
|
|
error_log('[AiController::ask] ' . $e->getMessage());
|
|
$this->jsonError('Assistente AI non disponibile in questo momento', 503, 'AI_UNAVAILABLE');
|
|
}
|
|
}
|
|
}
|