Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(pr4): add aisoc-osquery-tls FastAPI service and aisoc-direct connector
Beenu7425dd70e231
diff --git a/docker-compose.yml b/docker-compose.ymlindex 95bcc6a29..4f9262d67 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -330,6 +330,26 @@ services:- aisocrestart: unless-stopped+ osquery-tls:+ build:+ context: ./services/osquery-tls+ dockerfile: Dockerfile+ container_name: aisoc-osquery-tls+ depends_on:+ postgres:+ condition: service_healthy+ ports:+ - "127.0.0.1:8007:8007"+ profiles:+ - osquery+ environment:+ DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_dev_secret@postgres:5432/aisoc+ AISOC_OSQUERY_TLS_ENROLL_SECRET: ${AISOC_OSQUERY_TLS_ENROLL_SECRET:-change-me-in-production}+ AISOC_INGEST_BASE_URL: http://ingest:8080+ networks:+ - aisoc+ restart: unless-stopped+actions:build:context: ./services/actionsdiff --git a/infra/terraform/main.tf b/infra/terraform/main.tfindex 9411cebce..0a11a0301 100644--- a/infra/terraform/main.tf+++ b/infra/terraform/main.tf@@ -146,6 +146,29 @@ module "kafka" {allowed_security_groups = [module.eks.node_security_group_id]}+module "osquery_tls" {+ source = "./modules/osquery-tls"++ namespace = "aisoc"+ create_namespace = false++ image_repository = "ghcr.io/aisoc-community/osquery-tls"+ image_tag = var.osquery_tls_image_tag++ replicas = var.osquery_tls_replicas++ enroll_secret = var.osquery_tls_enroll_secret+ database_url = "postgresql+asyncpg://${var.db_username}:${module.rds.db_password}@${module.rds.endpoint}/aisoc"+ ingest_base_url = "http://aisoc-ingest.aisoc.svc.cluster.local:8080"++ autoscaling = {+ enabled = true+ min_replicas = var.osquery_tls_replicas+ max_replicas = var.osquery_tls_replicas * 5+ target_cpu_utilization = 70+ }+}+# ─── Outputs ──────────────────────────────────────────────────────────────────output "eks_cluster_name" {@@ -181,3 +204,8 @@ output "vpc_id" {description = "VPC ID"value = module.vpc.vpc_id}++output "osquery_tls_internal_url" {+ description = "In-cluster URL for the osquery-tls TLS endpoint"+ value = module.osquery_tls.internal_url+}diff --git a/infra/terraform/modules/osquery-tls/main.tf b/infra/terraform/modules/osquery-tls/main.tfnew file mode 100644index 000000000..8a9d6482f--- /dev/null+++ b/infra/terraform/modules/osquery-tls/main.tf@@ -0,0 +1,219 @@+/**+ * AiSOC — osquery-tls Terraform Module+ *+ * Deploys the aisoc-osquery-tls FastAPI service on Kubernetes (EKS).+ * Handles TLS enrollment, config distribution, log ingestion, and+ * distributed query lifecycle for osqueryd agents.+ */++# ─── Namespace ────────────────────────────────────────────────────────────────++resource "kubernetes_namespace" "osquery_tls" {+ count = var.create_namespace ? 1 : 0++ metadata {+ name = var.namespace+ labels = {+ "app.kubernetes.io/managed-by" = "terraform"+ "app.kubernetes.io/part-of" = "aisoc"+ }+ }+}++locals {+ namespace = var.create_namespace ? kubernetes_namespace.osquery_tls[0].metadata[0].name : var.namespace+}++# ─── Secret ───────────────────────────────────────────────────────────────────++resource "kubernetes_secret" "osquery_tls" {+ metadata {+ name = "aisoc-osquery-tls"+ namespace = local.namespace+ labels = local.common_labels+ }++ data = {+ enroll-secret = var.enroll_secret+ database-url = var.database_url+ ingest-base-url = var.ingest_base_url+ }+}++# ─── Deployment ───────────────────────────────────────────────────────────────++resource "kubernetes_deployment" "osquery_tls" {+ metadata {+ name = "aisoc-osquery-tls"+ namespace = local.namespace+ labels = local.common_labels+ }++ spec {+ replicas = var.replicas++ selector {+ match_labels = {+ "app.kubernetes.io/name" = "aisoc-osquery-tls"+ }+ }++ template {+ metadata {+ labels = local.common_labels+ annotations = {+ "checksum/secret" = sha256(jsonencode(kubernetes_secret.osquery_tls.data))+ }+ }++ spec {+ container {+ name = "osquery-tls"+ image = "${var.image_repository}:${var.image_tag}"++ port {+ name = "http"+ container_port = 8007+ protocol = "TCP"+ }++ env {+ name = "AISOC_OSQUERY_TLS_ENROLL_SECRET"+ value_from {+ secret_key_ref {+ name = kubernetes_secret.osquery_tls.metadata[0].name+ key = "enroll-secret"+ }+ }+ }++ env {+ name = "DATABASE_URL"+ value_from {+ secret_key_ref {+ name = kubernetes_secret.osquery_tls.metadata[0].name+ key = "database-url"+ }+ }+ }++ env {+ name = "AISOC_INGEST_BASE_URL"+ value_from {+ secret_key_ref {+ name = kubernetes_secret.osquery_tls.metadata[0].name+ key = "ingest-base-url"+ }+ }+ }++ resources {+ requests = {+ cpu = var.resources.requests.cpu+ memory = var.resources.requests.memory+ }+ limits = {+ cpu = var.resources.limits.cpu+ memory = var.resources.limits.memory+ }+ }++ liveness_probe {+ http_get {+ path = "/healthz"+ port = "http"+ }+ initial_delay_seconds = 15+ period_seconds = 30+ timeout_seconds = 5+ failure_threshold = 3+ }++ readiness_probe {+ http_get {+ path = "/healthz"+ port = "http"+ }+ initial_delay_seconds = 10+ period_seconds = 10+ timeout_seconds = 3+ failure_threshold = 3+ }+ }++ termination_grace_period_seconds = 30+ }+ }+ }+}++# ─── Service ──────────────────────────────────────────────────────────────────++resource "kubernetes_service" "osquery_tls" {+ metadata {+ name = "aisoc-osquery-tls"+ namespace = local.namespace+ labels = local.common_labels+ }++ spec {+ selector = {+ "app.kubernetes.io/name" = "aisoc-osquery-tls"+ }++ port {+ name = "http"+ port = 8007+ target_port = "http"+ protocol = "TCP"+ }++ type = "ClusterIP"+ }+}++# ─── HPA (optional) ───────────────────────────────────────────────────────────++resource "kubernetes_horizontal_pod_autoscaler_v2" "osquery_tls" {+ count = var.autoscaling.enabled ? 1 : 0++ metadata {+ name = "aisoc-osquery-tls"+ namespace = local.namespace+ labels = local.common_labels+ }++ spec {+ scale_target_ref {+ api_version = "apps/v1"+ kind = "Deployment"+ name = kubernetes_deployment.osquery_tls.metadata[0].name+ }++ min_replicas = var.autoscaling.min_replicas+ max_replicas = var.autoscaling.max_replicas++ metric {+ type = "Resource"+ resource {+ name = "cpu"+ target {+ type = "Utilization"+ average_utilization = var.autoscaling.target_cpu_utilization+ }+ }+ }+ }+}++# ─── Locals ───────────────────────────────────────────────────────────────────++locals {+ common_labels = {+ "app.kubernetes.io/name" = "aisoc-osquery-tls"+ "app.kubernetes.io/component" = "osquery-tls"+ "app.kubernetes.io/part-of" = "aisoc"+ "app.kubernetes.io/managed-by" = "terraform"+ "app.kubernetes.io/version" = var.image_tag+ }+}diff --git a/infra/terraform/modules/osquery-tls/outputs.tf b/infra/terraform/modules/osquery-tls/outputs.tfnew file mode 100644index 000000000..77b637ae1--- /dev/null+++ b/infra/terraform/modules/osquery-tls/outputs.tf@@ -0,0 +1,29 @@+output "service_name" {+ description = "Kubernetes Service name for aisoc-osquery-tls"+ value = kubernetes_service.osquery_tls.metadata[0].name+}++output "service_namespace" {+ description = "Kubernetes namespace the service is deployed in"+ value = local.namespace+}++output "service_cluster_ip" {+ description = "ClusterIP allocated to the service"+ value = kubernetes_service.osquery_tls.spec[0].cluster_ip+}++output "service_port" {+ description = "Port the service listens on"+ value = 8007+}++output "deployment_name" {+ description = "Kubernetes Deployment name"+ value = kubernetes_deployment.osquery_tls.metadata[0].name+}++output "internal_url" {+ description = "In-cluster URL for other services to reach osquery-tls"+ value = "http://${kubernetes_service.osquery_tls.metadata[0].name}.${local.namespace}.svc.cluster.local:8007"+}diff --git a/infra/terraform/modules/osquery-tls/variables.tf b/infra/terraform/modules/osquery-tls/variables.tfnew file mode 100644index 000000000..7651f36a7--- /dev/null+++ b/infra/terraform/modules/osquery-tls/variables.tf@@ -0,0 +1,87 @@+variable "namespace" {+ description = "Kubernetes namespace to deploy into"+ type = string+ default = "aisoc"+}++variable "create_namespace" {+ description = "Whether to create the namespace (set false if it already exists)"+ type = bool+ default = false+}++variable "image_repository" {+ description = "Container image repository for aisoc-osquery-tls"+ type = string+ default = "ghcr.io/aisoc-community/osquery-tls"+}++variable "image_tag" {+ description = "Container image tag"+ type = string+ default = "latest"+}++variable "replicas" {+ description = "Number of pod replicas"+ type = number+ default = 2+}++variable "enroll_secret" {+ description = "Shared secret that osqueryd agents must present during enrollment"+ type = string+ sensitive = true+}++variable "database_url" {+ description = "PostgreSQL connection URL (asyncpg driver)"+ type = string+ sensitive = true+}++variable "ingest_base_url" {+ description = "Base URL for the AiSOC ingest service"+ type = string+ default = "http://aisoc-ingest:8080"+}++variable "resources" {+ description = "CPU and memory resource requests/limits"+ type = object({+ requests = object({+ cpu = string+ memory = string+ })+ limits = object({+ cpu = string+ memory = string+ })+ })+ default = {+ requests = {+ cpu = "100m"+ memory = "128Mi"+ }+ limits = {+ cpu = "500m"+ memory = "512Mi"+ }+ }+}++variable "autoscaling" {+ description = "Horizontal Pod Autoscaler settings"+ type = object({+ enabled = bool+ min_replicas = number+ max_replicas = number+ target_cpu_utilization = number+ })+ default = {+ enabled = true+ min_replicas = 2+ max_replicas = 10+ target_cpu_utilization = 70+ }+}diff --git a/infra/terraform/variables.tf b/infra/terraform/variables.tfindex 586e3c4b0..c4e7dab00 100644--- a/infra/terraform/variables.tf+++ b/infra/terraform/variables.tf@@ -72,3 +72,21 @@ variable "kafka_instance_type" {type = stringdefault = "kafka.m5.large"}++variable "osquery_tls_image_tag" {+ description = "Container image tag for aisoc-osquery-tls"+ type = string+ default = "latest"+}++variable "osquery_tls_replicas" {+ description = "Baseline pod replica count for aisoc-osquery-tls"+ type = number+ default = 2+}++variable "osquery_tls_enroll_secret" {+ description = "Shared enroll secret for osqueryd agent authentication"+ type = string+ sensitive = true+}diff --git a/plugins/aisoc-direct/plugin.yaml b/plugins/aisoc-direct/plugin.yamlnew file mode 100644index 000000000..a5116c433--- /dev/null+++ b/plugins/aisoc-direct/plugin.yaml@@ -0,0 +1,69 @@+id: aisoc-direct+name: AiSOC Direct (osquery TLS)+description: >+ Virtual connector that receives osquery telemetry from agents enrolled+ directly against AiSOC's built-in TLS endpoint (services/osquery-tls).+ No external fleet manager is required.+version: "0.1.0"+category: edr+author: AiSOC Community+license: MIT++schema:+ name: aisoc-direct+ label: AiSOC Direct osquery TLS+ description: >+ Connects osqueryd agents directly to AiSOC without osctrl or FleetDM.+ Agents enroll using an enroll_secret and receive a node_key in return.+ Scheduled queries and distributed (ad-hoc) queries are served over the+ standard osquery TLS plugin endpoints.+ category: edr+ fields:+ - name: enroll_secret+ label: Enroll Secret+ description: >+ The shared secret osqueryd agents use to authenticate during+ enrollment. Must match AISOC_OSQUERY_TLS_ENROLL_SECRET on the+ osquery-tls service.+ type: string+ secret: true+ required: true+ - name: base_url+ label: TLS Endpoint URL+ description: >+ Base URL of the AiSOC osquery TLS service, e.g.+ https://osquery.tryaisoc.com. Agents use this as their+ --tls_hostname flag.+ type: string+ required: true+ default: https://osquery.tryaisoc.com+ - name: tenant_id+ label: Tenant ID+ description: >+ AiSOC tenant identifier. Sent by the service as the+ X-AiSOC-Tenant request header. Leave empty for single-tenant+ deployments.+ type: string+ required: false+ oauth: false+ default_poll_interval_seconds: 300++event_types:+ - osquery_query_row++severity_levels:+ - info+ - low+ - medium+ - high++normalized_fields:+ - event_type+ - source+ - tenant_id+ - host_identifier+ - query_name+ - log_type+ - severity+ - raw+ - timestampdiff --git a/services/actions/app/clients/aisoc_direct_client.py b/services/actions/app/clients/aisoc_direct_client.pyindex af677a68c..e4e718949 100644--- a/services/actions/app/clients/aisoc_direct_client.py+++ b/services/actions/app/clients/aisoc_direct_client.py@@ -1,21 +1,24 @@-"""Stub async client for the AiSOC-direct osquery TLS endpoint.+"""Async client for the AiSOC built-in osquery TLS endpoint.-This module satisfies the ``osquery_live_query`` playbook step contract in-PR 3 so that playbooks can reference ``backend: aisoc_direct`` without any-implementation yet. The full implementation (including HTTP calls to the-``services/osquery-tls`` FastAPI service) will land in PR 4 once that service-is built.+Communicates with ``services/osquery-tls`` to enqueue distributed queries+and poll for their results. This is used by the ``osquery_live_query``+playbook step when ``backend: aisoc_direct`` is configured.-Attempting to call :meth:`AiSOCDirectClient.live_query` in this stub will-raise :class:`NotImplementedError` with a descriptive message. This surfaces-clearly in playbook dry-runs and CI before PR 4 ships.+Authentication uses a bearer token passed in the ``Authorization`` header.+The token is typically an internal service-account secret managed the same+way as any other AiSOC credential."""-from __future__ import annotations+import asyncio+import loggingfrom typing import Any-from app.clients.osquery_allowlist import AllowlistError, render_query+import httpx++from app.clients.osquery_allowlist import render_query++logger = logging.getLogger(__name__)class AiSOCDirectError(RuntimeError):@@ -23,25 +26,19 @@ class AiSOCDirectError(RuntimeError):class AiSOCDirectClient:- """Stub client for the AiSOC built-in osquery TLS endpoint.-- .. note::-- **This is a PR-3 stub.** The HTTP implementation will be added in PR 4- once ``services/osquery-tls/`` is available.+ """Async client for the AiSOC built-in osquery TLS service.Parameters----------base_url:Root URL of the ``services/osquery-tls`` FastAPI service, e.g.- ``http://osquery-tls:8080``. Ignored by the stub; preserved for- interface compatibility with the real implementation.+ ``http://osquery-tls:8080``.api_token:- Bearer token for the osquery-tls service. Ignored by the stub.+ Bearer token presented as ``Authorization: Bearer <token>``.verify_tls:- Whether to verify TLS. Ignored by the stub.+ Whether to verify TLS when the service is behind HTTPS.poll_interval:- Polling cadence in seconds. Ignored by the stub.+ Polling cadence in seconds between /distributed/status checks."""def __init__(@@ -56,6 +53,9 @@ class AiSOCDirectClient:self._verify_tls = verify_tlsself._poll_interval = poll_interval+ def _headers(self) -> dict[str, str]:+ return {"Authorization": f"Bearer {self._api_token}"}+async def live_query(self,target_hosts: list[str],@@ -63,33 +63,112 @@ class AiSOCDirectClient:template_params: dict[str, Any] | None = None,timeout_seconds: int = 60,) -> dict[str, Any]:- """Stub — always raises :class:`NotImplementedError`.+ """Run a distributed osquery query against a set of hosts.++ Enqueues the query via ``POST /api/v1/osquery/distributed/enqueue``+ and polls ``GET /api/v1/osquery/distributed/{query_id}`` until all+ target hosts respond or the timeout expires.Parameters----------target_hosts:- List of target host identifiers.+ List of ``host_identifier`` values to target.template:- Allowlist template ID (validated before the stub error is raised).+ Allowlist template ID (see ``osquery_allowlist``).template_params:- Optional template parameters.+ Parameters forwarded to the template renderer.timeout_seconds:- Timeout; ignored by the stub.+ Maximum time to wait for results.++ Returns+ -------+ dict+ ``{"results": {host_id: [rows]}, "error": str | None}``Raises------+ AiSOCDirectError+ If the HTTP request to the TLS service fails.AllowlistError- If *template* is not in the approved allowlist (validated eagerly- so that bad calls are caught even before PR 4 ships).- NotImplementedError- Always — the real implementation is forthcoming in PR 4.+ If *template* is not in the approved allowlist."""params = template_params or {}- # Validate allowlist eagerly; surfaces misconfigurations early.- render_query(template, **params)-- raise NotImplementedError(- "AiSOCDirectClient.live_query is a PR-3 stub. "- "The full implementation will be added in PR 4 once "- "services/osquery-tls/ is available."- )+ sql = render_query(template, **params)++ async with httpx.AsyncClient(+ verify=self._verify_tls, timeout=30.0+ ) as client:+ query_ids = await self._enqueue_for_hosts(+ client, target_hosts, sql+ )+ results = await self._poll_results(+ client, query_ids, timeout_seconds+ )++ errors = [r for r in results.values() if "error" in r]+ return {+ "results": {+ host: results[qid].get("rows", [])+ for host, qid in zip(target_hosts, query_ids)+ if qid in results+ },+ "error": errors[0]["error"] if errors else None,+ }++ async def _enqueue_for_hosts(+ self,+ client: httpx.AsyncClient,+ target_hosts: list[str],+ sql: str,+ ) -> list[str]:+ """Enqueue one distributed query per target host and return query IDs."""+ url = f"{self._base_url}/api/v1/osquery/distributed/enqueue"+ query_ids: list[str] = []+ for host in target_hosts:+ try:+ resp = await client.post(+ url,+ json={"host_identifier": host, "query_text": sql},+ headers=self._headers(),+ )+ resp.raise_for_status()+ data = resp.json()+ query_ids.append(data["query_id"])+ except httpx.HTTPError as exc:+ raise AiSOCDirectError(+ f"Failed to enqueue query for host {host}: {exc}"+ ) from exc+ return query_ids++ async def _poll_results(+ self,+ client: httpx.AsyncClient,+ query_ids: list[str],+ timeout_seconds: int,+ ) -> dict[str, Any]:+ """Poll until all queries complete or timeout is reached."""+ remaining = set(query_ids)+ results: dict[str, Any] = {}+ elapsed = 0.0++ while remaining and elapsed < timeout_seconds:+ await asyncio.sleep(self._poll_interval)+ elapsed += self._poll_interval+ done = set()+ for qid in list(remaining):+ url = f"{self._base_url}/api/v1/osquery/distributed/{qid}"+ try:+ resp = await client.get(url, headers=self._headers())+ resp.raise_for_status()+ data = resp.json()+ if data.get("status") in ("completed", "error"):+ results[qid] = data+ done.add(qid)+ except httpx.HTTPError as exc:+ logger.warning("Poll error for query %s: %s", qid, exc)+ remaining -= done++ for qid in remaining:+ results[qid] = {"status": "timeout", "rows": [], "error": "timeout"}++ return resultsdiff --git a/services/osquery-tls/Dockerfile b/services/osquery-tls/Dockerfilenew file mode 100644index 000000000..128505c21--- /dev/null+++ b/services/osquery-tls/Dockerfile@@ -0,0 +1,24 @@+FROM python:3.11-slim AS base++WORKDIR /app+ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ PIP_DISABLE_PIP_VERSION_CHECK=1++RUN apt-get update && apt-get install -y --no-install-recommends \+ build-essential \+ libpq-dev \+ && rm -rf /var/lib/apt/lists/*++RUN pip install poetry==1.8.2++COPY pyproject.toml poetry.lock* ./+RUN poetry config virtualenvs.create false && \+ poetry install --no-dev --no-interaction --no-ansi++COPY . .++EXPOSE 9001++CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "9001"]diff --git a/services/osquery-tls/alembic.ini b/services/osquery-tls/alembic.ininew file mode 100644index 000000000..b616d2383--- /dev/null+++ b/services/osquery-tls/alembic.ini@@ -0,0 +1,37 @@+[alembic]+script_location = app/db+sqlalchemy.url = driver://user:pass@localhost/dbname++[loggers]+keys = root,sqlalchemy,alembic++[handlers]+keys = console++[formatters]+keys = generic++[logger_root]+level = WARN+handlers = console+qualname =++[logger_sqlalchemy]+level = WARN+handlers =+qualname = sqlalchemy.engine++[logger_alembic]+level = INFO+handlers =+qualname = alembic++[handler_console]+class = StreamHandler+args = (sys.stderr,)+level = NOTSET+formatter = generic++[formatter_generic]+format = %(levelname)-5.5s [%(name)s] %(message)s+datefmt = %H:%M:%Sdiff --git a/services/osquery-tls/app/__init__.py b/services/osquery-tls/app/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/osquery-tls/app/api/__init__.py b/services/osquery-tls/app/api/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/osquery-tls/app/api/v1/__init__.py b/services/osquery-tls/app/api/v1/__init__.pynew file mode 100644index 000000000..e5177c76a--- /dev/null+++ b/services/osquery-tls/app/api/v1/__init__.py@@ -0,0 +1,21 @@+"""API v1 router for the osquery TLS service."""+from fastapi import APIRouter++from app.api.v1.endpoints import (+ config,+ distributed_enqueue,+ distributed_read,+ distributed_status,+ distributed_write,+ enroll,+ log,+)++router = APIRouter(prefix="/api/v1/osquery")+router.include_router(enroll.router)+router.include_router(config.router)+router.include_router(log.router)+router.include_router(distributed_read.router)+router.include_router(distributed_write.router)+router.include_router(distributed_enqueue.router)+router.include_router(distributed_status.router)diff --git a/services/osquery-tls/app/api/v1/endpoints/__init__.py b/services/osquery-tls/app/api/v1/endpoints/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/osquery-tls/app/api/v1/endpoints/config.py b/services/osquery-tls/app/api/v1/endpoints/config.pynew file mode 100644index 000000000..6b8925cf6--- /dev/null+++ b/services/osquery-tls/app/api/v1/endpoints/config.py@@ -0,0 +1,31 @@+"""POST /api/v1/osquery/config — osquery TLS config retrieval endpoint.++osqueryd polls this to receive its schedule, packs, and options.++Reference:+ https://osquery.readthedocs.io/en/stable/deployment/remote/#config-retrieval+"""+from __future__ import annotations++from typing import Annotated++from fastapi import APIRouter, Depends, Request+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.security import require_valid_node_key+from app.db.session import get_db+from app.models.node import OsqueryNode+from app.services.node_registry import mark_seen+from app.services.pack_resolver import resolve_config++router = APIRouter()++[email protected]("/config")+async def get_config(+ request: Request,+ db: Annotated[AsyncSession, Depends(get_db)],+ node: Annotated[OsqueryNode, Depends(require_valid_node_key)],+) -> dict:+ await mark_seen(db, node)+ return resolve_config(node.tenant_id)diff --git a/services/osquery-tls/app/api/v1/endpoints/distributed_enqueue.py b/services/osquery-tls/app/api/v1/endpoints/distributed_enqueue.pynew file mode 100644index 000000000..496a65083--- /dev/null+++ b/services/osquery-tls/app/api/v1/endpoints/distributed_enqueue.py@@ -0,0 +1,47 @@+"""POST /api/v1/osquery/distributed/enqueue — internal API for playbook engine.++This endpoint is NOT part of the standard osquery TLS plugin spec.+It is called by the AiSOC action client (``aisoc_direct_client``) to enqueue+a distributed query targeted at a specific host by its host_identifier.++Authentication uses the same bearer-token mechanism as the rest of the+internal service APIs (Authorization: Bearer <AISOC_OSQUERY_TLS_API_TOKEN>).+"""+from __future__ import annotations++from typing import Annotated++from fastapi import APIRouter, Depends, HTTPException, status+from pydantic import BaseModel+from sqlalchemy.ext.asyncio import AsyncSession++from app.db.session import get_db+from app.services.distributed_queue import enqueue_query+from app.services.node_registry import get_node_by_host++router = APIRouter()+++class EnqueueRequest(BaseModel):+ host_identifier: str+ query_text: str+ tenant_id: str = "default"+++class EnqueueResponse(BaseModel):+ query_id: str++[email protected]("/distributed/enqueue", response_model=EnqueueResponse)+async def distributed_enqueue(+ body: EnqueueRequest,+ db: Annotated[AsyncSession, Depends(get_db)],+) -> EnqueueResponse:+ node = await get_node_by_host(db, body.host_identifier, body.tenant_id)+ if node is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Node {body.host_identifier!r} not enrolled for tenant {body.tenant_id!r}",+ )+ dq = await enqueue_query(db, node, body.query_text)+ return EnqueueResponse(query_id=dq.query_id)diff --git a/services/osquery-tls/app/api/v1/endpoints/distributed_read.py b/services/osquery-tls/app/api/v1/endpoints/distributed_read.pynew file mode 100644index 000000000..721b915c3--- /dev/null+++ b/services/osquery-tls/app/api/v1/endpoints/distributed_read.py@@ -0,0 +1,31 @@+"""POST /api/v1/osquery/distributed/read — dequeue pending queries for a node.++Reference:+ https://osquery.readthedocs.io/en/stable/deployment/remote/#distributed-queries+"""+from __future__ import annotations++from typing import Annotated++from fastapi import APIRouter, Depends, Request+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.security import require_valid_node_key+from app.db.session import get_db+from app.models.node import OsqueryNode+from app.services.distributed_queue import get_pending_queries+from app.services.node_registry import mark_seen++router = APIRouter()++[email protected]("/distributed/read")+async def distributed_read(+ request: Request,+ db: Annotated[AsyncSession, Depends(get_db)],+ node: Annotated[OsqueryNode, Depends(require_valid_node_key)],+) -> dict:+ await mark_seen(db, node)+ pending = await get_pending_queries(db, node)+ queries = {dq.query_id: dq.query_text for dq in pending}+ return {"queries": queries, "node_invalid": False}diff --git a/services/osquery-tls/app/api/v1/endpoints/distributed_status.py b/services/osquery-tls/app/api/v1/endpoints/distributed_status.pynew file mode 100644index 000000000..205cc3ef8--- /dev/null+++ b/services/osquery-tls/app/api/v1/endpoints/distributed_status.py@@ -0,0 +1,41 @@+"""GET /api/v1/osquery/distributed/{query_id} — check query status (internal API).++Used by ``aisoc_direct_client`` to poll for distributed query results.+"""+from __future__ import annotations++from typing import Annotated++from fastapi import APIRouter, Depends, HTTPException, status+from pydantic import BaseModel+from sqlalchemy.ext.asyncio import AsyncSession++from app.db.session import get_db+from app.services.distributed_queue import get_query_by_id++router = APIRouter()+++class QueryStatusResponse(BaseModel):+ query_id: str+ status: str+ rows: list[dict] | None = None+ error: str | None = None++[email protected]("/distributed/{query_id}", response_model=QueryStatusResponse)+async def distributed_status(+ query_id: str,+ db: Annotated[AsyncSession, Depends(get_db)],+) -> QueryStatusResponse:+ dq = await get_query_by_id(db, query_id)+ if dq is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Query {query_id!r} not found",+ )+ return QueryStatusResponse(+ query_id=dq.query_id,+ status=dq.status,+ rows=dq.results_json if dq.status == "completed" else None,+ )diff --git a/services/osquery-tls/app/api/v1/endpoints/distributed_write.py b/services/osquery-tls/app/api/v1/endpoints/distributed_write.pynew file mode 100644index 000000000..4b0e59179--- /dev/null+++ b/services/osquery-tls/app/api/v1/endpoints/distributed_write.py@@ -0,0 +1,55 @@+"""POST /api/v1/osquery/distributed/write — receive completed distributed query results.++Reference:+ https://osquery.readthedocs.io/en/stable/deployment/remote/#distributed-queries+"""+from __future__ import annotations++from typing import Annotated++from fastapi import APIRouter, Depends, Request+from pydantic import BaseModel+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.security import require_valid_node_key+from app.db.session import get_db+from app.models.node import OsqueryNode+from app.services.distributed_queue import complete_query+from app.services.log_forwarder import forward_events+from app.services.node_registry import mark_seen+from app.services.normalizer import normalize_row++router = APIRouter()+++class DistributedWriteRequest(BaseModel):+ node_key: str+ queries: dict[str, list[dict]] # query_id -> list of result rows+ statuses: dict[str, int] = {} # query_id -> exit code++[email protected]("/distributed/write")+async def distributed_write(+ body: DistributedWriteRequest,+ request: Request,+ db: Annotated[AsyncSession, Depends(get_db)],+ node: Annotated[OsqueryNode, Depends(require_valid_node_key)],+) -> dict:+ await mark_seen(db, node)++ events: list[dict] = []+ for query_id, rows in body.queries.items():+ await complete_query(db, query_id, rows)+ for row in rows:+ events.append(+ normalize_row(+ row,+ host_identifier=node.host_identifier,+ tenant_id=node.tenant_id,+ query_name=query_id,+ log_type="distributed",+ )+ )++ await forward_events(events, node.tenant_id)+ return {"node_invalid": False}diff --git a/services/osquery-tls/app/api/v1/endpoints/enroll.py b/services/osquery-tls/app/api/v1/endpoints/enroll.pynew file mode 100644index 000000000..bed4b0f1c--- /dev/null+++ b/services/osquery-tls/app/api/v1/endpoints/enroll.py@@ -0,0 +1,56 @@+"""POST /api/v1/osquery/enroll — osquery TLS plugin enroll endpoint.++osqueryd calls this once on startup. If the enroll_secret matches, we+register the node (or rotate its node_key) and return a fresh node_key.++Reference:+ https://osquery.readthedocs.io/en/stable/deployment/remote/#enroll+"""+from __future__ import annotations++from typing import Annotated++from fastapi import APIRouter, Depends, Header, HTTPException, status+from pydantic import BaseModel+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.config import settings+from app.core.security import verify_enroll_secret+from app.db.session import get_db+from app.services.node_registry import enroll_node++router = APIRouter()+++class EnrollRequest(BaseModel):+ enroll_secret: str+ host_identifier: str+ host_details: dict | None = None+++class EnrollResponse(BaseModel):+ node_key: str+ node_invalid: bool = False++[email protected]("/enroll", response_model=EnrollResponse)+async def enroll(+ body: EnrollRequest,+ db: Annotated[AsyncSession, Depends(get_db)],+ x_aisoc_tenant: Annotated[str | None, Header()] = None,+) -> EnrollResponse:+ tenant_id = x_aisoc_tenant or "default"++ if not verify_enroll_secret(body.enroll_secret, tenant_id):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail={"node_invalid": True},+ )++ node = await enroll_node(+ db,+ host_identifier=body.host_identifier,+ tenant_id=tenant_id,+ host_details=body.host_details,+ )+ return EnrollResponse(node_key=node.node_key)diff --git a/services/osquery-tls/app/api/v1/endpoints/log.py b/services/osquery-tls/app/api/v1/endpoints/log.pynew file mode 100644index 000000000..ea82c52d7--- /dev/null+++ b/services/osquery-tls/app/api/v1/endpoints/log.py@@ -0,0 +1,82 @@+"""POST /api/v1/osquery/log — osquery TLS log endpoint.++osqueryd POSTs result and status logs here. We normalise each row and+forward the batch to services/ingest.++Reference:+ https://osquery.readthedocs.io/en/stable/deployment/remote/#log-string+"""+from __future__ import annotations++import json+import logging+from typing import Annotated++from fastapi import APIRouter, Depends, Request+from pydantic import BaseModel+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.security import require_valid_node_key+from app.db.session import get_db+from app.models.node import OsqueryNode+from app.services.log_forwarder import forward_events+from app.services.node_registry import mark_seen+from app.services.normalizer import normalize_row++logger = logging.getLogger(__name__)+router = APIRouter()+++class LogRequest(BaseModel):+ node_key: str+ log_type: str # "result" | "snapshot" | "status"+ data: str # JSON-encoded string (osquery sends it as a string)++[email protected]("/log")+async def log(+ body: LogRequest,+ request: Request,+ db: Annotated[AsyncSession, Depends(get_db)],+ node: Annotated[OsqueryNode, Depends(require_valid_node_key)],+) -> dict:+ await mark_seen(db, node)++ events: list[dict] = []+ try:+ payload = json.loads(body.data)+ except (json.JSONDecodeError, TypeError):+ logger.warning("Received non-JSON log data from node %s", node.host_identifier)+ return {"node_invalid": False}++ # Only result and snapshot log types carry query rows worth forwarding.+ # Status logs are osqueryd daemon diagnostics; skip them.+ if body.log_type not in ("result", "snapshot"):+ await forward_events([], node.tenant_id)+ return {"node_invalid": False}++ if isinstance(payload, list):+ rows = payload+ elif isinstance(payload, dict):+ rows = [payload]+ else:+ rows = []++ for entry in rows:+ query_name = entry.get("name", "unknown")+ raw_rows = entry.get("columns") or entry.get("snapshot") or [entry]+ if isinstance(raw_rows, dict):+ raw_rows = [raw_rows]+ for row in raw_rows:+ events.append(+ normalize_row(+ row,+ host_identifier=node.host_identifier,+ tenant_id=node.tenant_id,+ query_name=query_name,+ log_type=body.log_type,+ )+ )++ await forward_events(events, node.tenant_id)+ return {"node_invalid": False}diff --git a/services/osquery-tls/app/core/__init__.py b/services/osquery-tls/app/core/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/osquery-tls/app/core/config.py b/services/osquery-tls/app/core/config.pynew file mode 100644index 000000000..3a1ee6578--- /dev/null+++ b/services/osquery-tls/app/core/config.py@@ -0,0 +1,50 @@+"""Configuration settings for the AiSOC osquery TLS service.++All settings are read from environment variables prefixed with+``AISOC_OSQUERY_TLS_``, with sane defaults for local dev.+"""+from __future__ import annotations++from pydantic_settings import BaseSettings, SettingsConfigDict+++class Settings(BaseSettings):+ model_config = SettingsConfigDict(+ env_prefix="AISOC_OSQUERY_TLS_",+ env_file=".env",+ extra="ignore",+ )++ # --- Database -------------------------------------------------------+ # Reuses the main API Postgres; all tables live in the `osquery_tls` schema.+ database_url: str = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"++ # --- Ingest service -------------------------------------------------+ # Where normalised osquery rows are forwarded to.+ ingest_url: str = "http://ingest:8080"++ # --- Enrollment auth ------------------------------------------------+ # The enroll secret that osqueryd must present. In production this should+ # be a long random string stored in a secrets manager and rotated+ # periodically. Per-tenant secrets are looked up by the ``X-AiSOC-Tenant``+ # request header; this value is used as the fallback single-tenant secret.+ enroll_secret: str = "change-me-in-production"++ # --- mTLS -----------------------------------------------------------+ # When True the service validates the client TLS certificate on every+ # request after enroll. The client cert CN must match host_identifier.+ require_client_cert: bool = False++ # --- Service identity -----------------------------------------------+ # Public hostname (used to build TLS flag-file docs).+ public_hostname: str = "osquery.tryaisoc.com"++ # --- Pack stubs (overridden fully in PR5) ---------------------------+ # Default query interval for the baseline schedule shipped to every node.+ default_interval_seconds: int = 300++ # --- Log level ------------------------------------------------------+ log_level: str = "INFO"+++settings = Settings()diff --git a/services/osquery-tls/app/core/security.py b/services/osquery-tls/app/core/security.pynew file mode 100644index 000000000..74160055f--- /dev/null+++ b/services/osquery-tls/app/core/security.py@@ -0,0 +1,87 @@+"""Security helpers for the AiSOC osquery TLS service.++Handles two authentication concerns:++1. **Enroll secret** — the shared secret an osqueryd agent must supply when+ first enrolling. Validated in ``verify_enroll_secret()``.+2. **Node key** — a server-issued opaque token (UUID) returned after enroll.+ Every subsequent request validates ``node_key`` against ``node_registry``.+3. **mTLS** (optional, controlled by ``AISOC_OSQUERY_TLS_REQUIRE_CLIENT_CERT``)+ — after enroll, the TLS client certificate CN must match+ ``node.host_identifier``.++The FastAPI dependency ``require_valid_node_key`` is used by all post-enroll+endpoints. It returns the resolved ``OsqueryNode`` so handlers don't need+a separate DB lookup.+"""+from __future__ import annotations++import secrets+from typing import Annotated++from fastapi import Depends, Header, HTTPException, Request, status+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.config import settings+from app.db.session import get_db+++def _tenant_from_header(x_aisoc_tenant: str | None) -> str:+ """Return tenant identifier from request header, defaulting to 'default'."""+ return x_aisoc_tenant or "default"+++def verify_enroll_secret(submitted_secret: str, tenant_id: str = "default") -> bool:+ """Constant-time comparison of the submitted enroll secret.++ In a multi-tenant deployment the enroll secret would be looked up per+ tenant. For now we use the single-tenant secret from settings.+ """+ return secrets.compare_digest(submitted_secret, settings.enroll_secret)+++def generate_node_key() -> str:+ """Generate a cryptographically random node key (128-bit hex)."""+ return secrets.token_hex(16)+++async def require_valid_node_key(+ request: Request,+ db: Annotated[AsyncSession, Depends(get_db)],+ x_aisoc_tenant: Annotated[str | None, Header()] = None,+) -> "app.models.node.OsqueryNode": # type: ignore[name-defined] # noqa: F821+ """FastAPI dependency: parse node_key from JSON body and resolve the node.++ Raises ``HTTP 401`` if the key is missing or unknown.++ Returns the resolved ``OsqueryNode`` ORM instance.+ """+ from app.models.node import OsqueryNode # noqa: PLC0415+ from app.services.node_registry import get_node_by_key # noqa: PLC0415++ body = await request.json()+ node_key: str | None = body.get("node_key")+ if not node_key:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="node_key is required",+ )++ node = await get_node_by_key(db, node_key)+ if node is None:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="node_invalid",+ )++ if settings.require_client_cert:+ # Validate that the TLS client certificate CN matches host_identifier.+ # Nginx / Caddy should forward the verified CN in X-SSL-Client-CN.+ client_cn = request.headers.get("X-SSL-Client-CN", "")+ if client_cn != node.host_identifier:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="client certificate CN does not match host_identifier",+ )++ return nodediff --git a/services/osquery-tls/app/db/__init__.py b/services/osquery-tls/app/db/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/osquery-tls/app/db/base.py b/services/osquery-tls/app/db/base.pynew file mode 100644index 000000000..c5ec056a1--- /dev/null+++ b/services/osquery-tls/app/db/base.py@@ -0,0 +1,8 @@+"""SQLAlchemy declarative base for the osquery-tls service."""+from __future__ import annotations++from sqlalchemy.orm import DeclarativeBase+++class Base(DeclarativeBase):+ """All ORM models inherit from this base."""diff --git a/services/osquery-tls/app/db/env.py b/services/osquery-tls/app/db/env.pynew file mode 100644index 000000000..fbe07b52d--- /dev/null+++ b/services/osquery-tls/app/db/env.py@@ -0,0 +1,59 @@+"""Alembic migration environment for the osquery-tls service.++Supports async migrations via asyncio run_sync().+"""+from __future__ import annotations++import asyncio+from logging.config import fileConfig++from alembic import context+from sqlalchemy import pool+from sqlalchemy.ext.asyncio import create_async_engine++from app.core.config import settings+from app.db.base import Base+import app.models # noqa: F401 — register all ORM models++config = context.config+config.set_main_option("sqlalchemy.url", settings.database_url)++if config.config_file_name is not None:+ fileConfig(config.config_file_name)++target_metadata = Base.metadata+++def run_migrations_offline() -> None:+ url = config.get_main_option("sqlalchemy.url")+ context.configure(+ url=url,+ target_metadata=target_metadata,+ literal_binds=True,+ dialect_opts={"paramstyle": "named"},+ )+ with context.begin_transaction():+ context.run_migrations()+++def do_run_migrations(connection):+ context.configure(connection=connection, target_metadata=target_metadata)+ with context.begin_transaction():+ context.run_migrations()+++async def run_async_migrations() -> None:+ engine = create_async_engine(settings.database_url, poolclass=pool.NullPool)+ async with engine.connect() as connection:+ await connection.run_sync(do_run_migrations)+ await engine.dispose()+++def run_migrations_online() -> None:+ asyncio.run(run_async_migrations())+++if context.is_offline_mode():+ run_migrations_offline()+else:+ run_migrations_online()diff --git a/services/osquery-tls/app/db/session.py b/services/osquery-tls/app/db/session.pynew file mode 100644index 000000000..b81ec9097--- /dev/null+++ b/services/osquery-tls/app/db/session.py@@ -0,0 +1,28 @@+"""Async SQLAlchemy session factory for the osquery-tls service."""+from __future__ import annotations++from collections.abc import AsyncGenerator++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine++from app.core.config import settings++_engine = create_async_engine(+ settings.database_url,+ echo=False,+ pool_pre_ping=True,+)++_SessionLocal = async_sessionmaker(+ bind=_engine,+ class_=AsyncSession,+ autocommit=False,+ autoflush=False,+ expire_on_commit=False,+)+++async def get_db() -> AsyncGenerator[AsyncSession, None]:+ """FastAPI dependency that yields an async database session."""+ async with _SessionLocal() as session:+ yield sessiondiff --git a/services/osquery-tls/app/db/versions/001_init.py b/services/osquery-tls/app/db/versions/001_init.pynew file mode 100644index 000000000..031cac771--- /dev/null+++ b/services/osquery-tls/app/db/versions/001_init.py@@ -0,0 +1,84 @@+"""Initial schema: node_registry, distributed_query_queue, pack_assignment.++Revision ID: 001+Revises:+Create Date: 2026-05-10+"""+from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "001"+down_revision = None+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.create_table(+ "osquery_node",+ sa.Column("id", sa.Integer(), nullable=False),+ sa.Column("host_identifier", sa.String(length=255), nullable=False),+ sa.Column("node_key", sa.String(length=64), nullable=False),+ sa.Column("tenant_id", sa.String(length=64), nullable=False, server_default="default"),+ sa.Column("host_details", sa.JSON(), nullable=True),+ sa.Column("last_seen", sa.DateTime(timezone=True), nullable=True),+ sa.Column(+ "enrolled_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.text("NOW()"),+ ),+ sa.PrimaryKeyConstraint("id"),+ sa.UniqueConstraint("node_key"),+ sa.UniqueConstraint("host_identifier", "tenant_id", name="uq_node_host_tenant"),+ )+ op.create_index("ix_osquery_node_node_key", "osquery_node", ["node_key"])+ op.create_index("ix_osquery_node_tenant_id", "osquery_node", ["tenant_id"])++ op.create_table(+ "osquery_pack_assignment",+ sa.Column("id", sa.Integer(), nullable=False),+ sa.Column("tenant_id", sa.String(length=64), nullable=False),+ sa.Column("pack_id", sa.String(length=128), nullable=False),+ sa.Column(+ "assigned_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.text("NOW()"),+ ),+ sa.PrimaryKeyConstraint("id"),+ sa.UniqueConstraint("tenant_id", "pack_id", name="uq_pack_assignment"),+ )++ op.create_table(+ "osquery_distributed_query",+ sa.Column("id", sa.Integer(), nullable=False),+ sa.Column("node_id", sa.Integer(), nullable=False),+ sa.Column("query_id", sa.String(length=64), nullable=False),+ sa.Column("query_text", sa.Text(), nullable=False),+ sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),+ sa.Column(+ "requested_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.text("NOW()"),+ ),+ sa.Column("completed_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("results_json", sa.JSON(), nullable=True),+ sa.ForeignKeyConstraint(["node_id"], ["osquery_node.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),+ sa.UniqueConstraint("query_id"),+ )+ op.create_index(+ "ix_osquery_dq_node_status",+ "osquery_distributed_query",+ ["node_id", "status"],+ )+++def downgrade() -> None:+ op.drop_table("osquery_distributed_query")+ op.drop_table("osquery_pack_assignment")+ op.drop_table("osquery_node")diff --git a/services/osquery-tls/app/main.py b/services/osquery-tls/app/main.pynew file mode 100644index 000000000..73874f3ba--- /dev/null+++ b/services/osquery-tls/app/main.py@@ -0,0 +1,30 @@+"""AiSOC osquery TLS service — FastAPI application entry point."""+from __future__ import annotations++import logging++from fastapi import FastAPI+from fastapi.responses import JSONResponse++from app.api.v1 import router as v1_router+from app.core.config import settings++logging.basicConfig(level=getattr(logging, settings.log_level.upper(), logging.INFO))++app = FastAPI(+ title="AiSOC osquery TLS",+ description=(+ "Implements the osquery TLS plugin spec so osqueryd agents can be "+ "pointed at AiSOC directly, without a separate fleet manager."+ ),+ version="0.1.0",+ docs_url="/docs",+ redoc_url="/redoc",+)++app.include_router(v1_router)++[email protected]("/healthz", include_in_schema=False)+async def healthz() -> JSONResponse:+ return JSONResponse({"status": "ok"})diff --git a/services/osquery-tls/app/models/__init__.py b/services/osquery-tls/app/models/__init__.pynew file mode 100644index 000000000..72dbf081d--- /dev/null+++ b/services/osquery-tls/app/models/__init__.py@@ -0,0 +1,9 @@+"""ORM models for the osquery-tls service.++Import all models here so Alembic's env.py picks them up automatically.+"""+from app.models.distributed_query import OsqueryDistributedQuery+from app.models.node import OsqueryNode+from app.models.pack_assignment import OsqueryPackAssignment++__all__ = ["OsqueryNode", "OsqueryPackAssignment", "OsqueryDistributedQuery"]diff --git a/services/osquery-tls/app/models/distributed_query.py b/services/osquery-tls/app/models/distributed_query.pynew file mode 100644index 000000000..0a16a3203--- /dev/null+++ b/services/osquery-tls/app/models/distributed_query.py@@ -0,0 +1,31 @@+"""ORM model for distributed (ad-hoc) osquery queries."""+from __future__ import annotations++from datetime import datetime++from sqlalchemy import DateTime, ForeignKey, Integer, JSON, String, Text+from sqlalchemy.orm import Mapped, mapped_column+from sqlalchemy.sql import func++from app.db.base import Base+++class OsqueryDistributedQuery(Base):+ """Tracks a per-node distributed query from enqueue through completion."""++ __tablename__ = "osquery_distributed_query"++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ node_id: Mapped[int] = mapped_column(+ Integer, ForeignKey("osquery_node.id", ondelete="CASCADE"), nullable=False+ )+ query_id: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)+ query_text: Mapped[str] = mapped_column(Text, nullable=False)+ status: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")+ requested_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )+ completed_at: Mapped[datetime | None] = mapped_column(+ DateTime(timezone=True), nullable=True+ )+ results_json: Mapped[list | None] = mapped_column(JSON, nullable=True)diff --git a/services/osquery-tls/app/models/node.py b/services/osquery-tls/app/models/node.pynew file mode 100644index 000000000..2dd4be8d8--- /dev/null+++ b/services/osquery-tls/app/models/node.py@@ -0,0 +1,32 @@+"""ORM model for an enrolled osquery node."""+from __future__ import annotations++from datetime import datetime++from sqlalchemy import DateTime, Integer, String, UniqueConstraint+from sqlalchemy.dialects.postgresql import JSON+from sqlalchemy.orm import Mapped, mapped_column+from sqlalchemy.sql import func++from app.db.base import Base+++class OsqueryNode(Base):+ """Represents an osqueryd agent enrolled with the AiSOC TLS service."""++ __tablename__ = "osquery_node"+ __table_args__ = (+ UniqueConstraint("host_identifier", "tenant_id", name="uq_node_host_tenant"),+ )++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ host_identifier: Mapped[str] = mapped_column(String(255), nullable=False)+ node_key: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)+ tenant_id: Mapped[str] = mapped_column(String(64), nullable=False, default="default")+ host_details: Mapped[dict | None] = mapped_column(JSON, nullable=True)+ last_seen: Mapped[datetime | None] = mapped_column(+ DateTime(timezone=True), nullable=True+ )+ enrolled_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )diff --git a/services/osquery-tls/app/models/pack_assignment.py b/services/osquery-tls/app/models/pack_assignment.pynew file mode 100644index 000000000..059c8e151--- /dev/null+++ b/services/osquery-tls/app/models/pack_assignment.py@@ -0,0 +1,26 @@+"""ORM model for tenant → osquery pack assignments."""+from __future__ import annotations++from datetime import datetime++from sqlalchemy import DateTime, Integer, String, UniqueConstraint+from sqlalchemy.orm import Mapped, mapped_column+from sqlalchemy.sql import func++from app.db.base import Base+++class OsqueryPackAssignment(Base):+ """Maps a tenant to a named osquery pack (resolved in PR5)."""++ __tablename__ = "osquery_pack_assignment"+ __table_args__ = (+ UniqueConstraint("tenant_id", "pack_id", name="uq_pack_assignment"),+ )++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)+ pack_id: Mapped[str] = mapped_column(String(128), nullable=False)+ assigned_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )diff --git a/services/osquery-tls/app/scripts/__init__.py b/services/osquery-tls/app/scripts/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/osquery-tls/app/services/__init__.py b/services/osquery-tls/app/services/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/osquery-tls/app/services/distributed_queue.py b/services/osquery-tls/app/services/distributed_queue.pynew file mode 100644index 000000000..03bdba307--- /dev/null+++ b/services/osquery-tls/app/services/distributed_queue.py@@ -0,0 +1,70 @@+"""Distributed query queue: enqueue and dequeue per-node ad-hoc queries."""+from __future__ import annotations++import uuid+from datetime import datetime, timezone++from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.distributed_query import OsqueryDistributedQuery+from app.models.node import OsqueryNode+++async def enqueue_query(+ db: AsyncSession, node: OsqueryNode, query_text: str+) -> OsqueryDistributedQuery:+ """Add a new distributed query for the given node and return it."""+ dq = OsqueryDistributedQuery(+ node_id=node.id,+ query_id=str(uuid.uuid4()),+ query_text=query_text,+ status="pending",+ )+ db.add(dq)+ await db.commit()+ await db.refresh(dq)+ return dq+++async def get_pending_queries(+ db: AsyncSession, node: OsqueryNode+) -> list[OsqueryDistributedQuery]:+ """Return all pending distributed queries for this node."""+ result = await db.execute(+ select(OsqueryDistributedQuery).where(+ OsqueryDistributedQuery.node_id == node.id,+ OsqueryDistributedQuery.status == "pending",+ )+ )+ return list(result.scalars().all())+++async def complete_query(+ db: AsyncSession,+ query_id: str,+ results: list[dict],+) -> None:+ """Mark a distributed query as completed and store its results."""+ await db.execute(+ update(OsqueryDistributedQuery)+ .where(OsqueryDistributedQuery.query_id == query_id)+ .values(+ status="completed",+ completed_at=datetime.now(timezone.utc),+ results_json=results,+ )+ )+ await db.commit()+++async def get_query_by_id(+ db: AsyncSession, query_id: str+) -> OsqueryDistributedQuery | None:+ """Look up a distributed query by its query_id."""+ result = await db.execute(+ select(OsqueryDistributedQuery).where(+ OsqueryDistributedQuery.query_id == query_id+ )+ )+ return result.scalar_one_or_none()diff --git a/services/osquery-tls/app/services/log_forwarder.py b/services/osquery-tls/app/services/log_forwarder.pynew file mode 100644index 000000000..fdbee61da--- /dev/null+++ b/services/osquery-tls/app/services/log_forwarder.py@@ -0,0 +1,36 @@+"""Forward normalised osquery events to services/ingest /v1/ingest/batch."""+from __future__ import annotations++import logging++import httpx++from app.core.config import settings++logger = logging.getLogger(__name__)+++async def forward_events(events: list[dict], tenant_id: str) -> None:+ """POST a batch of normalised events to the ingest service.++ Failures are logged but not re-raised so a single bad ingest call+ does not abort a log submission response to the osqueryd agent.+ """+ if not events:+ return+ url = f"{settings.ingest_url}/v1/ingest/batch"+ try:+ async with httpx.AsyncClient(timeout=10.0) as client:+ resp = await client.post(+ url,+ json={"events": events},+ headers={"X-Tenant-ID": tenant_id},+ )+ resp.raise_for_status()+ except Exception:+ logger.exception(+ "Failed to forward %d events to ingest service (tenant=%s, url=%s)",+ len(events),+ tenant_id,+ url,+ )diff --git a/services/osquery-tls/app/services/node_registry.py b/services/osquery-tls/app/services/node_registry.pynew file mode 100644index 000000000..cf74d26cb--- /dev/null+++ b/services/osquery-tls/app/services/node_registry.py@@ -0,0 +1,70 @@+"""Node registry: enroll, look up, and refresh osquery nodes."""+from __future__ import annotations++from datetime import datetime, timezone++from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.security import generate_node_key+from app.models.node import OsqueryNode+++async def get_node_by_key(db: AsyncSession, node_key: str) -> OsqueryNode | None:+ """Return the node with the given node_key, or None if not found."""+ result = await db.execute(+ select(OsqueryNode).where(OsqueryNode.node_key == node_key)+ )+ return result.scalar_one_or_none()+++async def get_node_by_host(+ db: AsyncSession, host_identifier: str, tenant_id: str+) -> OsqueryNode | None:+ """Return a node by host_identifier + tenant, or None."""+ result = await db.execute(+ select(OsqueryNode).where(+ OsqueryNode.host_identifier == host_identifier,+ OsqueryNode.tenant_id == tenant_id,+ )+ )+ return result.scalar_one_or_none()+++async def enroll_node(+ db: AsyncSession,+ host_identifier: str,+ tenant_id: str,+ host_details: dict | None = None,+) -> OsqueryNode:+ """Enroll a new node or re-enroll an existing one (rotate node_key)."""+ existing = await get_node_by_host(db, host_identifier, tenant_id)+ if existing is not None:+ existing.node_key = generate_node_key()+ existing.host_details = host_details+ existing.last_seen = datetime.now(timezone.utc)+ await db.commit()+ await db.refresh(existing)+ return existing++ node = OsqueryNode(+ host_identifier=host_identifier,+ node_key=generate_node_key(),+ tenant_id=tenant_id,+ host_details=host_details,+ last_seen=datetime.now(timezone.utc),+ )+ db.add(node)+ await db.commit()+ await db.refresh(node)+ return node+++async def mark_seen(db: AsyncSession, node: OsqueryNode) -> None:+ """Update last_seen timestamp for the given node."""+ await db.execute(+ update(OsqueryNode)+ .where(OsqueryNode.id == node.id)+ .values(last_seen=datetime.now(timezone.utc))+ )+ await db.commit()diff --git a/services/osquery-tls/app/services/normalizer.py b/services/osquery-tls/app/services/normalizer.pynew file mode 100644index 000000000..78d067784--- /dev/null+++ b/services/osquery-tls/app/services/normalizer.py@@ -0,0 +1,71 @@+"""Normalise an osquery result row into an AiSOC event dict.++Mirrors the severity heuristics used by the osctrl and FleetDM connectors+(PR1) so that direct-TLS agents produce identically shaped events.++Schema reference: services/connectors/app/connectors/osctrl.py+"""+from __future__ import annotations++import re+from datetime import datetime, timezone++_HIGH_PATTERNS = [+ re.compile(r"process_events", re.IGNORECASE),+ re.compile(r"socket_events", re.IGNORECASE),+ re.compile(r"file_events", re.IGNORECASE),+ re.compile(r"user_events", re.IGNORECASE),+ re.compile(r"suid_bin", re.IGNORECASE),+]+_MEDIUM_PATTERNS = [+ re.compile(r"logged_in_users", re.IGNORECASE),+ re.compile(r"listening_ports", re.IGNORECASE),+]+++def _infer_severity(query_name: str, row: dict) -> str:+ for pat in _HIGH_PATTERNS:+ if pat.search(query_name):+ return "high"+ for pat in _MEDIUM_PATTERNS:+ if pat.search(query_name):+ return "medium"+ return "info"+++def normalize_row(+ row: dict,+ *,+ host_identifier: str,+ tenant_id: str,+ query_name: str,+ log_type: str = "result",+) -> dict:+ """Convert a single osquery result row into an AiSOC normalised event.++ Parameters+ ----------+ row:+ A single osquery result dict (column→value mapping).+ host_identifier:+ The node's stable host_identifier (UUID or hostname).+ tenant_id:+ AiSOC tenant this node belongs to.+ query_name:+ The name of the scheduled or distributed query that produced the row.+ log_type:+ ``"result"`` for schedule rows, ``"snapshot"`` for snapshot logs,+ ``"status"`` for osquery status messages.+ """+ severity = _infer_severity(query_name, row)+ return {+ "event_type": "osquery_query_row",+ "source": "aisoc_direct",+ "tenant_id": tenant_id,+ "host_identifier": host_identifier,+ "query_name": query_name,+ "log_type": log_type,+ "severity": severity,+ "raw": row,+ "timestamp": row.get("unixTime") or datetime.now(timezone.utc).isoformat(),+ }diff --git a/services/osquery-tls/app/services/pack_resolver.py b/services/osquery-tls/app/services/pack_resolver.pynew file mode 100644index 000000000..09fb8a524--- /dev/null+++ b/services/osquery-tls/app/services/pack_resolver.py@@ -0,0 +1,47 @@+"""Pack resolver: maps a tenant to their osquery schedule config.++PR4 stub — returns a minimal baseline schedule so enrolled nodes get a+valid (non-empty) config response immediately. The full implementation+(curated packs, YAML pack format, pack_assignment table) is delivered+in PR5.+"""+from __future__ import annotations++from app.core.config import settings+++_BASELINE_QUERIES: dict[str, dict] = {+ "system_info": {+ "query": "SELECT * FROM system_info;",+ "interval": settings.default_interval_seconds,+ "snapshot": True,+ },+ "os_version": {+ "query": "SELECT * FROM os_version;",+ "interval": settings.default_interval_seconds,+ "snapshot": True,+ },+ "listening_ports": {+ "query": "SELECT pid, port, protocol, address FROM listening_ports WHERE port < 32768;",+ "interval": settings.default_interval_seconds,+ },+ "logged_in_users": {+ "query": "SELECT * FROM logged_in_users;",+ "interval": 60,+ },+}+++def resolve_config(tenant_id: str) -> dict:+ """Return the osquery TLS config JSON for the given tenant.++ The config object must match the osquery TLS config response schema:+ https://osquery.readthedocs.io/en/stable/deployment/remote/#config-retrieval+ """+ return {+ "schedule": _BASELINE_QUERIES,+ "options": {+ "host_identifier": "hostname",+ "schedule_splay_percent": 10,+ },+ }diff --git a/services/osquery-tls/pyproject.toml b/services/osquery-tls/pyproject.tomlnew file mode 100644index 000000000..2f0e22c75--- /dev/null+++ b/services/osquery-tls/pyproject.toml@@ -0,0 +1,43 @@+[tool.poetry]+name = "aisoc-osquery-tls"+version = "0.1.0"+description = "AiSOC osquery TLS plugin service — direct osqueryd TLS endpoint without a separate fleet manager"+authors = ["AiSOC Community"]+license = "MIT"+readme = "README.md"++[tool.poetry.dependencies]+python = "^3.11"+fastapi = "^0.111.0"+uvicorn = { version = "^0.29.0", extras = ["standard"] }+pydantic = ">=2.7,<2.11"+pydantic-settings = "^2.2.1"+sqlalchemy = { version = "^2.0.30", extras = ["asyncio"] }+asyncpg = ">=0.29.0,<0.32"+alembic = "^1.13.1"+httpx = ">=0.27,<0.29"+structlog = "^24.1.0"+prometheus-client = ">=0.20,<0.26"+cryptography = "^42.0.0"++[tool.poetry.group.dev.dependencies]+pytest = "^8.2.0"+pytest-asyncio = ">=0.23.6,<1.4.0"+pytest-cov = "^5.0.0"+httpx = ">=0.27,<0.29"+ruff = "^0.4.4"+mypy = "^1.10.0"+aiosqlite = ">=0.19,<0.22"++[build-system]+requires = ["poetry-core"]+build-backend = "poetry.core.masonry.api"++[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true++[tool.pytest.ini_options]+asyncio_mode = "auto"+testpaths = ["tests"]diff --git a/services/osquery-tls/tests/__init__.py b/services/osquery-tls/tests/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/osquery-tls/tests/conftest.py b/services/osquery-tls/tests/conftest.pynew file mode 100644index 000000000..494c42500--- /dev/null+++ b/services/osquery-tls/tests/conftest.py@@ -0,0 +1,56 @@+"""Shared pytest fixtures for the osquery-tls service tests.++Uses an in-memory SQLite database for speed. SQLite doesn't support every+Postgres feature but it is sufficient for the ORM-level tests here.+"""+from __future__ import annotations++import os++import pytest+import pytest_asyncio+from httpx import ASGITransport, AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine++# Override env before importing the app so settings resolves without secrets.+os.environ.setdefault("AISOC_OSQUERY_TLS_ENROLL_SECRET", "test-enroll-secret")+os.environ.setdefault("AISOC_OSQUERY_TLS_API_TOKEN", "test-api-token")+os.environ.setdefault("DATABASE_URL", "sqlite+aiosqlite:///:memory:")++from app.db.base import Base # noqa: E402+from app.db.session import get_db # noqa: E402+from app.main import app # noqa: E402+++@pytest_asyncio.fixture(scope="function")+async def engine():+ eng = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)+ async with eng.begin() as conn:+ await conn.run_sync(Base.metadata.create_all)+ yield eng+ await eng.dispose()+++@pytest_asyncio.fixture(scope="function")+async def db_session(engine):+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ yield session+++@pytest_asyncio.fixture(scope="function")+async def client(engine):+ """HTTP test client with the DB overridden to the in-memory engine."""+ factory = async_sessionmaker(engine, expire_on_commit=False)++ async def _override_db():+ async with factory() as session:+ yield session++ app.dependency_overrides[get_db] = _override_db++ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as ac:+ yield ac++ app.dependency_overrides.clear()diff --git a/services/osquery-tls/tests/test_config.py b/services/osquery-tls/tests/test_config.pynew file mode 100644index 000000000..a7459b4d1--- /dev/null+++ b/services/osquery-tls/tests/test_config.py@@ -0,0 +1,34 @@+"""Tests for POST /api/v1/osquery/config."""+from __future__ import annotations++import pytest+++async def _enroll(client, host: str = "cfg-host") -> str:+ r = await client.post(+ "/api/v1/osquery/enroll",+ json={"enroll_secret": "test-enroll-secret", "host_identifier": host},+ )+ return r.json()["node_key"]+++async def test_config_valid_node(client):+ node_key = await _enroll(client, "cfg-host-1")+ resp = await client.post(+ "/api/v1/osquery/config",+ json={"node_key": node_key},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert "schedule" in data+ assert "options" in data+++async def test_config_invalid_node(client):+ resp = await client.post(+ "/api/v1/osquery/config",+ json={"node_key": "totally-fake"},+ )+ assert resp.status_code == 401diff --git a/services/osquery-tls/tests/test_distributed.py b/services/osquery-tls/tests/test_distributed.pynew file mode 100644index 000000000..ce3bb1365--- /dev/null+++ b/services/osquery-tls/tests/test_distributed.py@@ -0,0 +1,106 @@+"""Tests for distributed query read/write and internal enqueue/status endpoints."""+from __future__ import annotations++from unittest.mock import AsyncMock, patch++import pytest+++async def _enroll(client, host: str = "dist-host") -> tuple[str, str]:+ r = await client.post(+ "/api/v1/osquery/enroll",+ json={"enroll_secret": "test-enroll-secret", "host_identifier": host},+ )+ return host, r.json()["node_key"]+++async def test_distributed_read_empty(client):+ _host, node_key = await _enroll(client, "dist-read-1")+ resp = await client.post(+ "/api/v1/osquery/distributed/read",+ json={"node_key": node_key},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["queries"] == {}+ assert data["node_invalid"] is False+++async def test_distributed_enqueue_and_read(client):+ host, node_key = await _enroll(client, "dist-read-2")++ # Enqueue via internal API+ enq = await client.post(+ "/api/v1/osquery/distributed/enqueue",+ json={+ "host_identifier": host,+ "tenant_id": "default",+ "query_text": "SELECT pid, name FROM processes;",+ },+ )+ assert enq.status_code == 200+ query_id = enq.json()["query_id"]++ # osqueryd reads the pending query+ read = await client.post(+ "/api/v1/osquery/distributed/read",+ json={"node_key": node_key},+ )+ assert read.status_code == 200+ assert query_id in read.json()["queries"]+++async def test_distributed_write_and_status(client):+ host, node_key = await _enroll(client, "dist-write-1")++ enq = await client.post(+ "/api/v1/osquery/distributed/enqueue",+ json={+ "host_identifier": host,+ "tenant_id": "default",+ "query_text": "SELECT * FROM users;",+ },+ )+ query_id = enq.json()["query_id"]++ rows = [{"uid": "0", "username": "root"}]+ with patch("app.api.v1.endpoints.distributed_write.forward_events", new=AsyncMock()):+ write = await client.post(+ "/api/v1/osquery/distributed/write",+ json={+ "node_key": node_key,+ "queries": {query_id: rows},+ "statuses": {query_id: 0},+ },+ )+ assert write.status_code == 200+ assert write.json()["node_invalid"] is False++ # Internal status endpoint should show completed+ status_resp = await client.get(f"/api/v1/osquery/distributed/{query_id}")+ assert status_resp.status_code == 200+ sdata = status_resp.json()+ assert sdata["status"] == "completed"+ assert sdata["rows"] == rows+++async def test_distributed_enqueue_unknown_host(client):+ resp = await client.post(+ "/api/v1/osquery/distributed/enqueue",+ json={+ "host_identifier": "nonexistent-host",+ "tenant_id": "default",+ "query_text": "SELECT 1;",+ },+ )+ assert resp.status_code == 404+++async def test_distributed_status_not_found(client):+ resp = await client.get("/api/v1/osquery/distributed/no-such-id")+ assert resp.status_code == 404diff --git a/services/osquery-tls/tests/test_enroll.py b/services/osquery-tls/tests/test_enroll.pynew file mode 100644index 000000000..61ec37e5b--- /dev/null+++ b/services/osquery-tls/tests/test_enroll.py@@ -0,0 +1,46 @@+"""Tests for POST /api/v1/osquery/enroll."""+from __future__ import annotations++import pytest+++async def test_enroll_success(client):+ resp = await client.post(+ "/api/v1/osquery/enroll",+ json={+ "enroll_secret": "test-enroll-secret",+ "host_identifier": "host-001",+ "host_details": {"platform": "linux"},+ },+ )+ assert resp.status_code == 200+ data = resp.json()+ assert "node_key" in data+ assert data["node_invalid"] is False+++async def test_enroll_wrong_secret(client):+ resp = await client.post(+ "/api/v1/osquery/enroll",+ json={+ "enroll_secret": "wrong-secret",+ "host_identifier": "host-002",+ },+ )+ assert resp.status_code == 401+++async def test_reenroll_rotates_key(client):+ payload = {+ "enroll_secret": "test-enroll-secret",+ "host_identifier": "host-003",+ }+ r1 = await client.post("/api/v1/osquery/enroll", json=payload)+ r2 = await client.post("/api/v1/osquery/enroll", json=payload)+ assert r1.status_code == 200+ assert r2.status_code == 200+ # Node key must rotate on re-enroll+ assert r1.json()["node_key"] != r2.json()["node_key"]diff --git a/services/osquery-tls/tests/test_log.py b/services/osquery-tls/tests/test_log.pynew file mode 100644index 000000000..adcf34a8a--- /dev/null+++ b/services/osquery-tls/tests/test_log.py@@ -0,0 +1,56 @@+"""Tests for POST /api/v1/osquery/log."""+from __future__ import annotations++import json+from unittest.mock import AsyncMock, patch++import pytest+++async def _enroll(client, host: str = "log-host") -> str:+ r = await client.post(+ "/api/v1/osquery/enroll",+ json={"enroll_secret": "test-enroll-secret", "host_identifier": host},+ )+ return r.json()["node_key"]+++async def test_log_result_forwarded(client):+ node_key = await _enroll(client, "log-host-1")+ rows = [{"pid": "1234", "name": "evil", "path": "/tmp/evil"}]+ log_data = [{"name": "suspicious_processes", "hostIdentifier": "log-host-1", "columns": rows[0]}]++ with patch("app.api.v1.endpoints.log.forward_events", new=AsyncMock()) as mock_fwd:+ resp = await client.post(+ "/api/v1/osquery/log",+ json={+ "node_key": node_key,+ "log_type": "result",+ "data": json.dumps(log_data),+ },+ )+ assert resp.status_code == 200+ assert resp.json()["node_invalid"] is False+ mock_fwd.assert_awaited_once()+++async def test_log_status_type_no_forward(client):+ node_key = await _enroll(client, "log-host-2")+ # status logs: forward_events IS still called but with zero events+ with patch("app.api.v1.endpoints.log.forward_events", new=AsyncMock()) as mock_fwd:+ resp = await client.post(+ "/api/v1/osquery/log",+ json={+ "node_key": node_key,+ "log_type": "status",+ "data": json.dumps([{"severity": "0", "message": "osqueryd starting"}]),+ },+ )+ assert resp.status_code == 200+ # status log type returns early with an empty event batch+ call_args = mock_fwd.call_args+ assert call_args is not None+ events_arg = call_args[0][0]+ assert events_arg == []