Changes between Initial Version and Version 1 of OtherTopics


Ignore:
Timestamp:
08/24/26 18:55:19 (6 weeks ago)
Author:
231118
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • OtherTopics

    v1 v1  
     1= Other Topics =
     2
     3== SQL Performance ==
     4Documented performance analysis for complex analytical queries executed in PostgreSQL (project schema, v04). We utilized the `EXPLAIN (ANALYZE, BUFFERS)` paradigm to isolate structural bottlenecks before and after implementing precise indexes, as well as optimizing time-window filters for high selectivity.
     5
     6=== Report 1: Top Outbound Connections by Process ===
     7* '''Query Description:''' Evaluates massive volumes of raw outbound network connection logs (`network_connections_history`) mapped inside a time-bounded window via CTE expressions to detect process-level traffic volume.
     8* '''Proposed Indexes:'''
     9{{{
     10#!sql
     11CREATE INDEX idx_nch_timestamp_comp ON network_connections_history (timestamp, computer_id);
     12CREATE INDEX idx_computers_tenant_env ON computers (tenant_id, env_name);
     13}}}
     14
     15==== Execution Plan Analysis ====
     16* '''Before Index Creation:'''
     17  * Plan Output: `Seq Scan on network_connections_history nc` (Rows Removed by Filter: ~96,647 — the engine is forced to perform an expansive sequential evaluation across log records).
     18  * Execution Time: 73.836 ms
     19[[Image(ss1_before.png)]]
     20
     21* '''After Index Creation (Optimized Time-Window Filter):'''
     22  * Plan Output: `Bitmap Index Scan using idx_nch_timestamp_comp` feeding a `Bitmap Heap Scan on network_connections_history nc`.
     23  * Execution Time: 14.924 ms
     24[[Image(ss1_after.2.png)]]
     25
     26* '''Index Usage Verification:''' Yes, the PostgreSQL engine bypassed raw relational sequential evaluation and bound query execution directly via index nodes inside the initial windowed CTE materialization.
     27* '''Conclusion:''' Performance scaled by over '''79%''' (73.8 ms → 14.9 ms), successfully shifting execution path to targeted bitmap index scans.
     28
     29---
     30
     31=== Report 2: Unresolved Security Alerts by Severity ===
     32* '''Query Description:''' Groups and breaks down security events across custom temporal partitions using aggregations to gauge environmental vulnerability baselines.
     33* '''Proposed Index:'''
     34{{{
     35#!sql
     36CREATE INDEX idx_sa_timestamp_comp ON security_alerts (timestamp, computer_id, resolved);
     37}}}
     38
     39==== Execution Plan Analysis ====
     40* '''Before Index Creation:'''
     41  * Plan Output: `Seq Scan on security_alerts sa` (Rows Removed by Filter: ~96,604 — forced sequential full table scan).
     42  * Execution Time: 59.983 ms
     43[[Image(ss2_before.png)]]
     44
     45* '''After Index Creation (Optimized Time-Window Filter):'''
     46  * Plan Output: `Bitmap Index Scan using idx_sa_timestamp_comp` feeding a `Bitmap Heap Scan on security_alerts sa`.
     47  * Execution Time: 8.799 ms
     48[[Image(ss2_after.png)]]
     49
     50* '''Index Usage Verification:''' Yes, explicitly verified. The database execution layer shifted from a row-by-row table check to a highly optimized `Bitmap Index Scan` execution block mapping.
     51* '''Conclusion:''' Performance scaled by over '''85%''' (59.9 ms → 8.8 ms), successfully validating index utilization under optimal predicate selectivity conditions.
     52
     53---
     54
     55=== Report 3: Resource Hotspots (CPU/RAM Overload) ===
     56* '''Query Description:''' Evaluates structural system telemetry logs (`computer_history`) over a time range to flag target hosts with utilization breaches.
     57* '''Proposed Index:'''
     58{{{
     59#!sql
     60CREATE INDEX idx_ch_timestamp_comp ON computer_history (timestamp, computer_id);
     61}}}
     62
     63==== Execution Plan Analysis ====
     64* '''Before Index Creation:'''
     65  * Plan Output: `Seq Scan on computer_history ch` (Rows Removed by Filter: ~96,671) causing an expensive down-stream HashAggregate step across historical partitions.
     66  * Execution Time: 61.481 ms
     67[[Image(ss3_before.png)]]
     68
     69* '''After Index Creation:'''
     70  * Plan Output: `Bitmap Index Scan using idx_ch_timestamp_comp` feeding a `Bitmap Heap Scan on computer_history ch`.
     71  * Execution Time: 3.664 ms
     72[[Image(ss3_after.png)]]
     73
     74* '''Index Usage Verification:''' Yes, successfully achieved an Index path, eliminating the need to parse raw heap blocks.
     75* '''Conclusion:''' Performance scaled up by over '''94%''' (61.5 ms → 3.7 ms), preventing telemetry logging pipelines from bottlenecking.
     76
     77---
     78
     79=== Report 6: Sysmon Event Anomaly Detection (Complex CTE) ===
     80* '''Query Description:''' Deep analytical CTE query calculating overall infrastructural averages to isolate anomalous logging events 1.5x above baseline values using `CROSS JOIN` evaluations.
     81* '''Proposed Index:'''
     82{{{
     83#!sql
     84CREATE INDEX idx_se_timestamp_comp ON sysmon_events (timestamp, computer_id);
     85}}}
     86
     87==== Execution Plan Analysis ====
     88* '''Before Index Creation:'''
     89  * Plan Output: `Seq Scan on sysmon_events se` (Rows Removed by Filter: ~96,619) across the CTE sub-trees to calculate environmental averages.
     90  * Execution Time: 240.350 ms
     91[[Image(ss6_before.png)]]
     92
     93* '''After Index Creation:'''
     94  * Plan Output: `Index Only Scan using idx_se_timestamp_comp on sysmon_events se` (Heap Fetches: 0 — served entirely from the index).
     95  * Execution Time: 1.403 ms
     96[[Image(ss6_after.png)]]
     97
     98* '''Index Usage Verification:''' Yes — achieved an `Index Only Scan` (Heap Fetches: 0), the optimal access path.
     99* '''Conclusion:''' Execution times dropped by over '''99%''' (240.4 ms → 1.4 ms), allowing heavy statistical parsing to complete efficiently.
     100
     101---
     102== Security Measures ==
     103
     104=== Application-Level Security ===
     105To secure database interactions within the application stack, the following measures have been programmatically enforced:
     106 * '''Prevention of SQL Injection (SQLi):''' All queries use parameterized statements (sqlite3 placeholders `?`) in the Flask backend, strictly separating SQL code from parameters. User-supplied values are never concatenated into SQL strings. (The planned PostgreSQL migration adds the SQLAlchemy layer.)
     107 * '''Prevention of Un-authorized Access:''' Implementation of custom decorators `@require_user()` and `@require_tenant_admin()` to intercept endpoints and force strict JWT validation before any data access.
     108
     109=== Database-Level Security ===
     110The database-side protections include:
     111 * '''Prevention of SQL Injection in Dynamic Queries:''' Avoiding manual string formatting (f-strings or `%s` concatenation) with user input. All dynamically evaluated filtering explicitly passes parameter tuples.
     112 * '''Prevention of Un-authorized Access to Data:''' Multi-tenant structural architecture where every row manipulation isolates and constrains queries via a verified `tenant_id` (and, for agents, a valid `X-Env-Token`).
     113
     114---
     115
     116== Other Developments ==
     117
     118=== JWT автентикација и авторизација ===
     119Системот користи JWT (JSON Web Token) за автентикација на корисниците по успешна Google најава.
     120
     121Процесот се состои од следните чекори:
     122 1. Корисникот се најавува преку Google OAuth.
     123 2. Серверот го верификува Google токенот.
     124 3. Доколку најавата е успешна, серверот креира JWT токен кој содржи: `user_id`, `email`, `role`, `tenant_id`.
     125 4. JWT токенот се зачувува во HttpOnly cookie со име `session`.
     126 5. При секое наредно барање прелистувачот автоматски го испраќа cookie-то.
     127 6. Серверот го верификува JWT токенот и ги чита корисничките информации.
     128
     129'''Креирање на JWT токен:'''
     130{{{
     131#!python
     132def make_jwt(payload: dict, minutes=60 * 24):
     133    exp = datetime.utcnow() + timedelta(minutes=minutes)
     134    data = {**payload, "iss": JWT_ISSUER, "exp": exp}
     135    return jwt.encode(data, JWT_SECRET, algorithm="HS256")
     136}}}
     137
     138'''Проверка на JWT токен:'''
     139{{{
     140#!python
     141def read_jwt(token: str):
     142    return jwt.decode(
     143        token,
     144        JWT_SECRET,
     145        algorithms=["HS256"],
     146        issuer=JWT_ISSUER
     147    )
     148}}}
     149
     150Пристапот до заштитените API рути е овозможен преку декораторите `@require_user` и `@require_tenant_admin`.
     151{{{
     152#!python
     153@require_user()
     154def api_me():
     155    ...
     156}}}
     157
     158=== CORS конфигурација ===
     159Бидејќи frontend апликацијата и Flask серверот работат на различни адреси, потребно е овозможување на Cross-Origin Resource Sharing (CORS).
     160
     161Во системот е конфигурирана листа на дозволени домени:
     162{{{
     163#!python
     164DEFAULT_ORIGINS = [
     165    "http://localhost:5173",
     166    "http://127.0.0.1:5173",
     167]
     168}}}
     169
     170Конфигурацијата се извршува преку Flask-CORS:
     171{{{
     172#!python
     173CORS(
     174    app,
     175    supports_credentials=True,
     176    origins=ALLOWED_ORIGINS,
     177    allow_headers=[
     178        "Content-Type",
     179        "X-Admin-Session",
     180        "X-Env",
     181        "X-Env-Token",
     182    ],
     183    methods=["GET", "POST", "OPTIONS"],
     184)
     185}}}
     186 * Се дозволуваат барања само од доверливи frontend адреси.
     187 * Се дозволува испраќање на JWT cookie преку `supports_credentials=True`.
     188 * Се ограничуваат HTTP методите на GET, POST и OPTIONS.
     189 * Се контролира кои HTTP заглавија може да се испраќаат кон серверот.
     190
     191=== Безбедносен модел ===
     192Системот користи повеќеслојна безбедност:
     193 * Google OAuth за верификација на идентитетот.
     194 * JWT токени за одржување на корисничка сесија.
     195 * HttpOnly cookies за заштита од JavaScript пристап до токените.
     196 * CORS политика за ограничување на дозволените клиентски апликации.
     197 * Tenant изолација преку `tenant_id`.
     198 * Посебни environment токени (`X-Env-Token`) за комуникација помеѓу агентите и серверот.