Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c01a2f297 |
@@ -1796,6 +1796,76 @@ systemctl is-active tsj-guardian-bot tsj-guardian-watchdog gost-tg
|
||||
- требует laptop-only path или интерактивный shell;
|
||||
- выводит секреты в stdout/journald/report.
|
||||
|
||||
## 12a. DetMir hardline resilience deltas
|
||||
|
||||
2026-06-24 Hayabusa poison-package isolation:
|
||||
|
||||
- `aw-hayabusa-autoprocess-rust` validates drop zip packages before `accept`;
|
||||
- corrupt/empty/unsafe packages and invalid sidecars are quarantined under
|
||||
`/opt/hayabusa/quarantine/drop/...` with `reason.json`;
|
||||
- `aw-hayabusa process-inbox` isolates failed incoming packages under
|
||||
`/opt/hayabusa/quarantine/incoming/...` and continues with the rest of the
|
||||
queue;
|
||||
- one poison zip no longer blocks the whole Hayabusa batch or trips systemd
|
||||
start-limit by itself;
|
||||
- verification: `bash -n aw-server/hayabusa/aw-hayabusa.sh` and
|
||||
`cargo test -p hayabusa-tools` passed locally;
|
||||
- live rollout on AW server completed on 2026-06-24 with backups, `doctor` OK,
|
||||
isolated empty-drop dry-run OK, production `incoming_zip=0`, `DROP_COUNT=0`,
|
||||
`staged_dirs=0`; stale 2026-06-20 staging residue moved to quarantine with
|
||||
`reason.json`.
|
||||
|
||||
2026-06-24 Windows collector guard child watchdog:
|
||||
|
||||
- `AWatchRusCollectorGuardService.cs` now watches the child process via
|
||||
`Process.Exited`;
|
||||
- unexpected child exit triggers bounded restart inside the service wrapper;
|
||||
- restart budget exhaustion exits the service with a non-zero code so SCM
|
||||
recovery can restart the wrapper instead of leaving `running/no child`;
|
||||
- `install-collector-guard-service.ps1` sets `sc.exe failureflag <service> 1`;
|
||||
- runtime contract is unchanged: Rust collector guard remains the preferred
|
||||
child, PowerShell guard remains fallback, and `ActivityWatch Recovery` remains
|
||||
enabled as bootstrap fallback;
|
||||
- local static verification passed: C# wrapper compiled through PowerShell
|
||||
`Add-Type`; PowerShell installer parsed through the PowerShell parser;
|
||||
- live rollout on RDP completed on 2026-06-24 with backup, reinstall in
|
||||
`enforce` mode, `failureflag` enabled, controlled child-kill fault injection,
|
||||
and final validation `service=Running`, `child_count=1`, latest Rust guard
|
||||
cycle `status=ok`.
|
||||
|
||||
2026-06-24 DetMir contour resilience check:
|
||||
|
||||
- added `scripts/detmir_resilience_check.sh`;
|
||||
- repo mode verifies hardening presence for Hayabusa poison quarantine, Windows
|
||||
child watchdog, SCM `failureflag`, and resilience docs;
|
||||
- live mode is read-only and checks local AW service/API state, failed systemd
|
||||
units, Hayabusa queues/quarantine, and AW SQLite DB/WAL size thresholds;
|
||||
- `scripts/run_awatch_contour_check.sh` can include it with
|
||||
`RUN_RESILIENCE_CHECK=1` and `RESILIENCE_CHECK_MODE=repo|live|all`;
|
||||
- strict secret mode (`DETMIR_RESILIENCE_STRICT_SECRETS=1`) fails literal
|
||||
Ansible password assignments without printing secret values;
|
||||
- local verification: shell syntax passed, repo mode passed with `ok=15`,
|
||||
`fail=0`, and one WARN for literal private inventory password assignments;
|
||||
- live AW server verification passed with `ok=9`, `fail=0`; one expected WARN
|
||||
remains for the deliberate quarantine `reason.json` created during stale
|
||||
staging cleanup.
|
||||
|
||||
2026-06-24 live healthd wrapper timeout correction:
|
||||
|
||||
- `aw-rus-healthd-rust` had a 20 second default wrapper timeout for
|
||||
`/usr/local/bin/aw-health-check` and `/usr/local/bin/dlp-health-check --json`;
|
||||
- under concurrent contour checks the DLP health command could exceed that
|
||||
limit, be killed, and leave partial stdout that healthd reported as
|
||||
`invalid JSON output`;
|
||||
- production `/etc/activitywatch/aw-server.env` now sets
|
||||
`AW_RUS_HEALTH_WRAPPER_TIMEOUT_SECONDS=90`, still below the service
|
||||
`TimeoutStartSec=180`;
|
||||
- `aw-server/aw-server.env.example` carries the same value so redeploys do not
|
||||
restore the false-fail default;
|
||||
- live verification after the change: `aw-rus-healthd.service` finished with
|
||||
`status=0/SUCCESS`, `fail=0`, while AW API, Worktime API and DLP health were
|
||||
independently reachable.
|
||||
|
||||
## 13. Рабочий принцип
|
||||
|
||||
Правильный перенос на Rust - это не переписывание строк один-в-один.
|
||||
|
||||
@@ -97,6 +97,17 @@ body.security-mode .demo-button.is-active {
|
||||
color: var(--link);
|
||||
}
|
||||
|
||||
.compact-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.security-findings-table td {
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.shell {
|
||||
max-width: none;
|
||||
min-width: 0;
|
||||
|
||||
@@ -9,6 +9,7 @@ const state = {
|
||||
cases: null,
|
||||
kpiExplain: null,
|
||||
pendingScrollSelector: null,
|
||||
refreshSeq: 0,
|
||||
load: {
|
||||
status: "LOADING",
|
||||
stage: "Инициализация портала",
|
||||
@@ -81,7 +82,7 @@ function apiBase() {
|
||||
|
||||
function apiRole() {
|
||||
if (state.tab === "employees" || state.tab === "departments") return "manager";
|
||||
if (state.tab === "owner" || state.tab === "perimeter") return "security";
|
||||
if (state.tab === "owner" || state.tab === "perimeter" || state.tab === "securityFindings") return "security";
|
||||
if (state.tab === "incidents") return "forensics";
|
||||
if (state.tab === "settings") return "admin";
|
||||
const mode = currentViewMode();
|
||||
@@ -104,6 +105,22 @@ async function loadJson(path) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function loadJsonWithTimeout(path, timeoutMs) {
|
||||
const controller = new AbortController();
|
||||
const timer = window.setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const response = await fetch(`${apiBase()}${path}`, {
|
||||
cache: "no-store",
|
||||
headers: roleHeaders(),
|
||||
signal: controller.signal
|
||||
});
|
||||
if (!response.ok) throw new Error(`${path}: HTTP ${response.status}`);
|
||||
return response.json();
|
||||
} finally {
|
||||
window.clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async function postJson(path, payload) {
|
||||
const response = await fetch(`${apiBase()}${path}`, {
|
||||
method: "POST",
|
||||
@@ -114,6 +131,19 @@ async function postJson(path, payload) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function fallbackSummary(error) {
|
||||
return {
|
||||
operator_ok: false,
|
||||
severity: "STALE",
|
||||
blocks: {
|
||||
collection: {
|
||||
status: "STALE",
|
||||
text: `Портал прогревает первичный срез; быстрый summary временно недоступен: ${error?.message || "timeout"}`
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function statusClass(status) {
|
||||
const s = String(status || "UNKNOWN").toLowerCase();
|
||||
if (s === "ok" || s === "ready" || s === "true" || s === "normal" || s === "low" || s === "false_positive" || s === "resolved") return "status-ok";
|
||||
@@ -480,6 +510,9 @@ function hasTabData(tab, payload) {
|
||||
if (tab === "owner" || tab === "perimeter") {
|
||||
return Boolean(payload.data && Object.keys(payload.data).length > 0);
|
||||
}
|
||||
if (tab === "securityFindings") {
|
||||
return Boolean(payload.data && Object.keys(payload.data).length > 0);
|
||||
}
|
||||
if (tab === "incidents") {
|
||||
return (Array.isArray(payload.data?.incidents) && payload.data.incidents.length > 0)
|
||||
|| (Array.isArray(payload.data?.reports?.risk_incident_candidates) && payload.data.reports.risk_incident_candidates.length > 0)
|
||||
@@ -1370,6 +1403,7 @@ function renderSecurityView(data, report, extras = {}) {
|
||||
return `
|
||||
${renderActionCenter(report?.recommended_actions, { title: "Рекомендуемые действия ИБ", security: true })}
|
||||
${renderSecurityEventsSummary(report?.security_events_summary)}
|
||||
${renderSecurityFindingInbox(extras.securityFindings)}
|
||||
${renderRiskIncidentCandidates(report?.risk_incident_candidates)}
|
||||
${renderSecurityCorrelation(report?.security_correlation)}
|
||||
${renderCases(cases)}
|
||||
@@ -1382,10 +1416,84 @@ function renderSecurityView(data, report, extras = {}) {
|
||||
`;
|
||||
}
|
||||
|
||||
function renderSecurityFindingInbox(inbox) {
|
||||
if (!inbox) {
|
||||
return `<section class="card security-findings-card"><h3>Подозрительные станции</h3><p class="muted">Очередь подозрительных станций загружается.</p></section>`;
|
||||
}
|
||||
const disabled = inbox.backend === "disabled" || inbox.status === "disabled";
|
||||
const fallback = Boolean(inbox.fallback_used);
|
||||
const status = disabled ? "UNKNOWN" : fallback ? "WARN" : Number(inbox.critical_count || 0) > 0 ? "FAIL" : Number(inbox.open_count || 0) > 0 ? "WARN" : "OK";
|
||||
const items = Array.isArray(inbox.items) ? inbox.items : [];
|
||||
const rows = items.map(item => `
|
||||
<tr>
|
||||
<td>
|
||||
<strong>${ui(item.host || "-")}</strong>
|
||||
<div class="muted small">${ui(item.ip || "-")} · ${ui(item.user || "-")} · ${ui(item.department || "-")}</div>
|
||||
</td>
|
||||
<td><span class="badge ${statusClass(item.severity)}">${ui(item.severity || "-")}</span></td>
|
||||
<td>
|
||||
<strong>${ui(item.state || "-")}</strong>
|
||||
<div class="muted small">${ui(item.workflow_status || "new")} · ${ui(item.last_workflow_event || "created")}</div>
|
||||
</td>
|
||||
<td>
|
||||
<strong>${ui(item.source || "-")}</strong>
|
||||
<div class="muted small">${ui(item.rule_id || "-")}</div>
|
||||
</td>
|
||||
<td>${ui(item.summary || item.rule_title || "-")}</td>
|
||||
<td>
|
||||
<div class="actions compact-actions">
|
||||
<button class="small-button" data-security-finding-action="decide" data-security-finding-id="${escapeHtml(item.finding_id)}">decide</button>
|
||||
<button class="small-button" data-security-finding-action="plan" data-security-finding-id="${escapeHtml(item.finding_id)}">plan</button>
|
||||
<button class="small-button" data-security-finding-action="approve" data-security-finding-id="${escapeHtml(item.finding_id)}">approve</button>
|
||||
<button class="small-button" data-security-finding-action="apply" data-security-finding-id="${escapeHtml(item.finding_id)}">apply</button>
|
||||
<button class="small-button" data-security-finding-action="rollback" data-security-finding-id="${escapeHtml(item.finding_id)}">rollback</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`).join("");
|
||||
return `
|
||||
<section class="card security-findings-card">
|
||||
<div class="section-head">
|
||||
<div>
|
||||
<h3 ${tooltip("Очередь подозрительных рабочих станций из Hayabusa/Sigma/Velociraptor/AWatch. Кнопки фиксируют workflow-события, но не выполняют firewall apply.")}>Подозрительные станции</h3>
|
||||
<p class="muted">Security Finding Inbox: triage -> decide -> plan -> approve -> apply. Реальное применение выполняется отдельным executor.</p>
|
||||
</div>
|
||||
<span class="badge ${statusClass(status)}">${ui(status)}</span>
|
||||
</div>
|
||||
<div class="quality-grid">
|
||||
<div><span class="muted">Открыто</span><strong>${ui(inbox.open_count ?? 0)}</strong></div>
|
||||
<div><span class="muted">Critical</span><strong>${ui(inbox.critical_count ?? 0)}</strong></div>
|
||||
<div><span class="muted">High</span><strong>${ui(inbox.high_count ?? 0)}</strong></div>
|
||||
<div><span class="muted">Contained</span><strong>${ui(inbox.contained_count ?? 0)}</strong></div>
|
||||
</div>
|
||||
${fallback ? `<div class="quality-warning">Security Finding Inbox временно недоступен: ${ui(inbox.error || "ошибка источника")}</div>` : ""}
|
||||
${disabled ? `<p class="muted small">Security Finding Inbox отключен: включите SECURITY_EVENTS_BACKEND=clickhouse и примените схему ClickHouse.</p>` : ""}
|
||||
${items.length === 0 ? `<p class="muted">Подозрительных станций в очереди нет.</p>` : `
|
||||
<div class="table-scroll">
|
||||
<table class="data-table security-findings-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Станция</th>
|
||||
<th>Риск</th>
|
||||
<th>Статус</th>
|
||||
<th>Источник</th>
|
||||
<th>Описание</th>
|
||||
<th>Workflow</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`}
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderManagerView(report) {
|
||||
return `
|
||||
${renderExecutiveDashboard(report)}
|
||||
${renderKpiExplain(report?.workforce_kpi_explain)}
|
||||
${renderWorkforceOperations(report?.workforce_operations || report?.workforce?.operations)}
|
||||
${renderDepartmentRanking(report)}
|
||||
${renderDepartmentHeatMap(report)}
|
||||
${renderOverviewAnalytics(report)}
|
||||
@@ -1708,6 +1816,134 @@ function renderSimpleItems(items, emptyText) {
|
||||
`).join("")}</div>`;
|
||||
}
|
||||
|
||||
function renderWorkforceOperations(ops) {
|
||||
if (!ops || typeof ops !== "object") return "";
|
||||
const summary = ops.summary || {};
|
||||
const load = summary.load || {};
|
||||
const idle = summary.idle || {};
|
||||
const discipline = summary.discipline || {};
|
||||
const confidence = summary.confidence || {};
|
||||
const rows = Array.isArray(ops.rows) ? ops.rows.slice(0, 18) : [];
|
||||
const model = ops.model || {};
|
||||
const guardrail = summary.guardrail || "Low confidence строки требуют проверки источников до персонального вывода.";
|
||||
return `
|
||||
<section class="dashboard-band workforce-ops-band">
|
||||
<div class="band-head">
|
||||
<div>
|
||||
<h3>Операционная загрузка</h3>
|
||||
<span class="muted">загрузка, простои, перегруз, дисциплина процесса и достоверность</span>
|
||||
</div>
|
||||
<span class="badge ${statusClass(summary.status || ops.status)}">${ui(summary.status || ops.status || "UNKNOWN")}</span>
|
||||
</div>
|
||||
<div class="quality-grid">
|
||||
<div><span class="muted">Требуют разбора</span><strong>${ui(summary.action_required_users ?? 0)}</strong></div>
|
||||
<div><span class="muted">Недогруз / ниже цели</span><strong>${ui(load.underloaded_users ?? 0)}</strong></div>
|
||||
<div><span class="muted">Перегруз</span><strong>${ui(load.overloaded_users ?? 0)}</strong></div>
|
||||
<div><span class="muted">Простой</span><strong>${ui(idle.idle_users ?? 0)}</strong></div>
|
||||
<div><span class="muted">Дисциплина процесса</span><strong>${ui(discipline.review_users ?? 0)}</strong></div>
|
||||
<div><span class="muted">Low confidence</span><strong>${ui(confidence.low_users ?? 0)}</strong></div>
|
||||
</div>
|
||||
<div class="table-scroll">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Сотрудник</th>
|
||||
<th>Ответственный</th>
|
||||
<th>Активно</th>
|
||||
<th>Простой</th>
|
||||
<th>Coverage</th>
|
||||
<th>Загрузка</th>
|
||||
<th>Простой</th>
|
||||
<th>Дисциплина</th>
|
||||
<th>Достоверность</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${rows.length ? rows.map(row => `
|
||||
<tr>
|
||||
<td><strong>${ui(row.user || "-")}</strong><small>${ui(row.department || "-")}</small></td>
|
||||
<td>${ui(row.manager_owner || "-")}</td>
|
||||
<td>${ui(row.workday_active_hhmm || "00:00")}</td>
|
||||
<td>${ui(row.workday_idle_hhmm || "00:00")}</td>
|
||||
<td>${ui(Math.round(Number(row.coverage_pct || 0)))}%</td>
|
||||
<td><span class="badge ${statusClass(workforceOpsSeverity("load", row.load_status))}">${ui(workforceOpsLabel("load", row.load_status))}</span></td>
|
||||
<td><span class="badge ${statusClass(workforceOpsSeverity("idle", row.idle_status))}">${ui(workforceOpsLabel("idle", row.idle_status))}</span></td>
|
||||
<td><span class="badge ${statusClass(workforceOpsSeverity("discipline", row.discipline_status))}">${ui(workforceOpsLabel("discipline", row.discipline_status))}</span></td>
|
||||
<td><span class="badge ${statusClass(workforceOpsSeverity("confidence", row.data_confidence))}">${ui(workforceOpsLabel("confidence", row.data_confidence))}</span></td>
|
||||
<td>${ui(row.recommended_action || row.operations_recommended_action || row.operations?.recommended_action || "-")}</td>
|
||||
</tr>
|
||||
`).join("") : `
|
||||
<tr><td colspan="10"><strong>Нет данных</strong><small>Управленческий срез Worktime пока не сформирован.</small></td></tr>
|
||||
`}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="muted small">${ui(guardrail)} · модель: <code>${escapeHtml(model.version || "workforce-operations-v1")}</code> / <code>${escapeHtml(model.type || "rule_based")}</code>.</p>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function workforceOpsSeverity(kind, value) {
|
||||
const status = String(value || "").toLowerCase();
|
||||
if (kind === "load") {
|
||||
if (status === "normal") return "OK";
|
||||
if (status === "overloaded") return "HIGH";
|
||||
if (["underloaded", "below_target", "no_activity"].includes(status)) return "WARN";
|
||||
if (["no_data", "insufficient_data"].includes(status)) return "MISSING";
|
||||
}
|
||||
if (kind === "idle") {
|
||||
if (status === "no_significant_idle") return "OK";
|
||||
if (["idle_detected", "full_workday_idle_or_absent"].includes(status)) return "WARN";
|
||||
if (status === "unknown") return "MISSING";
|
||||
}
|
||||
if (kind === "discipline") {
|
||||
if (status === "ok") return "OK";
|
||||
if (status) return "WARN";
|
||||
}
|
||||
if (kind === "confidence") {
|
||||
if (status === "high") return "OK";
|
||||
if (status === "medium") return "WARN";
|
||||
if (status === "low") return "MISSING";
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
function workforceOpsLabel(kind, value) {
|
||||
const status = String(value || "").toLowerCase();
|
||||
const labels = {
|
||||
load: {
|
||||
insufficient_data: "нет окна",
|
||||
no_data: "нет данных",
|
||||
no_activity: "нет активности",
|
||||
underloaded: "недогруз",
|
||||
below_target: "ниже цели",
|
||||
normal: "норма",
|
||||
overloaded: "перегруз",
|
||||
},
|
||||
idle: {
|
||||
not_applicable: "не применимо",
|
||||
unknown: "нет данных",
|
||||
full_workday_idle_or_absent: "пустой день",
|
||||
idle_detected: "простой",
|
||||
no_significant_idle: "без простоя",
|
||||
},
|
||||
discipline: {
|
||||
ok: "процесс в норме",
|
||||
off_hours: "вне графика",
|
||||
late_start: "поздний старт",
|
||||
early_finish: "раннее завершение",
|
||||
multiple_flags: "несколько отклонений",
|
||||
},
|
||||
confidence: {
|
||||
high: "high",
|
||||
medium: "medium",
|
||||
low: "low",
|
||||
},
|
||||
};
|
||||
return labels[kind]?.[status] || value || "unknown";
|
||||
}
|
||||
|
||||
function workforceIndexText(usersCount, activeSeconds) {
|
||||
const users = Number(usersCount || 0);
|
||||
const seconds = Number(activeSeconds || 0);
|
||||
@@ -3037,6 +3273,7 @@ function renderReports(data) {
|
||||
<h3 class="section-title">Ключевые показатели</h3>
|
||||
${renderKpiCards(data.kpis)}
|
||||
${renderKpiExplain(data.workforce_kpi_explain)}
|
||||
${renderWorkforceOperations(data.workforce_operations || data.workforce?.operations)}
|
||||
${renderAgentQuality(data.agent_quality, data.agent_quality_explain)}
|
||||
${renderAgentQualityHistory(data.agent_quality_history, data.agent_quality_history_summary)}
|
||||
${renderAgentQualityNodes(data.agent_quality_nodes, data.agent_quality_nodes_summary)}
|
||||
@@ -3107,28 +3344,41 @@ async function refresh(options = {}) {
|
||||
const content = document.getElementById("content");
|
||||
const background = Boolean(options.background);
|
||||
const stage = options.stage || "Получение данных";
|
||||
const refreshSeq = ++state.refreshSeq;
|
||||
const isCurrentRefresh = () => refreshSeq === state.refreshSeq;
|
||||
const progress = (status, label, value) => {
|
||||
if (!background) setLoadStatus(status, label, value);
|
||||
if (!background && isCurrentRefresh()) setLoadStatus(status, label, value);
|
||||
};
|
||||
try {
|
||||
progress("LOADING", stage, 8);
|
||||
if (!background && content) content.innerHTML = renderLoadingContent(stage);
|
||||
if (!background && content && isCurrentRefresh()) {
|
||||
content.innerHTML = renderLoadingContent(stage);
|
||||
}
|
||||
if (!state.links) {
|
||||
progress("LOADING", "Получение данных", 18);
|
||||
state.links = await loadJson("/links");
|
||||
if (!isCurrentRefresh()) return;
|
||||
}
|
||||
progress("LOADING", "Расчёт показателей", 34);
|
||||
const summary = await loadJson("/summary");
|
||||
const summary = await loadJsonWithTimeout("/summary", 5000).catch(fallbackSummary);
|
||||
if (!isCurrentRefresh()) return;
|
||||
progress("LOADING", "Расчёт показателей", 46);
|
||||
state.readiness = {
|
||||
bundle: await loadJson("/readiness/bundle").catch(error => ({ ok: false, error: error.message })),
|
||||
bundle: await loadJsonWithTimeout("/readiness/bundle", 3000).catch(error => ({ ok: false, error: error.message })),
|
||||
verify: state.readiness?.verify || null
|
||||
};
|
||||
if (!isCurrentRefresh()) return;
|
||||
renderSummary(summary, state.readiness);
|
||||
progress("LOADING", "Формирование главного вывода", 68);
|
||||
const tabResult = await loadCurrentTab();
|
||||
if (!isCurrentRefresh()) return;
|
||||
progress("LOADING", "Подготовка разделов", 88);
|
||||
if (!hasTabData(state.tab, tabResult)) {
|
||||
if (tabResult.html && tabResult.html.includes("data-loading-state=\"STALE\"")) {
|
||||
setLoadStatus("STALE", "Первичный срез прогревается", 100, { error: "cache/prewarm in progress" });
|
||||
if (content) content.innerHTML = tabResult.html;
|
||||
return;
|
||||
}
|
||||
setLoadStatus("EMPTY", "Данные отсутствуют", 100);
|
||||
if (content) {
|
||||
content.innerHTML = `${renderEmptyState("Источники ответили, но полезные записи для текущего раздела пока не найдены.")}${tabResult.html || ""}`;
|
||||
@@ -3139,20 +3389,29 @@ async function refresh(options = {}) {
|
||||
setLoadStatus("READY", "Данные готовы", 100);
|
||||
consumePendingScroll();
|
||||
} catch (error) {
|
||||
if (!isCurrentRefresh()) return;
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCurrentTab() {
|
||||
if (state.tab === "operator") {
|
||||
const data = await loadJson("/operator");
|
||||
const data = await loadJsonWithTimeout("/operator", 7000).catch(error => null);
|
||||
if (!data) {
|
||||
return {
|
||||
data: {},
|
||||
html: staleBanner("Портал прогревает первичный срез. Быстрые health/readiness доступны, тяжелый операционный срез будет подставлен после cache/prewarm.")
|
||||
};
|
||||
}
|
||||
state.operatorData = data;
|
||||
state.reports = await loadJson("/reports").catch(() => state.reports);
|
||||
state.reports = await loadJsonWithTimeout("/reports", 3000).catch(() => state.reports);
|
||||
let securityFindings = null;
|
||||
if (currentViewMode() === "security" || currentViewMode() === "forensics") {
|
||||
state.cases = await loadJson("/cases").catch(error => ({ ok: false, error: error.message, cases: [] }));
|
||||
securityFindings = await loadJson("/security/findings").catch(error => ({ status: "fallback", fallback_used: true, error: error.message, items: [] }));
|
||||
}
|
||||
updateFilters(state.reports);
|
||||
return { data, report: state.reports, cases: state.cases, html: renderOperator(data, state.reports, { cases: state.cases }) };
|
||||
return { data, report: state.reports, cases: state.cases, securityFindings, html: renderOperator(data, state.reports, { cases: state.cases, securityFindings }) };
|
||||
}
|
||||
if (state.tab === "manager") {
|
||||
const data = await loadJson("/manager");
|
||||
@@ -3178,6 +3437,19 @@ async function loadCurrentTab() {
|
||||
const data = await loadJson("/owner");
|
||||
return { data, html: renderOwner(data) };
|
||||
}
|
||||
if (state.tab === "securityFindings") {
|
||||
const data = await loadJson("/security/findings");
|
||||
return { data, html: `
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h2 class="section-title">Подозрительные станции</h2>
|
||||
<p class="muted">Очередь triage для Hayabusa/Sigma/Velociraptor/AWatch findings. Реальное применение containment выполняется отдельным executor.</p>
|
||||
</div>
|
||||
<span class="badge ${statusClass(data.status)}">${ui(data.status || "unknown")}</span>
|
||||
</div>
|
||||
${renderSecurityFindingInbox(data)}
|
||||
` };
|
||||
}
|
||||
if (state.tab === "incidents") {
|
||||
const data = await loadJson("/incidents");
|
||||
const evidence = await loadJson("/dlp/evidence").catch(error => ({ ok: false, error: error.message, items: [] }));
|
||||
@@ -3213,6 +3485,7 @@ function tabLoadingStage(tab) {
|
||||
employees: "Получение данных сотрудников",
|
||||
departments: "Расчёт показателей подразделений",
|
||||
owner: "Формирование главного вывода по рискам",
|
||||
securityFindings: "Загрузка очереди подозрительных станций",
|
||||
incidents: "Подготовка разделов расследований",
|
||||
perimeter: "Подготовка разделов сетевого периметра",
|
||||
reports: "Подготовка разделов отчета",
|
||||
@@ -3230,7 +3503,7 @@ function setTab(tab) {
|
||||
}
|
||||
|
||||
function applySecurityMode(tab) {
|
||||
document.body.classList.toggle("security-mode", tab === "owner" || tab === "incidents" || tab === "perimeter");
|
||||
document.body.classList.toggle("security-mode", tab === "owner" || tab === "incidents" || tab === "perimeter" || tab === "securityFindings");
|
||||
}
|
||||
|
||||
function consumePendingScroll() {
|
||||
@@ -3311,6 +3584,12 @@ document.addEventListener("click", event => {
|
||||
incidentAction(button).catch(showError);
|
||||
});
|
||||
|
||||
document.addEventListener("click", event => {
|
||||
const button = event.target.closest("[data-security-finding-action]");
|
||||
if (!button) return;
|
||||
securityFindingWorkflowAction(button).catch(showError);
|
||||
});
|
||||
|
||||
document.addEventListener("click", event => {
|
||||
const button = event.target.closest("[data-review-status]");
|
||||
if (!button) return;
|
||||
@@ -3425,6 +3704,23 @@ async function incidentAction(button) {
|
||||
await refresh({ stage: "Обновление статуса инцидента" });
|
||||
}
|
||||
|
||||
async function securityFindingWorkflowAction(button) {
|
||||
const findingId = button.dataset.securityFindingId;
|
||||
const action = button.dataset.securityFindingAction;
|
||||
const promptText = action === "apply"
|
||||
? "Комментарий к apply request. Реальное применение firewall отсюда не выполняется."
|
||||
: `Комментарий к действию ${action}`;
|
||||
const comment = window.prompt(promptText, "");
|
||||
if (comment === null) return;
|
||||
button.disabled = true;
|
||||
await postJson("/security/findings/workflow", {
|
||||
finding_id: findingId,
|
||||
action,
|
||||
comment,
|
||||
});
|
||||
await refresh({ stage: "Обновление очереди подозрительных станций" });
|
||||
}
|
||||
|
||||
async function candidateReviewAction(button) {
|
||||
const candidateId = button.dataset.candidateId;
|
||||
const status = button.dataset.reviewStatus;
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
<button class="tab" data-tab="employees">Сотрудники</button>
|
||||
<button class="tab" data-tab="departments">Подразделения</button>
|
||||
<button class="tab" data-tab="owner">Риски</button>
|
||||
<button class="tab" data-tab="securityFindings">Подозрительные станции</button>
|
||||
<button class="tab" data-tab="incidents">Расследования</button>
|
||||
<button class="tab" data-tab="perimeter">Сетевой периметр</button>
|
||||
<button class="tab" data-tab="reports">Отчеты</button>
|
||||
|
||||
+16
-6
@@ -38,9 +38,15 @@ ansible-playbook -i inventory.ini deploy_aw_server.yml
|
||||
Рекомендуемый способ не хранить пароли в репозитории — перед запуском экспортировать их в переменные окружения:
|
||||
|
||||
- Linux `aw_server` (SSH пароль root): `AW_SSH_PASSWORD`
|
||||
- Linux `proxmox` (SSH пароль): `AW_PROXMOX_SSH_PASSWORD`
|
||||
- Sudo для Linux, если отличается от SSH: `AW_SUDO_PASSWORD` или
|
||||
`AW_PROXMOX_SUDO_PASSWORD`
|
||||
- Windows `aw_windows` (WinRM пароль): `AW_WINRM_PASSWORD`
|
||||
|
||||
В `group_vars/aw_server.yml` и `group_vars/windows.yml` они читаются через `lookup('env', ...)`.
|
||||
В `group_vars/aw_server.yml`, `group_vars/proxmox.yml` и
|
||||
`group_vars/aw_windows.yml` они читаются через `lookup('env', ...)`.
|
||||
В `ansible/inventory.ini` пароли хранить нельзя: там остаются только host,
|
||||
user, port и connection-параметры.
|
||||
|
||||
## Полный установочный playbook (всё за один запуск)
|
||||
|
||||
@@ -125,8 +131,8 @@ Playbook:
|
||||
- после deploy принудительно запускает `ActivityWatch Recovery` и managed `ActivityWatch Launch *` задачи;
|
||||
- включает (`Enable-ScheduledTask`) `ActivityWatch Recovery` и managed `ActivityWatch Launch *` задачи перед запуском (иначе WebUI может показывать `Active time: 0s`);
|
||||
- оставляет `ActivityWatch Recovery` включённым даже при активном `AWatchRusCollectorGuard`: guard является основным контроллером, recovery остаётся fallback/bootstrap path;
|
||||
- выполняет API smoke-check bucket `aw-watcher-afk_<COMPUTERNAME>` и ожидает свежие события;
|
||||
- выполняет API smoke-check bucket `aw-watcher-window_<COMPUTERNAME>` и ожидает свежие события (по умолчанию включено);
|
||||
- выполняет API smoke-check bucket `aw-watcher-afk_<aw_windows_logical_host_id>` и ожидает свежие события;
|
||||
- выполняет API smoke-check bucket `aw-watcher-window_<aw_windows_logical_host_id>` и ожидает свежие события (по умолчанию включено);
|
||||
- запускает `validate-deployment.ps1`;
|
||||
- забирает JSON-отчёт в локальную директорию (`/tmp/aw-rus-validation-<USER>` по умолчанию).
|
||||
- настраивает scheduled task `ActivityWatch Hayabusa Upload` с периодом и lookback по vars.
|
||||
@@ -146,8 +152,10 @@ Playbook:
|
||||
- `aw_windows_legacy_install_root` / `aw_windows_legacy_state_root` — старые production paths, откуда выполняется перенос;
|
||||
- `aw_windows_migration_report_remote_path` — JSON-отчёт о миграции на Windows-хосте;
|
||||
- `aw_windows_package_version`, `aw_windows_package_url`, `aw_windows_package_zip_path` — версия и источник Windows-пакета ActivityWatch;
|
||||
- `aw_windows_api_smoke_check_bucket: ""` — автоматически использовать `aw-watcher-afk_<COMPUTERNAME>`;
|
||||
- `aw_windows_api_smoke_check_window_enabled: true` — включить дополнительный smoke-check `aw-watcher-window_<COMPUTERNAME>`;
|
||||
- `aw_windows_domain: ""` — Windows account domain/local logon prefix. Если пусто или `HOST-EXAMPLE`, playbook берёт текущий `$env:COMPUTERNAME` с Windows-хоста через WinRM;
|
||||
- `aw_windows_logical_host_id: ""` — stable ActivityWatch id для bucket-ов/дашбордов; если пусто, fallback к `COMPUTERNAME`;
|
||||
- `aw_windows_api_smoke_check_bucket: ""` — автоматически использовать `aw-watcher-afk_<aw_windows_logical_host_id>`;
|
||||
- `aw_windows_api_smoke_check_window_enabled: true` — включить дополнительный smoke-check `aw-watcher-window_<aw_windows_logical_host_id>` с fallback к физическому `COMPUTERNAME`;
|
||||
- `aw_windows_api_smoke_check_window_bucket: ""` — переопределить bucket для window smoke-check;
|
||||
- `aw_windows_api_smoke_check_min_events: 1` — минимум событий, ожидаемых в smoke-check;
|
||||
- `aw_windows_fail_on_validation_error: true` — завершать playbook ошибкой, если `validate-deployment.ps1` возвращает `overallOk=false`;
|
||||
@@ -157,7 +165,7 @@ Playbook:
|
||||
- `aw_windows_hayabusa_auto_upload_hours_back: 6` — lookback для каждого запуска;
|
||||
- `aw_windows_hayabusa_auto_upload_mode: "incident"` — mode для server-side processing;
|
||||
- `aw_windows_hayabusa_auto_upload_task_name: "ActivityWatch Hayabusa Upload"` — имя scheduled task.
|
||||
- `aw_windows_hayabusa_auto_upload_run_as_user: "Администратор"` — production principal для scheduled task на RDP-хосте. На `SHARKON2025` запуск `powershell.exe` из `SYSTEM` возвращал `0xC0000142`, поэтому авто-upload должен идти как interactive/highest task от локального администратора.
|
||||
- `aw_windows_hayabusa_auto_upload_run_as_user: "Администратор"` — production principal для scheduled task на RDP-хосте. На текущем DetMir RDP-контуре запуск `powershell.exe` из `SYSTEM` возвращал `0xC0000142`, поэтому auto-upload должен идти как interactive/highest task от локального администратора.
|
||||
|
||||
## Server-side Hayabusa auto-case и Telegram alerting
|
||||
|
||||
@@ -290,3 +298,5 @@ bash scripts/prod_rollout.sh
|
||||
```
|
||||
|
||||
Скрипт попросит `AW_SSH_PASSWORD` и `AW_WINRM_PASSWORD` интерактивно (ввод скрыт) и сложит логи в `.rollout-logs/`.
|
||||
Для Proxmox можно дополнительно экспортировать `AW_PROXMOX_SSH_PASSWORD`, если
|
||||
он отличается от `AW_SSH_PASSWORD`.
|
||||
|
||||
@@ -47,6 +47,7 @@ aw_worktime_host: "{{ aw_monitored_windows_hostname }}"
|
||||
aw_rus_health_worktime_api_base: "http://127.0.0.1:5610"
|
||||
aw_rus_health_state_dir: "{{ aw_server_data_dir }}/health"
|
||||
aw_rus_health_validation_dir: "{{ aw_rus_health_state_dir }}/windows-validation"
|
||||
aw_rus_health_rdp_tcp_required: true
|
||||
aw_browser_smoke_enabled: true
|
||||
aw_browser_smoke_engine: "chromium-cli"
|
||||
aw_legacy_db_merge_enabled: false
|
||||
@@ -58,6 +59,15 @@ aw_hayabusa_telegram_enabled: true
|
||||
aw_hayabusa_telegram_min_severity: "high"
|
||||
aw_hayabusa_telegram_bot_token: ""
|
||||
aw_hayabusa_telegram_chat_ids: ""
|
||||
aw_security_finding_inbox_enabled: false
|
||||
aw_security_finding_inbox_required: false
|
||||
aw_security_finding_inbox_bin: "/usr/local/bin/security-finding-inbox"
|
||||
aw_security_finding_inbox_min_severity: "medium"
|
||||
aw_security_finding_executor_work_dir: "{{ aw_server_data_dir }}/security-finding-executor"
|
||||
aw_security_finding_executor_lock: "/var/lock/aw-security-finding-executor.lock"
|
||||
aw_containment_engine_bin: "/usr/local/bin/containment-engine"
|
||||
aw_containment_management_allowlist: ""
|
||||
aw_containment_blocked_remote_addresses: ""
|
||||
|
||||
aw_repo_root: "{{ playbook_dir | dirname }}"
|
||||
|
||||
@@ -85,17 +95,44 @@ aw_server_always_active_pattern: "aw-watcher-window"
|
||||
aw_server_landingpage: "/#/activity/HOST-EXAMPLE/view/"
|
||||
aw_health_strict_fileops: 0
|
||||
|
||||
aw_dlp_policy_engine_enabled: true
|
||||
aw_dlp_profile: "core_only"
|
||||
detmir_portal_dlp_profile: "core_only"
|
||||
detmir_portal_dlp_module_enabled_override: false
|
||||
aw_dlp_enabled: false
|
||||
aw_dlp_disabled_reason: "operator_disabled_to_reduce_proxmox_influx_grafana_clickhouse_load"
|
||||
aw_dlp_disabled_since: ""
|
||||
aw_dlp_light_collector_enabled: false
|
||||
aw_dlp_light_guard_enabled: true
|
||||
aw_dlp_light_guard_load_ratio: "1.50"
|
||||
aw_dlp_light_guard_mem_available_pct_min: "15"
|
||||
aw_dlp_light_guard_iowait_pct_max: "20"
|
||||
aw_dlp_light_guard_strikes_required: 3
|
||||
aw_dlp_light_guard_state_dir: "{{ aw_server_data_dir }}/health"
|
||||
aw_dlp_aggregator_bucket_prefixes: "aw-file-operations_,aw-dlp-incidents_"
|
||||
aw_dlp_aggregator_limit: 500
|
||||
aw_dlp_aggregator_lookback_hours: 2
|
||||
aw_dlp_aggregator_overlap_seconds: 60
|
||||
aw_dlp_aggregator_timeout_seconds: 8
|
||||
aw_dlp_aggregator_on_calendar: "*:3/15:10"
|
||||
aw_dlp_aggregator_cpu_quota: "10%"
|
||||
aw_dlp_aggregator_memory_max: "256M"
|
||||
aw_containment_enabled: false
|
||||
aw_containment_mode: "shadow"
|
||||
aw_containment_policy_path: "/etc/activitywatch/containment-policy.json"
|
||||
aw_containment_default_ttl_minutes: 60
|
||||
aw_containment_require_admin_channel_check: true
|
||||
aw_containment_allow_auto_for_servers: false
|
||||
aw_dlp_policy_engine_enabled: false
|
||||
aw_dlp_policy_engine_bind_host: "0.0.0.0"
|
||||
aw_dlp_policy_engine_port: 5601
|
||||
aw_dlp_policy_engine_db_path: "{{ aw_server_data_dir }}/dlp-policy-engine.sqlite"
|
||||
aw_dlp_content_analysis_enabled: true
|
||||
aw_dlp_integrations_enabled: true
|
||||
aw_dlp_case_management_enabled: true
|
||||
aw_dlp_content_analysis_enabled: false
|
||||
aw_dlp_integrations_enabled: false
|
||||
aw_dlp_case_management_enabled: false
|
||||
aw_dlp_case_bind_host: "0.0.0.0"
|
||||
aw_dlp_case_port: 5602
|
||||
aw_dlp_case_db_path: "/opt/activitywatch/dlp-case-management/cases.db"
|
||||
aw_dlp_compliance_enabled: true
|
||||
aw_dlp_compliance_enabled: false
|
||||
aw_dlp_compliance_report_dir: "/opt/activitywatch/dlp-compliance/reports"
|
||||
aw_dlp_compliance_template_path: "/opt/activitywatch/dlp-compliance/templates/152-fz-report.html"
|
||||
aw_server_post_deploy_health_check_enabled: true
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Secret handling:
|
||||
# - put the real Proxmox SSH password into env var before running Ansible:
|
||||
# export AW_PROXMOX_SSH_PASSWORD='...'
|
||||
# - if Proxmox and AW server share the same SSH credential, AW_SSH_PASSWORD is
|
||||
# accepted as a fallback.
|
||||
ansible_password: "{{ lookup('env', 'AW_PROXMOX_SSH_PASSWORD') | default(lookup('env', 'AW_SSH_PASSWORD'), true) }}"
|
||||
|
||||
ansible_become: true
|
||||
ansible_become_method: sudo
|
||||
# If sudo password differs, set AW_PROXMOX_SUDO_PASSWORD. Otherwise it reuses
|
||||
# AW_PROXMOX_SSH_PASSWORD and then AW_SSH_PASSWORD.
|
||||
ansible_become_password: "{{ lookup('env', 'AW_PROXMOX_SUDO_PASSWORD') | default(lookup('env', 'AW_PROXMOX_SSH_PASSWORD'), true) | default(lookup('env', 'AW_SUDO_PASSWORD'), true) | default(lookup('env', 'AW_SSH_PASSWORD'), true) }}"
|
||||
@@ -6,7 +6,7 @@ aw-ct ansible_host=10.20.30.13 ansible_user=root ansible_port=22
|
||||
|
||||
[aw_windows]
|
||||
# Примечание: в русифицированных Windows часто нужен "Администратор", а не "Administrator".
|
||||
win-node1 ansible_host=<WINDOWS_HOST> ansible_user=Администратор ansible_password=CHANGE_ME ansible_connection=winrm ansible_winrm_transport=ntlm ansible_port=5985 ansible_winrm_server_cert_validation=ignore
|
||||
win-node1 ansible_host=<WINDOWS_HOST> ansible_user=Администратор ansible_connection=winrm ansible_winrm_transport=ntlm ansible_port=5985 ansible_winrm_server_cert_validation=ignore
|
||||
|
||||
[aw_pfsense_pollers]
|
||||
# pfsense-poller1 ansible_host=198.51.100.30 ansible_user=root ansible_port=22
|
||||
|
||||
@@ -274,7 +274,7 @@ server {
|
||||
location ^~ /portal/api/readiness {
|
||||
proxy_set_header Authorization "";
|
||||
proxy_set_header X-Remote-User $remote_user;
|
||||
proxy_pass http://192.0.2.13:8721/api/readiness;
|
||||
proxy_pass http://127.0.0.1:8720/api/readiness;
|
||||
proxy_redirect off;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"use strict";
|
||||
|
||||
var BAD_HOST = ["HOST", "EXAMPLE"].join("-");
|
||||
var DEFAULT_HOST = "SHARKON2025";
|
||||
var DEFAULT_HOST = "HOST-EXAMPLE";
|
||||
|
||||
function decode(value) {
|
||||
try {
|
||||
|
||||
@@ -19,10 +19,16 @@ Forensics усиливают продукт, но не должны перетя
|
||||
- как меняется загрузка сотрудников и подразделений;
|
||||
- где тормозят бизнес-процессы.
|
||||
|
||||
Канонический контракт по загрузке, простоям, перегрузу, дисциплине процесса и
|
||||
достоверности данных: [WORKFORCE_OPERATIONS_MODEL_RU.md](WORKFORCE_OPERATIONS_MODEL_RU.md).
|
||||
|
||||
Основные KPI:
|
||||
|
||||
- UEBA риск: read-only `risk_score/risk_level/reasons` для приоритизации
|
||||
проверки;
|
||||
- операционная загрузка: rule-based статусы `load_status`, `idle_status`,
|
||||
`discipline_status`, `data_confidence` для разбора загрузки, простоев,
|
||||
перегруза и дисциплины процесса;
|
||||
- индекс активности: proxy `активное время / плановое рабочее время`;
|
||||
- взвешенная активность: только при настроенной role/application policy;
|
||||
- сравнение подразделений за текущий день;
|
||||
@@ -195,7 +201,7 @@ Worktime API сохраняет daily history как агрегированны
|
||||
|
||||
```json
|
||||
{
|
||||
"overload_threshold": 0.92,
|
||||
"overload_threshold": 1.15,
|
||||
"underload_threshold": 0.45,
|
||||
"drop_threshold_pct": 20,
|
||||
"night_work_after": "20:00",
|
||||
@@ -204,7 +210,9 @@ Worktime API сохраняет daily history как агрегированны
|
||||
```
|
||||
|
||||
`overload_threshold` и `underload_threshold` можно задавать дробью
|
||||
`0.92`/`0.45` или процентом `92`/`45`; внутри они нормализуются к процентам.
|
||||
`1.15`/`0.45` или процентом `115`/`45`; внутри они нормализуются к процентам.
|
||||
Порог перегруза ниже 100% не применяется как перегруз: это защищает отчет от
|
||||
ложного статуса "перегружен" при обычной высокой занятости.
|
||||
Если policy-файл отсутствует или отдельное поле не задано, используются
|
||||
env/default значения:
|
||||
|
||||
@@ -260,6 +268,27 @@ env/default значения:
|
||||
- подтвержденным инцидентом событие становится после регламентной валидации;
|
||||
- продукт не заявляется как сертифицированная DLP/SIEM/EDR/XDR/СЗИ.
|
||||
|
||||
### Runtime boundary для DLP
|
||||
|
||||
Актуальный DetMir baseline перед переработкой зафиксирован в
|
||||
[DETMIR_CURRENT_STATE_RU.md](DETMIR_CURRENT_STATE_RU.md).
|
||||
|
||||
Коммерчески и технически DLP нужно подавать как подключаемый модуль, а не как
|
||||
обязательную часть первого экрана Workforce:
|
||||
|
||||
- Workforce должен открываться и строить управленческие показатели без ожидания
|
||||
DLP evidence, screenshots и heavy correlation;
|
||||
- DLP endpoint signals, clipboard/USB/print/web/file incidents, evidence review
|
||||
и screenshots остаются ценным модулем Security/Forensics;
|
||||
- отключенная или не настроенная DLP должна давать честный disabled-state, а не
|
||||
ошибку портала;
|
||||
- тяжелый DLP слой не должен блокировать `/api/operator`, prewarm и первичную
|
||||
загрузку руководительского/операционного экрана.
|
||||
|
||||
Это не означает отказ от DLP-сигналов. Это означает правильную модульность:
|
||||
ежедневная бизнес-ценность Workforce должна быть доступна быстро, а Security и
|
||||
Forensics подключаются как углубляющие слои.
|
||||
|
||||
## AWatch-rus Forensics
|
||||
|
||||
Для разбора сложных событий и пост-инцидентной аналитики.
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
# DetMir/AWatch-rus: hardline resilience hardening
|
||||
|
||||
Документ фиксирует реализованные и проверенные шаги по доведению живого
|
||||
контура до fail-closed уровня. Он не заменяет production runbook; здесь только
|
||||
изменения, влияющие на отказоустойчивость.
|
||||
|
||||
## 2026-06-30: crash-test readiness gate and healthd route boundary
|
||||
|
||||
Статус: implemented in repo, deployed on live AW server, verified by manual
|
||||
crash test.
|
||||
|
||||
Что прогонялось:
|
||||
|
||||
- baseline `check-aw-full.sh`, SQLite hot-path plan, disk/headroom, RDP guard;
|
||||
- bounded parallel load на `/api/0/info`,
|
||||
`/aw-worktime-sessions_SHARKON2025/events?limit=100`,
|
||||
`aw-detmir-web-category_SHARKON2025` и Worktime API;
|
||||
- controlled restart: `aw-worktime-api`, `activitywatch-server`,
|
||||
`AWatchRusCollectorGuard`;
|
||||
- gateway/ClickHouse/Grafana reachability checks;
|
||||
- live `scripts/detmir_resilience_check.sh --live` on AW server.
|
||||
|
||||
Что найдено:
|
||||
|
||||
- `systemctl is-active activitywatch-server` не равен полной готовности API:
|
||||
сразу после `systemctl restart activitywatch-server` первый `/api/0/info`
|
||||
мог уйти в 15 секунд timeout, затем API стабилизировался и hot-path
|
||||
`/events?limit=100` отвечал быстро;
|
||||
- `aw-dlp-case-management.service` оставался active при disabled DLP profile;
|
||||
- `aw-rus-healthd.service` падал из-за TCP timeout с AW server до
|
||||
`192.168.100.19:5985/3389`, хотя фактическая RDP/WinRM проверка с
|
||||
admin/VPN side и bucket freshness были зелёными;
|
||||
- SQLite hot-path index
|
||||
`events_bucketrow_starttime_desc_index` присутствовал и использовался,
|
||||
`TEMP B-TREE` для worktime event query не строился.
|
||||
|
||||
Что изменено:
|
||||
|
||||
- `scripts/detmir_resilience_check.sh --live` теперь использует readiness-loop
|
||||
для `/api/0/info`, проверяет worktime hot path, Worktime API rows/degraded
|
||||
state, SQLite hot-path index/plan и disabled-state optional DLP/Loki units;
|
||||
- `aw-rus-healthd-rust` получил fail-closed параметр
|
||||
`AW_RUS_HEALTH_RDP_TCP_REQUIRED` / `--rdp-tcp-required`;
|
||||
- default/example остаётся `true`; в DetMir production выставлено
|
||||
`false`, потому что server-side TCP до RDP сейчас является route/ACL
|
||||
boundary, а не authoritative proof of collector health;
|
||||
- active drift `aw-dlp-case-management.service` остановлен, unit оставлен
|
||||
disabled для штатного будущего включения DLP contour.
|
||||
|
||||
Live verification:
|
||||
|
||||
- `check-aw-full.sh`: `FRESH=8`, `STALE=0`, `DEAD=0`;
|
||||
- targeted load after stabilization:
|
||||
`info_p2/p4/p8/p12` по `24/24` HTTP 200,
|
||||
worktime events `40/40` HTTP 200,
|
||||
web category bucket `40/40` HTTP 200,
|
||||
Worktime today `30/30` HTTP 200;
|
||||
- `AWatchRusCollectorGuard` restart: service `Running`, `GUARD_CHILDREN=1`,
|
||||
collector process layout unchanged;
|
||||
- `aw-rus-healthd.service`: `status=0/SUCCESS`, `ok=11`, `warn=3`, `fail=0`;
|
||||
- `scripts/detmir_resilience_check.sh --live` after fixes:
|
||||
readiness, hot path, Worktime API, SQLite index, optional DLP and Loki checks
|
||||
pass; Hayabusa quarantine warning remains informational evidence to review.
|
||||
|
||||
Safety guardrails:
|
||||
|
||||
- no AW bucket schema, API, UI or Workforce business logic changed;
|
||||
- GitHub/Grafana/ClickHouse are still validation/visibility surfaces, not
|
||||
Russian registry release evidence;
|
||||
- DLP remains optional/reconnectable, not removed.
|
||||
|
||||
## 2026-06-25: optional DLP runtime off switch and statistics
|
||||
|
||||
Статус: implemented in repo, deployed, live disable verified on 2026-06-25.
|
||||
|
||||
Проблема:
|
||||
|
||||
- DLP runtime может создавать избыточную нагрузку на InfluxDB, Grafana,
|
||||
ClickHouse и AW server при включенных aggregator/exporter/case/report
|
||||
pipeline;
|
||||
- простая остановка DLP units раньше приводила бы к ложным красным health,
|
||||
readiness и contour checks.
|
||||
|
||||
Что добавлено:
|
||||
|
||||
- `AW_DLP_ENABLED=false` для AW server runtime;
|
||||
- `DETMIR_DLP_ENABLED=false` для управляющего DetMir contour check;
|
||||
- `dlp-health-check` возвращает штатный `dlp:mode=disabled`;
|
||||
- `detmir-dlp` не выполняет SSH health probe при disabled mode;
|
||||
- `detmir-check`, `check-aw-full`, `check-aw-data` пропускают DLP buckets при
|
||||
disabled mode;
|
||||
- `detmir-readiness` не требует DLP Influx write и DLP systemd units при
|
||||
disabled mode;
|
||||
- `scripts/detmir_dlp_runtime_control.sh` собирает JSON-срез DLP units/buckets
|
||||
и выполняет controlled `disable|enable`.
|
||||
- live `disable` сохраняет отдельные evidence-снимки `current`,
|
||||
`pre_disable` и `disabled` в
|
||||
`/var/lib/activitywatch/health/dlp-runtime-history/`.
|
||||
|
||||
Safety guardrails:
|
||||
|
||||
- ActivityWatch server, worktime, Hayabusa, 1C/ClickHouse core не отключаются;
|
||||
- historical DLP buckets/evidence не удаляются;
|
||||
- disabled-state не заявляет, что DLP проверки выполнены;
|
||||
- это не claim замены DLP/SIEM/EDR и не удаление DLP-функциональности.
|
||||
|
||||
Runbook:
|
||||
|
||||
- [DLP_OPTIONAL_RUNTIME_RU.md](DLP_OPTIONAL_RUNTIME_RU.md).
|
||||
|
||||
Live verification 2026-06-25:
|
||||
|
||||
- before disable, active DLP runtime units were present:
|
||||
`aw-dlp-influx-exporter.timer`, `activitywatch-dlp-aggregator.timer`,
|
||||
DLP report/integration timers, policy/case services and
|
||||
`detmir-portal-evidence.service`;
|
||||
- after disable, active/enabled DLP units: `0/0`;
|
||||
- `AW_DLP_ENABLED=false`, `AW_DLP_INFLUX_ENABLED=false`,
|
||||
`AW_DLP_DISABLED_REASON=operator_disabled_to_reduce_influx_grafana_clickhouse_load`;
|
||||
- `dlp-health-check` and `detmir-dlp` both returned `dlp:mode=disabled`;
|
||||
- `check-aw-full` reported DLP buckets as `SKIPPED`;
|
||||
- ActivityWatch core remained active:
|
||||
`activitywatch-server`, `aw-worktime-api`.
|
||||
|
||||
Residual non-DLP findings from the same check:
|
||||
|
||||
- RDP-side collectors require separate recovery: AFK/window/worktime buckets
|
||||
were stale;
|
||||
- server-side WinRM reachability to `192.168.100.18:5985` was unavailable;
|
||||
- `aw-rus-healthd.service` was already failed and is tracked separately from
|
||||
this DLP runtime disable.
|
||||
|
||||
## 2026-06-24: Hayabusa poison-package isolation
|
||||
|
||||
Статус: implemented locally, unit-tested, deployed on AW server.
|
||||
|
||||
Проблема:
|
||||
|
||||
- один битый zip в `/opt/hayabusa/inbox/incoming` мог остановить весь
|
||||
Hayabusa pipeline;
|
||||
- `aw-hayabusa-drop.path` после повторных падений мог упереться в systemd
|
||||
start-limit;
|
||||
- восстановление требовало ручного переноса bad zip в quarantine.
|
||||
|
||||
Что изменено:
|
||||
|
||||
- `aw-hayabusa-autoprocess-rust` проверяет drop zip до `accept`;
|
||||
- corrupt/empty/unsafe zip и битые sidecar-файлы не попадают в рабочий inbox;
|
||||
- bad drop package переносится в `/opt/hayabusa/quarantine/drop/...` вместе с
|
||||
`.meta.json`, `.caseid`, optional `.sha256` и `reason.json`;
|
||||
- `aw-hayabusa process-inbox` больше не abort'ит весь batch из-за одного
|
||||
incoming package;
|
||||
- failed incoming package переносится в
|
||||
`/opt/hayabusa/quarantine/incoming/...` с partial staging payload и
|
||||
`reason.json`, если пакет остался в incoming;
|
||||
- пакеты, уже архивированные wrapper'ом как `failed-no-evtx` или
|
||||
`failed-analysis`, остаются в штатном archive/intake manifest для
|
||||
расследования.
|
||||
|
||||
Safety guardrails:
|
||||
|
||||
- quarantine не удаляет evidence;
|
||||
- replay выполняется только после re-export или явного восстановления пакета;
|
||||
- один poison archive не должен мешать обработке остальных zip;
|
||||
- operational failures инфраструктуры (`aw-hayabusa` отсутствует, права,
|
||||
broken runtime) остаются красными и не маскируются как успешная обработка.
|
||||
|
||||
Проверки:
|
||||
|
||||
```bash
|
||||
cd /mnt/usb_hdd2/Projects/ActivityWatch-Russian
|
||||
bash -n aw-server/hayabusa/aw-hayabusa.sh
|
||||
|
||||
cd /mnt/usb_hdd2/Projects/ActivityWatch-Russian/adk-rust
|
||||
export CARGO_TARGET_DIR=/home/igor/.cache/detmir-adk-rust-target
|
||||
cargo test -p hayabusa-tools
|
||||
```
|
||||
|
||||
Результат проверки:
|
||||
|
||||
- `bash -n aw-server/hayabusa/aw-hayabusa.sh` passed;
|
||||
- `cargo test -p hayabusa-tools` passed: 5 tests passed.
|
||||
|
||||
Production deployment note:
|
||||
|
||||
- после сборки и доставки нового `aw-hayabusa-autoprocess-rust` нужно
|
||||
выполнить live dry-run на empty drop и контролируемый bad-zip test в
|
||||
непроизводственном каталоге или с временным isolated `--drop-dir`;
|
||||
- live production queue руками не мутировать без предварительного backup/listing.
|
||||
|
||||
Live rollout evidence:
|
||||
|
||||
- deployed on AW server on `2026-06-24`;
|
||||
- previous `/usr/local/bin/aw-hayabusa` and
|
||||
`/usr/local/bin/aw-hayabusa-autoprocess-rust` were backed up with timestamp
|
||||
suffix;
|
||||
- `/usr/local/bin/aw-hayabusa doctor` returned OK;
|
||||
- isolated empty-drop dry-run returned `no zip packages in drop dir`;
|
||||
- production queue after rollout: `incoming_zip=0`, `DROP_COUNT=0`,
|
||||
`aw-hayabusa-drop.path=active`, `aw-hayabusa-drop.service=inactive`;
|
||||
- stale staging residue from `2026-06-20` was moved, not deleted, to
|
||||
`/opt/hayabusa/quarantine/staging-stale-20260624T190739Z/` with
|
||||
`reason.json`;
|
||||
- after cleanup: `staged_dirs=0`, `archived_packages=74`,
|
||||
`archived_payloads=74`.
|
||||
|
||||
## 2026-06-24: Windows collector guard service child watchdog
|
||||
|
||||
Статус: implemented locally, static checks passed, deployed on RDP host.
|
||||
|
||||
Проблема:
|
||||
|
||||
- Windows service `AWatchRusCollectorGuard` мог оставаться в состоянии
|
||||
`running`, когда дочерний `aw-windows-telemetry.exe collector-guard` уже
|
||||
отсутствовал;
|
||||
- SCM recovery не срабатывал, потому что сам service wrapper не падал.
|
||||
|
||||
Что изменено:
|
||||
|
||||
- `AWatchRusCollectorGuardService.cs` теперь подписывается на `Process.Exited`;
|
||||
- при неожиданном выходе child-процесса wrapper делает bounded restart;
|
||||
- restart budget: 5 child restarts за 600 секунд, задержка 5 секунд;
|
||||
- при исчерпании бюджета wrapper завершает service с ошибкой, чтобы Windows
|
||||
Service Control Manager применил recovery actions;
|
||||
- installer включает `sc.exe failureflag <service> 1`, чтобы recovery actions
|
||||
применялись к service failures, а не только к crash-путям;
|
||||
- `ActivityWatch Recovery` остаётся fallback/bootstrap задачей и не отключается.
|
||||
|
||||
Safety guardrails:
|
||||
|
||||
- штатный `Stop-Service`/shutdown выставляет `stopping=true`, поэтому child exit
|
||||
во время остановки не считается аварией;
|
||||
- wrapper не меняет collector mode, bucket names, event schema и AW API;
|
||||
- service-level recovery ограничен существующим `sc.exe failure` budget.
|
||||
|
||||
Проверки:
|
||||
|
||||
```powershell
|
||||
pwsh -NoProfile -Command '<compile AWatchRusCollectorGuardService.cs through Add-Type>'
|
||||
pwsh -NoProfile -Command '<parse install-collector-guard-service.ps1>'
|
||||
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File windows/install-collector-guard-service.ps1
|
||||
Get-Service AWatchRusCollectorGuard
|
||||
Get-Content C:\ProgramData\AWatch-rus\logs\collector-guard-service.log -Tail 20
|
||||
```
|
||||
|
||||
Результат локальной проверки:
|
||||
|
||||
- `AWatchRusCollectorGuardService.cs` compiled through PowerShell `Add-Type`;
|
||||
- `windows/install-collector-guard-service.ps1` parsed with PowerShell parser;
|
||||
- live install/restart validation still requires Windows/RDP deployment window.
|
||||
|
||||
Live rollout evidence:
|
||||
|
||||
- deployed on RDP host on `2026-06-24`;
|
||||
- previous service source, installer and exe were backed up under
|
||||
`C:\ProgramData\AWatch-rus\backup\collector-guard-service-20260624T190827Z`;
|
||||
- installer completed with `Runtime: rust`, `Mode: enforce`;
|
||||
- SCM `failureflag` is enabled:
|
||||
`FAILURE_ACTIONS_ON_NONCRASH_FAILURES: TRUE`;
|
||||
- controlled fault-injection killed only the child
|
||||
`aw-windows-telemetry.exe collector-guard`;
|
||||
- wrapper observed child exit, attempted bounded restarts, SCM recovery restarted
|
||||
wrapper after budget exhaustion, and child stabilized;
|
||||
- final validation after one guard loop: service `Running`, `CHILD_COUNT=1`,
|
||||
child `aw-windows-telemetry.exe`, latest rust guard cycle `status=ok`.
|
||||
|
||||
Live validation после деплоя:
|
||||
|
||||
- убить только child `aw-windows-telemetry.exe collector-guard`;
|
||||
- убедиться, что service остаётся running и child перезапущен;
|
||||
- повторить child crash больше 5 раз за 600 секунд в тестовом окне;
|
||||
- убедиться, что service перешёл через SCM recovery, а не остался
|
||||
`running/no child`.
|
||||
|
||||
## 2026-06-24: contour resilience check
|
||||
|
||||
Статус: implemented locally, shell syntax/repo-mode passed, live AW server
|
||||
check passed.
|
||||
|
||||
Проблема:
|
||||
|
||||
- отдельные исправления легко потерять при deploy/drift;
|
||||
- CI не проверял, что poison-package isolation и child watchdog реально
|
||||
присутствуют в коде и документации;
|
||||
- live-проверки должны оставаться read-only и не маскировать production сбой.
|
||||
|
||||
Что добавлено:
|
||||
|
||||
- `scripts/detmir_resilience_check.sh`;
|
||||
- `--repo` режим для CI-safe проверки hardening-файлов, паттернов и docs;
|
||||
- `--live` режим для read-only проверки локального AW/Hayabusa host:
|
||||
`activitywatch-server`, `aw-worktime-api`, AW `/api/0/info`, failed systemd
|
||||
units, Hayabusa `incoming/drop/quarantine`, SQLite DB/WAL size;
|
||||
- `RUN_RESILIENCE_CHECK=1` hook в `scripts/run_awatch_contour_check.sh`;
|
||||
- `DETMIR_RESILIENCE_STRICT_SECRETS=1` режим, который fail'ит literal
|
||||
`ansible_password`/`ansible_become_password` в private inventory без вывода
|
||||
значений.
|
||||
|
||||
Safety guardrails:
|
||||
|
||||
- check не рестартует сервисы, не двигает очереди, не пишет в production dirs;
|
||||
- secret check печатает только факт наличия literal assignments, не значения;
|
||||
- live mode запускается явно через `--live` или `--all`;
|
||||
- GitHub/public CI может использовать только `--repo`.
|
||||
|
||||
Secret handling update 2026-06-30:
|
||||
|
||||
- literal `ansible_password` и `ansible_become_password` удалены из локального
|
||||
`ansible/inventory.ini`;
|
||||
- `aw_server` читает SSH/sudo secrets из `AW_SSH_PASSWORD` и
|
||||
`AW_SUDO_PASSWORD`;
|
||||
- `proxmox` читает SSH/sudo secrets из `AW_PROXMOX_SSH_PASSWORD` и
|
||||
`AW_PROXMOX_SUDO_PASSWORD`, с fallback на `AW_SSH_PASSWORD` /
|
||||
`AW_SUDO_PASSWORD`;
|
||||
- `aw_windows` читает WinRM secret из `AW_WINRM_PASSWORD`;
|
||||
- `inventory.example.ini` больше не содержит placeholder password-поля.
|
||||
|
||||
Проверки:
|
||||
|
||||
```bash
|
||||
bash -n scripts/detmir_resilience_check.sh
|
||||
bash scripts/detmir_resilience_check.sh --repo
|
||||
```
|
||||
|
||||
Результат локальной проверки:
|
||||
|
||||
- shell syntax passed for `scripts/detmir_resilience_check.sh`;
|
||||
- shell syntax passed for `scripts/run_awatch_contour_check.sh`;
|
||||
- repo-mode passed with `ok=15`, `fail=0`;
|
||||
- repo-mode reported one WARN: literal Ansible password assignments appear to
|
||||
exist in `ansible/inventory.ini`; values are not printed, and
|
||||
`DETMIR_RESILIENCE_STRICT_SECRETS=1` converts this to fail for private
|
||||
contour gates.
|
||||
|
||||
Live AW server result:
|
||||
|
||||
- `bash /tmp/detmir_resilience_check.sh --live` passed on AW server;
|
||||
- result: `ok=9`, `warn=1`, `fail=0`;
|
||||
- WARN is expected after this rollout: one quarantine `reason.json` exists for
|
||||
the moved stale Hayabusa staging residue.
|
||||
|
||||
## 2026-06-24: live drift fixes after full contour re-check
|
||||
|
||||
Статус: deployed and verified live.
|
||||
|
||||
Что было найдено:
|
||||
|
||||
- ClickHouse container was healthy by direct SQL checks, but Docker Compose did
|
||||
not define a container `HEALTHCHECK`; because of that
|
||||
`aw-1c-clickhouse-health.service` failed with
|
||||
`docker healthcheck is not configured`.
|
||||
- `detmir-auto` used the default public gateway URL for portal checks when
|
||||
`/etc/detmir/detmir-check.env` did not set `DETMIR_PORTAL_URL`; protected
|
||||
public `/readyz`, `/version` and `/metrics` returned legitimate `401`.
|
||||
- `detmir-portal-prewarm.service` had `curl --max-time 60`, but a cold
|
||||
`/api/reports` build on the live contour can take more than 60 seconds.
|
||||
- `aw-rus-healthd-rust` used the default 20 second wrapper timeout; under
|
||||
concurrent checks `dlp-health-check --json` could be killed mid-output and be
|
||||
reported as `invalid JSON output`.
|
||||
|
||||
Что изменено:
|
||||
|
||||
- `clickhouse-1c/docker-compose.yml` now defines a ClickHouse client
|
||||
`HEALTHCHECK`, deployed to `/opt/activitywatch/clickhouse-1c/docker-compose.yml`;
|
||||
- production `/etc/detmir/detmir-check.env` now contains
|
||||
`DETMIR_PORTAL_URL=http://127.0.0.1:8720` and
|
||||
`DETMIR_GATEWAY_HOST=127.0.0.1`;
|
||||
- `ops/systemd/detmir-portal-prewarm.service` is now tracked in the repo and
|
||||
deployed with `curl --max-time 180` and `TimeoutStartSec=210`;
|
||||
- production `/etc/activitywatch/aw-server.env` and
|
||||
`aw-server/aw-server.env.example` now set
|
||||
`AW_RUS_HEALTH_WRAPPER_TIMEOUT_SECONDS=90`.
|
||||
|
||||
Verification:
|
||||
|
||||
- `check-aw-full.sh`: `FRESH=8`, `STALE=0`, `DEAD=0`;
|
||||
- `detmir-check` through the production env file: `ok=true`,
|
||||
`service_failures=0`;
|
||||
- `detmir-auto.service`, `awatch-contour-daily-check.service`,
|
||||
`awatch-contour-weekly-check.service`: `status=0/SUCCESS`;
|
||||
- `detmir-portal-prewarm.service`: `status=0/SUCCESS`;
|
||||
- `aw-1c-clickhouse-health.service`: `status=0/SUCCESS`, Docker state
|
||||
`(healthy)`;
|
||||
- `aw-rus-healthd.service`: `status=0/SUCCESS`, failed systemd units on
|
||||
AW server and Proxmox are zero.
|
||||
|
||||
## 2026-06-25: portal cold-start prewarm after service restart
|
||||
|
||||
Статус: deployed and verified live at the time, then superseded by the
|
||||
fail-soft hot-path boundary below.
|
||||
|
||||
Что было найдено:
|
||||
|
||||
- после ручного `systemctl restart detmir-portal` первый
|
||||
`/api/reports?role=manager` может выполнять холодный расчет дольше 120 секунд;
|
||||
- `detmir-portal-prewarm.timer` держит cache теплым каждые 30 минут, но не
|
||||
запускается немедленно при ручном рестарте портала.
|
||||
- одного prewarm недостаточно, если каждый пользовательский `/api/reports`
|
||||
заново запускает тяжелую генерацию отчета.
|
||||
|
||||
Что изменено:
|
||||
|
||||
- добавлен tracked drop-in
|
||||
`ops/systemd/detmir-portal.service.d/30-prewarm-after-start.conf`;
|
||||
- production drop-in `/etc/systemd/system/detmir-portal.service.d/30-prewarm-after-start.conf`
|
||||
запускает `detmir-portal-prewarm.service` через `systemctl --no-block` после
|
||||
каждого старта портала;
|
||||
- prewarm остается best-effort: портал стартует независимо, а тяжелый
|
||||
`/api/reports` прогревается в фоне.
|
||||
- в `detmir-portal` добавлен short-lived in-process report cache с TTL 120
|
||||
секунд и защитой от stampede: первый report-запрос строит payload, следующие
|
||||
report endpoints в окне TTL отдают тот же payload без повторной генерации.
|
||||
- в `/metrics` добавлены отдельные счетчики report-cache:
|
||||
`awatch_report_requests_total`, `awatch_report_cache_hits_total`,
|
||||
`awatch_report_cache_misses_total`. Старый
|
||||
`awatch_reports_generated_total` остается счетчиком успешно завершенных
|
||||
тяжелых генераций отчета, а не счетчиком HTTP-запросов.
|
||||
|
||||
Verification:
|
||||
|
||||
- `/healthz`: `200`;
|
||||
- `/readyz`: `200`, `status=ready`;
|
||||
- prewarm after restart: `status=0/SUCCESS`;
|
||||
- cold `/api/reports?role=manager` after expired cache: `200`, около `63s`;
|
||||
- warm `/api/reports?role=manager`: `200`, около `0.34..0.35s` в трех
|
||||
последовательных запросах;
|
||||
- `awatch_reports_generated_total` не вырос после трех warm report-запросов;
|
||||
- `awatch_report_requests_total` растет на report endpoints, а
|
||||
`awatch_report_cache_hits_total` растет на warm cache-запросах;
|
||||
- во время cold/prewarm сборки `awatch_report_requests_total` показывает
|
||||
входящие report-запросы до ожидания cache lock, а
|
||||
`awatch_reports_generated_total` растет только после готового payload;
|
||||
- `workforce_operations.summary` и `workforce_operations.rows` доступны в JSON;
|
||||
- browser smoke: блок `Операционная загрузка` отрисован, строки сотрудников
|
||||
видны, console errors/warnings отсутствуют.
|
||||
|
||||
Superseded note:
|
||||
|
||||
- restart-triggered external prewarm reduced warm-cache latency, but it also
|
||||
kept a heavy full-report job coupled to service restart;
|
||||
- after the DLP/hot-path phase 1 change, the preferred production behavior is
|
||||
immediate `warming`/`STALE` API response from the portal itself, not a
|
||||
mandatory heavy `ExecStartPost` prewarm after every restart;
|
||||
- legacy drop-ins
|
||||
`/etc/systemd/system/detmir-portal.service.d/20-prod-timeout.conf` and
|
||||
`/etc/systemd/system/detmir-portal.service.d/30-prewarm-after-start.conf`
|
||||
are now treated as stale deployment residue and are removed by
|
||||
`ansible/deploy_detmir_portal.yml`.
|
||||
|
||||
## 2026-06-25: current state and first DLP hot-path boundary
|
||||
|
||||
Статус: phase 1 implemented, targeted Rust tests passed, deployed once on the
|
||||
DetMir portal host and API-smoke verified. Follow-up production cleanup of stale
|
||||
restart-prewarm drop-ins is pending until DetMir VPN handshake is stable again.
|
||||
|
||||
Фактический runtime:
|
||||
|
||||
- production `detmir-portal` binary:
|
||||
`653b22b0fbf29a22f7de42ade7b689490b1de16fa07e785e4e0efd3078e7a3bc`;
|
||||
- deploy command used:
|
||||
`ansible-playbook -i inventory.ini deploy_detmir_portal.yml --limit proxmox -e detmir_portal_bind_override=0.0.0.0:8720 -e detmir_portal_dlp_module_enabled_override=false`;
|
||||
- `/healthz`: `status=ok` after deploy;
|
||||
- `/readyz`: `status=ready` after deploy;
|
||||
- `/api/reports`: `ok=true`, `cache_status=warming`,
|
||||
`modules.dlp.enabled=false`, `modules.dlp.hot_path=false`;
|
||||
- `/api/operator`: `cache_status=warming`, `summary.severity=STALE`,
|
||||
`modules.dlp.status=disabled`, `incidents=0`;
|
||||
- server log: `/api/operator` returned `200` with `latency_ms=49`;
|
||||
- browser smoke after restart: `loadStatus=STALE`, progress `100%`,
|
||||
`LOADING=false`, `EMPTY=false`, `ERROR=false`.
|
||||
|
||||
Что это означает:
|
||||
|
||||
- первичное зависание портала устранено на уровне UX/cache/stale fallback;
|
||||
- `/api/operator` no longer waits for the cold full snapshot and can return a
|
||||
bounded `warming` payload;
|
||||
- тяжелая генерация полного отчета/snapshot все еще может быть дорогой во время
|
||||
cold/prewarm;
|
||||
- DLP/security enrichment has a first runtime boundary out of the Workforce hot
|
||||
path: phase 1 used `DETMIR_PORTAL_DLP_MODULE_ENABLED=false`; the current
|
||||
DetMir production default keeps DLP runtime disabled/`core_only`, while
|
||||
`light` remains an explicit operator re-enable profile after resource check;
|
||||
- текущее состояние зафиксировано отдельно:
|
||||
`docs/DETMIR_CURRENT_STATE_RU.md`.
|
||||
|
||||
Архитектурное решение для следующего шага:
|
||||
|
||||
- Workforce core должен оставаться быстрым и доступным без DLP;
|
||||
- DLP evidence, endpoint signals, screenshots, case review, heavy correlation
|
||||
and forensics enrichment должны стать optional module;
|
||||
- prewarm не должен обязательно выполнять heavy DLP path;
|
||||
- Security/Forensics views при отключенной DLP должны показывать disabled-state,
|
||||
а не ломать portal readiness.
|
||||
|
||||
Реализованная первая граница:
|
||||
|
||||
- CLI/env flag: `--dlp-module-enabled` /
|
||||
`DETMIR_PORTAL_DLP_MODULE_ENABLED`;
|
||||
- DetMir production default после resource hardening: `false` / `core_only`,
|
||||
чтобы обычный deploy/recovery не возвращал DLP нагрузку на Proxmox, AW,
|
||||
ClickHouse, InfluxDB и Grafana;
|
||||
- `light` допускается только как явное operator re-enable действие после
|
||||
resource check; при `light` основной portal snapshot не читает тяжелые
|
||||
incident/case/review/audit DLP state, а evidence/case/exporter path остается
|
||||
выключенным;
|
||||
- Ansible deploy parameter:
|
||||
`detmir_portal_dlp_module_enabled_override`.
|
||||
|
||||
Проверено локально:
|
||||
|
||||
- `cargo test -p detmir-portal --locked`;
|
||||
- `cargo clippy -p detmir-portal --all-targets --locked -- -D warnings`.
|
||||
|
||||
Deployment cleanup status:
|
||||
|
||||
- `ansible/deploy_detmir_portal.yml` now removes stale restart-prewarm drop-ins:
|
||||
`20-prod-timeout.conf` and `30-prewarm-after-start.conf`;
|
||||
- repeat production deploy of that cleanup is pending because the DetMir
|
||||
`pfSense-gate-UDP4-1194-vpn_prog10-config` tunnel later failed TLS handshake
|
||||
to `178.178.98.83:1194`;
|
||||
- do not claim final production prewarm cleanup until
|
||||
`systemctl cat detmir-portal` no longer shows `ExecStartPost` prewarm.
|
||||
|
||||
Ограничения:
|
||||
|
||||
- это не удаление DLP collectors;
|
||||
- это не claim, что production DLP decoupling уже завершен без live smoke;
|
||||
- это не registry release evidence;
|
||||
- GitHub/GitHub Actions не являются primary registry build contour.
|
||||
|
||||
## 2026-06-30: DLP disabled/core_only default, load guard and rollback
|
||||
|
||||
Статус: implemented in repository defaults/scripts/docs, deployed on live
|
||||
DetMir contour and verified manually.
|
||||
|
||||
Что изменено:
|
||||
|
||||
- DetMir production defaults переведены в `AW_DLP_ENABLED=false` и
|
||||
`AW_DLP_PROFILE=core_only`;
|
||||
- `aw_dlp_enabled=false`, `aw_dlp_influx_enabled=false`;
|
||||
- lightweight collector остается подключаемым, но не стартует по умолчанию;
|
||||
- heavy DLP component flags в production defaults остаются выключены;
|
||||
- `detmir_portal_dlp_module_enabled_override=false` показывает честный
|
||||
disabled-state в портале без heavy evidence/case path;
|
||||
- добавлен `scripts/detmir_dlp_load_guard.sh`;
|
||||
- `detmir-dlp-load-guard.timer` контролирует load/RAM/iowait и при перегрузе
|
||||
переводит DLP в `core_only`;
|
||||
- Ansible DLP tasks больше не имеют DLP-heavy default `true`;
|
||||
- `scripts/detmir_dlp_runtime_control.sh` получил профили
|
||||
`core_only`, `light`, `on_demand`, `full`;
|
||||
- перед каждым `set-profile` сохраняется rollback-снимок systemd
|
||||
active/enabled состояния DLP units;
|
||||
- `rollback` восстанавливает предыдущее состояние DLP units без изменения
|
||||
retention и без запуска Loki CT.
|
||||
|
||||
Эксплуатационная позиция:
|
||||
|
||||
- Loki CT отключён намеренно для снижения нагрузки на Proxmox VM/LXC;
|
||||
- Loki не является обязательной зависимостью Workforce/Worktime/AW core;
|
||||
- DLP не удалён: lightweight-сбор нужен для UEBA, а тяжелый runtime не должен
|
||||
возвращаться обычным deploy/recovery;
|
||||
- Hayabusa/Velociraptor findings остаются отдельным optional security layer
|
||||
через Security Finding Inbox / ClickHouse и не требуют Loki.
|
||||
|
||||
Runbook:
|
||||
|
||||
- `docs/DLP_RESOURCE_PROFILES_RU.md`;
|
||||
- `docs/DLP_OPTIONAL_RUNTIME_RU.md`.
|
||||
|
||||
## 2026-06-24: fail-closed timeout hardening after manual live run
|
||||
|
||||
Статус: implemented locally, targeted Rust tests passed, deployed and verified
|
||||
live.
|
||||
|
||||
Что было найдено ручным прогоном:
|
||||
|
||||
- при деградации `activitywatch-server` запросы `/api/0/buckets` и отдельные
|
||||
bucket event endpoints могли занимать 15-30 секунд;
|
||||
- `detmir-check` мог зависнуть без общего дедлайна, а штатные
|
||||
daily/weekly checks оставались в `activating`;
|
||||
- timeout в `detmir-check` убивал shell, но мог оставить `detmir-dlp`/`ssh`
|
||||
хвост, который удерживал stdout pipe;
|
||||
- `detmir-dlp` не имел собственного SSH timeout;
|
||||
- прямой `dlp-health-check --json` на AW server мог зависать дольше ожиданий;
|
||||
- `aw-worktime-autoheal-rust` считал ошибкой timeout чтения response body после
|
||||
POST backfill, хотя ActivityWatch уже мог применить запись.
|
||||
|
||||
Что изменено:
|
||||
|
||||
- `detmir-check` получил общий watchdog
|
||||
`DETMIR_CHECK_OVERALL_TIMEOUT_SECONDS` и env-настройки
|
||||
`DETMIR_SERVICE_TIMEOUT_SECONDS`, `DETMIR_BUCKET_TIMEOUT_SECONDS`,
|
||||
`DETMIR_DLP_TIMEOUT_SECONDS`;
|
||||
- production `/etc/detmir/detmir-check.env` настроен на:
|
||||
`DETMIR_SERVICE_TIMEOUT_SECONDS=35`,
|
||||
`DETMIR_BUCKET_TIMEOUT_SECONDS=35`,
|
||||
`DETMIR_DLP_TIMEOUT_SECONDS=120`,
|
||||
`DETMIR_CHECK_OVERALL_TIMEOUT_SECONDS=300`;
|
||||
- `detmir-check` и `detmir-auto` убивают timed-out child process group, чтобы
|
||||
не оставлять shell/SSH/DLP хвосты;
|
||||
- `detmir-dlp` получил bounded SSH timeout и больше не выносит SSH child в
|
||||
отдельную process group, чтобы parent timeout мог убить всю ветку;
|
||||
- `dlp-health-check` получил общий self-timeout
|
||||
`AW_DLP_HEALTH_OVERALL_TIMEOUT_SECONDS` с default 120 секунд;
|
||||
- `aw-worktime-autoheal-rust` для POST events проверяет HTTP status и не читает
|
||||
response body, потому что body не нужен для backfill evidence.
|
||||
|
||||
Safety guardrails:
|
||||
|
||||
- изменения не меняют AW API schema, bucket names, UI или product workflow;
|
||||
- timeout failure остается красным, но больше не оставляет активные процессы и
|
||||
lock poisoning;
|
||||
- production timeouts расширены только до фактической live latency, общий
|
||||
deadline остается bounded;
|
||||
- remote DLP и worktime autoheal не публикуют secrets/PII в logs сверх уже
|
||||
существующих operational identifiers.
|
||||
|
||||
Проверки:
|
||||
|
||||
```bash
|
||||
cargo test --manifest-path adk-rust/Cargo.toml \
|
||||
-p detmir-check -p detmir-auto -p detmir-dlp -p dlp-health-check \
|
||||
-p worktime-autoheal
|
||||
|
||||
cargo build --manifest-path adk-rust/Cargo.toml --release \
|
||||
-p detmir-check -p detmir-auto -p detmir-dlp -p dlp-health-check \
|
||||
-p worktime-autoheal
|
||||
```
|
||||
|
||||
Live verification:
|
||||
|
||||
- `dlp-health-check --json`: `ok=22`, `warn=0`, `fail=0`, elapsed 17s;
|
||||
- `aw-worktime-autoheal.service`: success, posted `afk=28`, `win=28`;
|
||||
- `aw-rus-healthd.service`: success, `ok=13`, `warn=1`, `fail=0`;
|
||||
- `detmir-check` through production env: `rc=0`, elapsed 19s;
|
||||
- `detmir-auto.service`: `rc=0`, elapsed 56s, bucket `dead=0`, `stale=0`,
|
||||
`ok=8`;
|
||||
- `awatch-contour-daily-check.service`: `rc=0`, elapsed 14s;
|
||||
- `awatch-contour-weekly-check.service`: `rc=0`, elapsed 136s;
|
||||
- `check-aw-full.sh`: `FRESH=8`, `STALE=0`, `DEAD=0`;
|
||||
- final AW/PVE failed systemd units: `0`;
|
||||
- final RDP guard: service `Running`, 13 telemetry processes, last guard cycles
|
||||
`status=ok problems=0`.
|
||||
|
||||
## 2026-06-30: manual collection and analysis smoke after DLP light enablement
|
||||
|
||||
Статус: partially green, live fixes applied, one external reachability blocker
|
||||
remains.
|
||||
|
||||
Ручной прогон подтвердил:
|
||||
|
||||
- `activitywatch-server` and `aw-worktime-api` are active;
|
||||
- Worktime API `/reports/worktime/today` returns current data for 4 users;
|
||||
- DetMir portal `/portal` renders through browser and no frontend console error
|
||||
was observed for the tested portal pages;
|
||||
- `/api/manager` returns OK after restoring the portal timeout to 25 seconds;
|
||||
- `/api/operator` returns current collection/DLP/Grafana/1C/worktime blocks;
|
||||
- Security Finding Inbox is reachable for `security`/`admin` role headers and
|
||||
returns ClickHouse backend `status=ok`, `open_count=0`;
|
||||
- DLP light warehouse is present on the portal host and DLP checks show OK in
|
||||
the operator card;
|
||||
- Grafana backend is reachable directly at `10.10.10.11:3000/api/health`.
|
||||
|
||||
Live fixes applied:
|
||||
|
||||
- removed stale systemd drop-in
|
||||
`/etc/systemd/system/detmir-portal.service.d/10-detmir-check-env.conf`;
|
||||
- restored `/etc/detmir-portal.env` timeout to
|
||||
`DETMIR_PORTAL_TIMEOUT_SECONDS=25`;
|
||||
- updated `/etc/detmir/detmir-check.env` for the current light profile:
|
||||
`DETMIR_DLP_ENABLED=true` and `DETMIR_DISABLE_DLP_HEALTH_CHECK=true`;
|
||||
- updated `/var/lib/detmir-ai/latest-run` to the fresh 2026-06-30
|
||||
`detmir-check` JSON so the portal no longer displays the stale 2026-06-25
|
||||
collection snapshot;
|
||||
- updated Ansible to remove the stale portal timeout override during deploy.
|
||||
|
||||
Remaining live blocker:
|
||||
|
||||
- `detmir-check` still fails by design because RDP host `192.168.100.19`
|
||||
responds to ICMP, but TCP `22` and `5985` time out from the DetMir contour;
|
||||
- `awatch-contour-daily-check.service` therefore remains failed with
|
||||
`service_failures=2`;
|
||||
- this is not an AW-server, Worktime API, DLP warehouse, ClickHouse, or portal
|
||||
rendering failure. It is the current RDP control/reachability failure.
|
||||
|
||||
Grafana note:
|
||||
|
||||
- Browser access to Grafana through the gateway is protected by Basic Auth and
|
||||
the current certificate chain is not trusted by the Playwright browser when
|
||||
opened by IP/DNS in this run;
|
||||
- direct backend health check is green:
|
||||
`http://10.10.10.11:3000/api/health -> 200`;
|
||||
- gateway returns `401` without credentials, which is expected for the
|
||||
protected dashboard entrypoint.
|
||||
@@ -4,6 +4,12 @@ Explainable Workforce KPI отвечает на вопрос: почему по
|
||||
активности. Слой предназначен для руководителя, ИБ и администратора, но не
|
||||
является HR-оценкой сотрудника и не использует ML/LLM.
|
||||
|
||||
Смежный, но отдельный contract по операционной загрузке описан в
|
||||
[WORKFORCE_OPERATIONS_MODEL_RU.md](WORKFORCE_OPERATIONS_MODEL_RU.md). KPI
|
||||
объясняет процент активности, а Workforce Operations показывает загрузку,
|
||||
простои, перегруз, дисциплину процесса, достоверность данных и рекомендуемое
|
||||
ручное действие.
|
||||
|
||||
## API
|
||||
|
||||
Endpoint:
|
||||
@@ -102,6 +108,10 @@ Security и Forensics не получают Workforce Dashboard через `/api
|
||||
Раздел содержит KPI score, confidence, coverage, факторы, warnings и
|
||||
рекомендации.
|
||||
|
||||
Блок `Операционная загрузка` в портале использует другой payload:
|
||||
`workforce_operations`. Он не заменяет explainable KPI и не должен
|
||||
интерпретироваться как автоматическая HR-оценка.
|
||||
|
||||
## Ограничения Pilot v1
|
||||
|
||||
- Это не ML и не LLM.
|
||||
|
||||
@@ -83,6 +83,11 @@ gateway:
|
||||
/d/detmir-rdp-user-activity/detmir3a-rabota-pol-zovatelej-v-rdp?orgId=1&from=now-7d&to=now&timezone=browser&var-host=SHARKON2025&refresh=5m
|
||||
```
|
||||
|
||||
`var-host=SHARKON2025` здесь является stable logical host id, а не требованием
|
||||
к физическому Windows `COMPUTERNAME`. При переименовании RDP-сервера dashboard
|
||||
должен продолжать смотреть на тот же logical id до отдельной planned migration.
|
||||
См. `docs/WINDOWS_LOGICAL_HOST_ID_RU.md`.
|
||||
|
||||
В портале он доступен как кнопка `Графики сотрудников`.
|
||||
|
||||
Не включайте `[auth.anonymous]` для решения этой задачи: это откроет Grafana на
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
## Workforce сценарий
|
||||
|
||||
- Отображается индекс активности и объяснение факторов.
|
||||
- Отображается блок `Операционная загрузка`: загрузка, простой, перегруз,
|
||||
дисциплина процесса и достоверность данных.
|
||||
- Доступно сравнение подразделений и ответственных.
|
||||
- Видны тренды daily, weekly и monthly, если данные есть.
|
||||
- Отдельно показываются признаки перегрузки и недозагрузки.
|
||||
|
||||
@@ -46,6 +46,51 @@ React/Tauri-интерфейса без переписывания backend-ло
|
||||
- `GET /api/readiness/latest` - готовность системы;
|
||||
- `GET /api/workforce/policy/explain` - объяснение расчёта показателей.
|
||||
|
||||
`GET /api/reports` должен сохранять additive payload `workforce_operations`.
|
||||
Это основной contract для экрана руководителя по загрузке, простоям, перегрузу,
|
||||
дисциплине процесса и достоверности данных. Клиент должен читать:
|
||||
|
||||
- `workforce_operations.summary`;
|
||||
- `workforce_operations.rows`;
|
||||
- `workforce_operations.model`;
|
||||
- `workforce_operations.rows[].load_status`;
|
||||
- `workforce_operations.rows[].idle_status`;
|
||||
- `workforce_operations.rows[].discipline_status`;
|
||||
- `workforce_operations.rows[].data_confidence`;
|
||||
- `workforce_operations.rows[].recommended_action`.
|
||||
|
||||
Подробная семантика статусов:
|
||||
[WORKFORCE_OPERATIONS_MODEL_RU.md](WORKFORCE_OPERATIONS_MODEL_RU.md).
|
||||
|
||||
`GET /api/reports` также публикует additive payload `modules.dlp`.
|
||||
Клиент должен трактовать его как runtime capability, а не как claim
|
||||
сертифицированной DLP:
|
||||
|
||||
- `modules.dlp.enabled`;
|
||||
- `modules.dlp.status`;
|
||||
- `modules.dlp.hot_path`;
|
||||
- `modules.dlp.note`.
|
||||
|
||||
Если `modules.dlp.enabled=false`, Workforce UI должен продолжать работу и
|
||||
показывать DLP/Security/Forensics как disabled или not configured, не превращая
|
||||
это в ошибку основного рабочего экрана.
|
||||
|
||||
`GET /api/operator` также публикует additive runtime-state поля для первичного
|
||||
экрана:
|
||||
|
||||
- `cache_status`;
|
||||
- `modules.dlp.enabled`;
|
||||
- `modules.dlp.status`;
|
||||
- `modules.dlp.hot_path`;
|
||||
- `modules.dlp.note`;
|
||||
- `summary.severity`;
|
||||
- `summary.blocks`.
|
||||
|
||||
Если `cache_status=warming`, клиент должен показать bounded stale/warming
|
||||
state и не держать бесконечный loading indicator. Если
|
||||
`modules.dlp.enabled=false`, operator screen должен считать DLP disabled-state
|
||||
допустимым состоянием, а не ошибкой Workforce core.
|
||||
|
||||
## Что не меняется
|
||||
|
||||
- HTML-портал не удаляется.
|
||||
|
||||
@@ -50,6 +50,13 @@ Security layer:
|
||||
|
||||
Это не полноценная SIEM и не сертифицированная DLP.
|
||||
|
||||
Heavy DLP processing is not part of the required Workforce hot path. DLP
|
||||
endpoint signals, screenshots, evidence review, heavy correlation and forensics
|
||||
enrichment are treated as optional/deployment-specific modules. If the DLP
|
||||
module is disabled or not configured, core Workforce reports and portal
|
||||
readiness must remain available and the Security/Forensics views must show an
|
||||
honest disabled/not configured state.
|
||||
|
||||
## Forensics Core
|
||||
|
||||
Forensics layer:
|
||||
@@ -68,6 +75,7 @@ Optional addons and deployment-specific directions:
|
||||
|
||||
- pfSense;
|
||||
- 1C;
|
||||
- DLP endpoint signals and evidence workflow;
|
||||
- AD/LDAP;
|
||||
- SIEM/syslog;
|
||||
- external storage;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=DetMir portal report cache prewarm
|
||||
After=network-online.target detmir-portal.service
|
||||
Wants=network-online.target detmir-portal.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=igor
|
||||
Group=igor
|
||||
Environment=no_proxy=localhost,127.0.0.1,10.10.10.2
|
||||
Environment=NO_PROXY=localhost,127.0.0.1,10.10.10.2
|
||||
ExecStart=/usr/bin/curl -fsS --max-time 180 http://127.0.0.1:8720/api/reports -o /dev/null
|
||||
TimeoutStartSec=210
|
||||
Nice=19
|
||||
IOSchedulingClass=idle
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Pre-warm DetMir portal report cache every 30 minutes
|
||||
|
||||
[Timer]
|
||||
OnBootSec=5min
|
||||
OnUnitActiveSec=30min
|
||||
AccuracySec=1min
|
||||
Persistent=true
|
||||
Unit=detmir-portal-prewarm.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,2 @@
|
||||
[Service]
|
||||
ExecStartPost=/bin/systemctl --no-block start detmir-portal-prewarm.service
|
||||
Reference in New Issue
Block a user