---
title: Meraki Integration - Done
slug: meraki-integration-done
createdAt: 2025-04-14T19:33:31.069Z
---

# Functional Specification

## 1. Introduction

### 1.1 Purpose

This document outlines the functional requirements and specifications for integrating cloud-managed network platforms (such as Cisco Meraki, Aruba Central, Ubiquiti UniFi) with the CommandIT platform. The primary goal is to provide Managed Service Providers (MSPs) using CommandIT with centralized visibility into client network organizations/sites, logical network containers, devices (Switches, APs, Firewalls, MV Cameras, MG Gateways, MT Sensors, etc.), configurations, licenses, and key operational logs including sensor readings and webhook events. This integration aims to streamline monitoring, inventory management, documentation, troubleshooting, reporting, and license tracking for these environments managed across multiple clients.

### 1.2 Scope

- **In Scope:**
  - Secure authentication mechanism using vendor-specific API Keys or OAuth tokens.
  - Configuration within CommandIT for MSPs to manage integrations for different client networks/sites across supported vendors.
  - Scheduled synchronization of key inventory data: Organizations/Sites, Managed Networks, Devices (Switches, APs, Firewalls, Cameras (basic inventory), **Gateways (MG)**, Sensors), Configuration Templates (Meraki), Switch Port Profiles (Meraki), Licenses.
  - Synchronization of **Meraki MT Sensor readings, status, and basic health (e.g., battery)** via API polling.
  - **Real-time event ingestion via Meraki Webhooks** for critical MT sensor alerts and MX network/security events.
  - Synchronization of Client Connectivity History per device via API polling.
  - Synchronization of WAN Uplink Performance History (Loss/Latency) where available via API.
  - Synchronization of core network configurations: VLANs, SSIDs, Firewall Rules via API polling.
  - Automated backup and historical tracking of network device configurations via API polling.
  - Synchronization of key operational logs: Configuration Changes, Network Events, Security Events via API polling.
  - Mapping synced data to relevant CommandIT schema entities (Organizations, ManagedNetworks, Devices incl. tags, WirelessNetworks, Vlans, FirewallRules, AuditLog, DeviceEventLogs, SecurityThreatEvents, DeviceConfigurationHistory, ExternalSystemIdentifiers, SoftwareLicenses, DeviceClientHistory, WanLinkPerformanceLog, MerakiConfigurationTemplates, MerakiSwitchPortProfiles, EnvironmentalSensors, EnvironmentalReadings, DeviceBattery, Alerts, etc.).
  - Providing data views and reports within CommandIT based on the synchronized information.
  - Generating alerts within CommandIT based on specific events or configuration data retrieved from the APIs or received via Webhooks.
- **Out of Scope (Initial Version):**
  - **Configuration Push:** Direct modification of configurations via API from CommandIT.
  - **Real-time event streaming via MQTT** (for MT data).
  - **Synchronization of MV Sense analytic event data** (object counts, motion alerts, etc.).
  - **Deep traffic analysis.**
  - **Detailed historical log storage for Wireless Health.**
  - **Retrieval/Storage of video footage** from MV cameras.
  - **Deployment/Management of Custom CV models** on MV cameras.

### 1.3 Goals

- Provide MSPs/Admins with a single pane of glass for key managed network information across multiple clients and potentially multiple vendors.
- Automate the collection of inventory, configuration, status, license, template/profile definitions, sensor readings, and key historical performance/connectivity data via API polling.
- **Receive and process critical real-time alerts** for MT sensors and MX devices via Webhooks.
- Enable proactive alerting based on network events, configuration states, sensor thresholds, and webhook events.
- Reduce manual effort required for documenting and monitoring managed networks.
- Enhance visibility into network structure, device configurations, applied standards, security events, operational changes, licensing status, client connectivity, WAN performance, and environmental conditions.
- Establish a foundation for future configuration management and automation capabilities.

## 2. Architecture Overview

- The integration will leverage the **specific vendor's Dashboard API** (e.g., Meraki API v1) for polling data and **Webhook infrastructure** for receiving real-time events.
- Connections managed via IntegrationInstances.
- Authentication via **API Keys or OAuth tokens**, stored securely.
- **Scheduled background jobs** for **API polling-based** synchronization.
- **A dedicated backend endpoint** to receive incoming Webhook notifications from vendors like Meraki.
- Sync jobs and Webhook processors will populate CommandIT schema tables.
- Error handling and logging for both sync jobs and webhook processing.
- API **rate limits** handled gracefully for polling jobs.

## 3. MSP Setup & Configuration

### 3.1 API Key/Credential Generation & Security (Guidance)

- Provide clear guidance per supported vendor on generating API Keys/Credentials using dedicated service accounts with least-privilege read-only permissions.
- Emphasize secure storage.

### 3.2 Secure Key/Credential Storage

- Implement secure storage for API Keys/Tokens linked to IntegrationInstances via Credentials/CredentialUsage.

### 3.3 Managing Integrations

- Implement backend API (CRUD) for vendor-specific IntegrationInstances.
- **Integration Instance Creation:**
  - Requires: Link to CommandIT Client Organization (org\_id), integration\_type (e.g., 'MerakiAPI'), user-defined name, link to stored credential\_id (MSP's API Key).
  - Initial status should be 'PendingConfig'.
- **Organization Mapping UI (Within Integration Instance Detail/Edit Screen):**
  - Provide a button "Discover/Refresh Accessible Organizations".
  - **Action:** Triggers backend call using the linked credential\_id to GET /organizations (or vendor equivalent).
  - **Display:** Shows a list/dropdown of Organizations returned by the API (Name, External ID).
  - **Action:** MSP user selects the specific external Organization from the list that corresponds to the CommandIT Client Organization this IntegrationInstance is linked to.
  - **Action:** Upon selection, save the chosen external Organization ID to the IntegrationInstances.external\_organization\_id field. Update status from 'PendingConfig' to 'Ok' (if connection test also passes).
- **Webhook Receiver Configuration:**
  - Display the unique CommandIT endpoint URL for the vendor's webhook configuration.
  - Allow configuration of a shared secret for validating incoming webhooks (if supported by vendor).
  - Potentially allow enabling/disabling webhook processing for the instance.
- **API Connection Test:** Include function to verify API key and basic access to the mapped external\_organization\_id.

## 4. Client Setup & Configuration (Vendor Dashboard Permissions & Webhooks)

- MSP admin account (whose API key is used) needs necessary **read-only permissions** in the vendor dashboard for the specific client organization mapped in Task 3.3.
- **MSP must configure Webhook destinations within the vendor platform** (e.g., Meraki Dashboard -> Network-wide alerts -> HTTP servers) pointing to the URL provided by CommandIT (from Task 3.3) and using any required shared secret.

## 5. Backend Data Synchronization & Event Processing

### 5.1 Sync Job Architecture (API Polling)

- Scheduled background jobs per *active* ('Ok' status) vendor-specific IntegrationInstance.
- Jobs retrieve the target external\_organization\_id from the IntegrationInstance record.
- Jobs use stored API credentials associated with the instance.
- Different schedules possible for inventory vs. logs vs. performance data.

### 5.2 API Calls & Data Mapping (Read Sync: Vendor API -> CommandIT)

*(API calls are scoped using the mapped external\_organization\_id. Meraki examples used where applicable)*

- **Organizations/Sites:** GET /organizations -> ExternalSystemIdentifiers, Organizations. (Map external\_organization\_id during setup - Task 3.3). Optionally sync other org details.
- **Networks (Logical Containers):** GET /organizations/&#x7B;external\_organization\_id}/networks -> ManagedNetworks.
- **Devices (incl. MV Cameras, MT Sensors, MG Gateways):** GET /organizations/&#x7B;external\_organization\_id}/devices, GET /networks/&#x7B;networkId}/devices, GET /devices/&#x7B;serial} -> Upsert Devices. Map properties including tags. Store vendor device ID in ExternalSystemIdentifiers. Link Devices.managed\_network\_record\_id. *(For MV/MT/MG, ensure basic inventory fields like model, serial, status, firmware are mapped).*
- **Device Status:** GET /organizations/&#x7B;external\_organization\_id}/devices/statuses -> Update Devices.status.
- **Management Interface:** GET /devices/&#x7B;serial}/managementInterface -> Update DeviceNetworkAdapters or Devices.configuration.
- **VLANs:** GET /networks/&#x7B;networkId}/appliance/vlans -> Populate Vlans.
- **Wireless SSIDs:** GET /networks/&#x7B;networkId}/wireless/ssids/&#x7B;number} -> Populate WirelessNetworks. Store associated FW rules in FirewallRules.
- **Firewall Rules:** GET /networks/&#x7B;networkId}/appliance/firewall/...Rules -> Populate FirewallRules.
- **Configuration Backups:** GET /networks/&#x7B;networkId}/devices/&#x7B;serial}/configuration -> Populate DeviceConfigurationHistory.
- **Configuration Changes Log:** GET /organizations/&#x7B;external\_organization\_id}/configurationChanges -> Populate AuditLog.
- **Network Events Log:** GET /networks/&#x7B;networkId}/events -> Populate DeviceEventLogs.
- **Security Events Log:** GET /networks/&#x7B;networkId}/appliance/security/events -> Populate SecurityThreatEvents.
- **Vendor Licenses:** GET /organizations/&#x7B;external\_organization\_id}/licenses -> Populate SoftwareLicenses.
- **Client Connectivity History:** GET /devices/&#x7B;serial}/clients -> Populate DeviceClientHistory.
- **WAN Uplink Performance History:** GET /organizations/&#x7B;external\_organization\_id}/uplinksLossAndLatency or /devices/&#x7B;serial}/lossAndLatencyHistory -> Populate WanLinkPerformanceLog.
- **Meraki Configuration Templates:** GET /organizations/&#x7B;external\_organization\_id}/configTemplates -> Populate MerakiConfigurationTemplates.
- **Meraki Switch Port Profiles:** GET /networks/&#x7B;networkId}/switch/settings/profiles -> Populate MerakiSwitchPortProfiles. Update NetworkDevicePorts.
- **Meraki MT Sensor Readings & Health:** GET /networks/&#x7B;networkId}/sensors/readings/latest, /history. Define sensors in EnvironmentalSensors (incl. thresholds based on API data or defaults). Populate EnvironmentalReadings with history. Update EnvironmentalSensors.last\_reading\_value, last\_reading\_time, status. Query sensor health endpoints (if available) to update DeviceBattery.level\_percentage, DeviceBattery.status, and Devices.status (for connectivity).
- **Meraki MV Snapshots:** *(Optional/Out of Scope for V1)* If triggering/retrieving snapshots: POST /devices/&#x7B;serial}/camera/generateSnapshot, store URL/link potentially in Attachments.
- *(Deferred/Out of Scope Logs):* Traffic Analysis, Wireless Health Stats, MV Analytic Events.

### 5.3 Webhook Event Ingestion & Processing

- **Webhook Receiver Endpoint:** Implement a secure backend HTTP endpoint to receive POST requests from vendor webhooks (e.g., /api/webhooks/meraki/&#x7B;integrationInstanceId}).
- **Authentication/Validation:** Validate incoming requests using the shared secret configured in the IntegrationInstance (if applicable) or other vendor-specific validation methods.
- **Event Parsing:** Parse the JSON payload of the webhook request to identify the event type (e.g., MT sensor threshold violation, MX security event, device status change), affected network/device identifiers, timestamp, and relevant details.
- **Data Mapping & Action:**
  - For critical alerts (MT threshold exceeded, MX security event): Create or update records in the CommandIT Alerts table, linking to the appropriate Device or EnvironmentalSensor.
  - For status changes or network events: Create records in DeviceEventLogs or update Devices.status.
  - For sensor readings pushed via webhook: Update EnvironmentalSensors.last\_reading\_value/status and potentially create EnvironmentalReadings entries.
- **Error Handling:** Log errors during webhook processing (parsing failures, mapping issues). Implement retries if appropriate for transient errors.
- **Security:** Ensure the webhook receiver endpoint is protected against abuse (e.g., rate limiting, input validation).

### 5.4 Error Handling & Throttling (API Polling)

- Implement robust error handling for vendor-specific API errors. Log errors against IntegrationInstances.
- Implement vendor-specific rate limit handling (e.g., Meraki's 10 calls/sec/org).

## 6. Configuration Monitoring

- Develop engine to periodically query vendor APIs for specific configurations based on ComplianceRules.
- Implement comparison logic against desired state.
- Create/update DeviceComplianceResults.
- Trigger Alerts via AlertProcessingRules.

## 7. Configuration Push (Future Scope - Read Only Initially)

- **Future Goal:** Allow triggering configuration changes via vendor APIs.
- **Required API Calls:** Vendor-specific PUT/POST/DELETE endpoints.
- **Schema Support:** Use ConfigurationDeploymentLog table to track actions.
- **Permissions:** Will require API keys/credentials with **write permissions**.

## 8. Security Considerations

- **API Key/Token Security:** Secure storage via Credentials/CredentialUsage. Recommend least privilege service accounts.
- **Webhook Security:** Use shared secrets for validation. Protect the receiver endpoint.
- **Audit Logging:** Log all sync activities, **webhook processing events**, API calls, errors, config checks in AuditLog.

## 9. Data Mapping Summary (Example - Vendor Agnostic, Meraki Detail)

| **Vendor API Concept / Meraki Endpoint**       | **Key Property**                                 | **CommandIT Table(s)**                                     | **Key CommandIT Columns**                                                                                         |
| ---------------------------------------------- | ------------------------------------------------ | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Organization/Site / GET /organizations         | id, name                                         | ExternalSystemIdentifiers, Organizations                   | external\_identifier\_value, target\_entity\_id, name                                                             |
| Network / GET /.../networks                    | id, name, productTypes, timeZone                 | ManagedNetworks                                            | managed\_network\_record\_id, external\_network\_id, name, platform\_type='Meraki', platform\_specific\_config    |
| Device / GET /devices/&#x7B;serial}            | serial, name, model, mac, tags, firmware         | Devices, ExternalSystemIdentifiers                         | serial\_number, name, model\_number, mac\_address (adapter), tags, firmware\_version, external\_identifier\_value |
| Device Status / GET /.../statuses              | status                                           | Devices                                                    | status                                                                                                            |
| VLANs / GET /.../vlans                         | id, name, subnet, applianceIp                    | Vlans                                                      | vlan\_id (mapped), name, subnet, gateway                                                                          |
| Wireless SSIDs / GET /.../ssids/&#x7B;num}     | name, enabled, authMode, psk, etc.               | WirelessNetworks                                           | name, is\_enabled, authentication\_mode, encryption\_mode, psk                                                    |
| Firewall Rules / GET /.../firewall/rules       | policy, protocol, src/dest, etc.                 | FirewallRules                                              | action, protocol, source\_ip, dest\_ip, etc.                                                                      |
| Config Backup / GET /.../configuration         | Configuration Text                               | DeviceConfigurationHistory                                 | config\_content                                                                                                   |
| Config Change Log / GET /.../configChanges     | ts, adminName, label, oldValue, newValue         | AuditLog                                                   | timestamp, actor\_display\_name, event\_action, details                                                           |
| Network Event Log / GET /.../events            | occurredAt, type, description                    | DeviceEventLogs                                            | timestamp, event\_type, message                                                                                   |
| Security Event Log / GET /.../security/events  | ts, eventType, srcIp, destIp                     | SecurityThreatEvents                                       | timestamp, event\_type, source\_ip, destination\_ip                                                               |
| Licenses / GET /.../licenses                   | state, deviceCount, expirationDate               | SoftwareLicenses                                           | status, quantity\_purchased, expiry\_date, license\_type='MerakiCoTerm'                                           |
| Client History / GET /.../clients              | mac, ip, description, firstSeen, lastSeen, usage | DeviceClientHistory                                        | client\_mac, first\_seen\_timestamp, last\_seen\_timestamp, usage\_sent/received\_bytes                           |
| WAN Performance / GET /.../lossLatency         | startTs, endTs, lossPercent, latencyMs           | WanLinkPerformanceLog                                      | log\_timestamp\_utc, loss\_percent, latency\_ms                                                                   |
| Config Templates / GET /.../configTemplates    | id, name, productTypes                           | MerakiConfigurationTemplates                               | template\_id, name, product\_types                                                                                |
| Switch Port Profiles / GET /.../profiles       | id, name, config details                         | MerakiSwitchPortProfiles                                   | profile\_id, name, profile\_data                                                                                  |
| MT Sensor Readings / GET /.../sensors/readings | ts, serial, metric, value                        | EnvironmentalReadings, EnvironmentalSensors, DeviceBattery | reading\_timestamp, reading\_value, sensor\_id (linked via serial/label), battery\_level\_percentage              |
| *Webhook Events*                               | *Varies*                                         | Alerts, DeviceEventLogs, EnvironmentalReadings, etc.       | *Mapped based on event type*                                                                                      |

## 10. Future Considerations

- Implement **Configuration Push** capabilities (Section 7).
- **Expand Webhook support** to cover more event types or vendors beyond critical MT/MX alerts.



# Tasks:&#x20;

This document outlines the detailed backend tasks required to implement the Network Vendor API integration (using Meraki as the primary example) as specified in meraki\_integration\_spec\_v1 (v1.5 - Read Only + Webhooks), assuming a TypeScript environment with PostgreSQL/ORM access.

## Phase 1: Core Setup & Configuration Backend

- **Task 1.1: Implement/Verify Schema Migrations:**
  - **Context:** Ensure database structure supports Meraki/Network Vendor integration.
  - **Action:** Create/verify migration scripts for ManagedNetworks, MerakiConfigurationTemplates, MerakiSwitchPortProfiles, DeviceClientHistory, WanLinkPerformanceLog, EnvironmentalSensors, EnvironmentalReadings, ConfigurationDeploymentLog (for future use), and ensure necessary FKs/fields exist on IntegrationInstances, Devices, NetworkDevicePorts, Credentials, AuditLog, DeviceEventLogs, SecurityThreatEvents, SoftwareLicenses.
  - **Output:** Database schema matching specification.
  - **Success Criteria:** Migrations run successfully; schema introspection confirms tables/fields/constraints/indexes.
  - **Config Level:** Platform/Deployment.
- **Task 1.2: Secure Credential Storage for API Keys:**
  - **Context:** Securely store the MSP's Meraki API key(s) or other vendor credentials. (MSP Level Config).
  - **Action:** Implement logic to store API Keys securely, using the Credentials table (credential\_type='MerakiAPIKey', 'ArubaAPIKey', etc.) with robust encryption (e.g., using platform-level encryption keys) or integrate with an external vault. Implement strict access control for retrieval functions.
  - **Input:** API Key string, credential name, associated MSP org\_id.
  - **Output:** Securely stored credential record linked to the MSP org\_id.
  - **Schema Interaction:** Credentials (Write), Organizations (Read MSP Org ID).
  - **Success Criteria:** API keys stored encrypted; retrieval function secured and audited.
- **Task 1.3: Manage Network Vendor Integration Instances:**
  - **Context:** Allow MSPs to configure integration for each client's network vendor instance (e.g., a specific Meraki Organization). (Org/Client Level Config Instance, managed by MSP).
  - **Action:** Implement backend RESTful API endpoints (CRUD) for IntegrationInstances. Required fields on Create: CommandIT Client org\_id, integration\_type (e.g., 'MerakiAPI'), name, credential\_id (linking to the MSP's stored key from Task 1.2). Set initial status to 'PendingConfig'. Update allows modifying name, is\_enabled, credential\_id, configuration JSONB. Delete removes the instance. Enforce authorization (MSP user needs rights for the client org\_id).
  - **Input:** Instance details (Org ID, Type, Name, Credential ID).
  - **Output:** Created/Updated/Deleted IntegrationInstances record.
  - **Schema Interaction:** IntegrationInstances (CRUD), Credentials (Read Link), Organizations (Read).
  - **Success Criteria:** API endpoints function; data persisted; authorization enforced.
- **Task 1.4: Implement Meraki Org Discovery & Mapping Backend Logic:**
  - **Context:** Allow MSPs to link a CommandIT client org to the correct Meraki organization accessible via their API key. (MSP action within Org/Client Level config setup).
  - **Action:**
    - Create backend API endpoint (e.g., GET /api/integrations/meraki/discoverOrgs?credentialId=...). Logic uses credential\_id to fetch API key, calls Meraki GET /organizations via Meraki API Client Wrapper, returns list (Meraki Org ID, Name).
    - Create backend API endpoint (e.g., PUT /api/integrationInstances/&#x7B;instanceId}) to receive the selected external\_organization\_id (Meraki Org ID) from the UI. Logic saves this ID to the specified IntegrationInstances record and attempts to update status from 'PendingConfig' to 'Ok' (potentially after running connection test Task 1.6).
  - **Input:** credential\_id (for discovery), instanceId and selected external\_organization\_id (for saving).
  - **Output:** List of Meraki Orgs (for discovery), updated IntegrationInstances record (for saving).
  - **API Interaction:** Meraki GET /organizations.
  - **Schema Interaction:** IntegrationInstances (Update external\_organization\_id, status), Credentials (Read).
  - **Success Criteria:** Accessible Meraki Orgs listed; selected Meraki Org ID saved correctly to the client's IntegrationInstance.
- **Task 1.5: Implement Webhook Receiver Endpoint Setup:**
  - **Context:** Provide necessary info and storage for vendor webhook configuration. (Org/Client Level Config).
  - **Action:** Backend logic to generate a unique, persistent webhook URL per IntegrationInstance (e.g., /api/webhooks/&#x7B;vendor}/&#x7B;instanceId} or using a unique token stored on the instance). Implement API endpoints for UI to retrieve this URL and to set/get a shared\_secret (store securely, e.g., encrypted in IntegrationInstances.configuration or linked Credentials).
  - **Input:** instanceId. For setting secret: shared\_secret string.
  - **Output:** Webhook URL, stored shared secret.
  - **Schema Interaction:** IntegrationInstances (Read/Write configuration or link to Credentials).
  - **Success Criteria:** Unique URL generated; shared secret stored securely; UI retrieves necessary info.
- **Task 1.6: Implement API Connection Test Endpoint:**
  - **Context:** Verify API key validity and access to the mapped external Org/Site. (Org/Client Level config check).
  - **Action:** Implement backend API endpoint POST /api/integrationInstances/&#x7B;instanceId}/test.
  - **Logic:** Retrieves instanceId, its credential\_id, and mapped external\_organization\_id. Uses Meraki API Client Wrapper (Task 2.1) to call a basic read endpoint scoped to the org (e.g., Meraki GET /organizations/&#x7B;external\_organization\_id}/networks).
  - **Output:** JSON \{ success: boolean, message: string } indicating success or specific error (auth failed, org not found, permission denied).
  - **Success Criteria:** Endpoint accurately reflects API key validity and access to the mapped external Org.

## Phase 2: Authentication & API Client

- **Task 2.1: Develop Network Vendor API Client Wrapper (e.g., MerakiApiClient):**
  - **Context:** Create a reusable TypeScript client for vendor API interactions.
  - **Action:** Develop class. Takes API key, base URL. Implements methods for GET/POST/PUT/DELETE. Automatically adds vendor-specific headers (e.g., X-Cisco-Meraki-API-Key). Implements pagination logic (e.g., Meraki Link headers). Implements rate limit handling (detect 429, respect Retry-After, exponential backoff, track calls per org ID for Meraki's limit). Parses common API errors.
  - **Libraries:** axios or similar.
  - **Success Criteria:** Wrapper simplifies calls; handles auth, pagination, errors, rate limiting per vendor specifics.
  - **Unit Test(s):** Mock successful calls. Mock pagination responses. Mock 429 responses (with/without Retry-After). Mock 401/403/404 errors. Verify correct headers are added. Verify rate limit logic pauses/retries appropriately.

## Phase 3: Core Inventory Sync (Read - Vendor API)

- **Task 3.1: Sync Job Framework:**
  - **Context:** Orchestrate periodic data synchronization per integration instance.
  - **Action:** Utilize/adapt a generic Sync Job Scheduler/Queue (e.g., BullMQ). Create job definitions for Meraki (and other vendors). Jobs target active IntegrationInstances based on integration\_type. Retrieve the target external\_organization\_id and credential\_id for each job run. Update IntegrationInstances status/timestamps/errors.
  - **Schema Interaction:** IntegrationInstances (Read config, Update status).
  - **Success Criteria:** Vendor-specific sync jobs scheduled and executed reliably per tenant.
- **Task 3.2: Implement Network Sync:**
  - **Context:** Sync logical network containers (Meraki Networks, UniFi Sites, etc.).
  - **Action:** Create sync job task. Use API Client Wrapper to call vendor equivalent of GET /organizations/&#x7B;orgId}/networks. Perform upsert into ManagedNetworks based on external\_network\_id and integration\_instance\_id. Map id, name, timeZone, tags. Store vendor-specific details (Meraki productTypes, templateId) in platform\_specific\_config. Set network\_platform\_type. Update last\_sync\_time.
  - **Schema Interaction:** ManagedNetworks (Upsert), IntegrationInstances (Read).
  - **Success Criteria:** ManagedNetworks table accurately reflects containers for the client org.
- **Task 3.3: Implement Device Synchronization:**
  - **Context:** Sync devices (MX, MS, MR, MV, MT, MG for Meraki; switches/APs/gateways for others).
  - **Action:** Create sync job task. Use API Client to call vendor equivalent of GET /organizations/&#x7B;orgId}/devices or /networks/&#x7B;netId}/devices. Get details via /devices/&#x7B;serial} or equivalent. Perform upsert into Devices based on serialNumber (or other reliable unique ID) and org\_id. Map properties: name, model->model\_number, mac->primary DeviceNetworkAdapters, lanIp->ip\_address, tags->tags, firmware->firmware\_version, status->status. Set manufacturer\_id. Store vendor device ID/Serial in ExternalSystemIdentifiers. Link Devices.managed\_network\_record\_id using network ID from API response. Update last\_sync\_time.
  - **Schema Interaction:** Devices (Upsert), Manufacturers (Read), ManagedNetworks (Read), DeviceNetworkAdapters (Upsert), ExternalSystemIdentifiers (Upsert).
  - **Success Criteria:** Devices table accurately reflects vendor device inventory; links to network and external IDs created.
- **Task 3.4: Implement Device Status Sync:**
  - **Context:** Keep device operational status up-to-date (potentially more frequent sync).
  - **Action:** Create sync job task. Fetch vendor equivalent of GET /organizations/&#x7B;orgId}/devices/statuses. Update Devices.status field based on the result for each device.
  - **Schema Interaction:** Devices (Update).
  - **Success Criteria:** Devices.status reflects current vendor status.

## Phase 4: Detailed Configuration Sync (Read - Vendor API)

- **Task 4.1: Implement Management Interface Sync:** Fetch vendor equivalent of GET /devices/&#x7B;serial}/managementInterface. Update corresponding DeviceNetworkAdapters record or store relevant details in Devices.configuration.
  - **Unit Test(s):** Verify data correctly updates DeviceNetworkAdapters or Devices.configuration.
- **Task 4.2: Implement VLAN Sync:** Fetch vendor equivalent of GET /networks/&#x7B;netId}/.../vlans. Upsert into Vlans table linked to org\_id or ManagedNetworks.
  - **Unit Test(s):** Verify Vlans records created/updated correctly.
- **Task 4.3: Implement Wireless SSID Sync:** Fetch vendor equivalent of GET /networks/&#x7B;netId}/wireless/ssids/&#x7B;num}. Upsert into WirelessNetworks. Map settings (auth, encryption, PSK ref, VLAN ID). Store associated firewall rules (if applicable and returned with SSID) in FirewallRules linked to WirelessNetworks.
  - **Unit Test(s):** Verify WirelessNetworks created/updated. Verify associated FirewallRules created/updated if applicable.
- **Task 4.4: Implement Firewall Rule Sync:** Fetch vendor equivalent of GET /networks/&#x7B;netId}/appliance/firewall/...Rules. Upsert into FirewallRules linked to the firewall Device. Map rule details.
  - **Unit Test(s):** Verify FirewallRules created/updated, linked correctly to the firewall Device.
- **Task 4.5: Implement Config Backup Sync:** Periodically fetch vendor equivalent of GET /devices/&#x7B;serial}/configuration. Create new DeviceConfigurationHistory records with timestamp, type, and content. Implement logic to avoid storing unchanged configs if desired.
  - **Unit Test(s):** Verify DeviceConfigurationHistory records created. Test change detection logic (if implemented).
- **Task 4.6: Implement Meraki Template Sync:** Fetch GET /organizations/&#x7B;orgId}/configTemplates. Upsert into MerakiConfigurationTemplates. Update ManagedNetworks.platform\_specific\_config with templateId for bound networks.
  - **Unit Test(s):** Verify MerakiConfigurationTemplates created/updated. Verify ManagedNetworks updated correctly for bound networks.
- **Task 4.7: Implement Meraki Switch Profile Sync:** Fetch GET /networks/&#x7B;netId}/switch/settings/profiles (or equivalent). Upsert into MerakiSwitchPortProfiles. Update NetworkDevicePorts.applied\_switch\_profile\_id based on data retrieved from switch port configuration sync (which might be part of Task 3.3 device detail fetch or a separate port detail sync task).
  - **Unit Test(s):** Verify MerakiSwitchPortProfiles created/updated. Verify NetworkDevicePorts FK is updated correctly when port config sync runs.

## Phase 5: Log & Performance Data Sync (Read - Vendor API)

- **Task 5.1: Implement Config Changes Log Sync:** Fetch vendor equivalent of GET /organizations/&#x7B;orgId}/configurationChanges. Create AuditLog entries (source='VendorAPI', e.g., 'MerakiAPI'). Implement checkpointing (using timestamps or pagination tokens) to avoid fetching old logs repeatedly.
  - **Unit Test(s):** Verify AuditLog entries created with correct source/details. Test checkpointing logic.
- **Task 5.2: Implement Network Events Log Sync:** Fetch vendor equivalent of GET /networks/&#x7B;netId}/events. Create DeviceEventLogs entries (source='VendorAPI'). Implement checkpointing/filtering.
  - **Unit Test(s):** Verify DeviceEventLogs entries created, linked to devices. Test checkpointing/filtering.
- **Task 5.3: Implement Security Events Log Sync:** Fetch vendor equivalent of GET /networks/&#x7B;netId}/appliance/security/events. Create SecurityThreatEvents entries (source='VendorAPI'). Implement checkpointing/filtering.
  - **Unit Test(s):** Verify SecurityThreatEvents entries created, linked to devices. Test checkpointing/filtering.
- **Task 5.4: Implement License Sync:** Fetch vendor equivalent of GET /organizations/&#x7B;orgId}/licenses. Upsert SoftwareLicenses record(s) for the org (license\_type='VendorSpecific'). Map status, counts, expiry.
  - **Unit Test(s):** Verify SoftwareLicenses created/updated correctly reflecting Meraki co-term or other vendor models.
- **Task 5.5: Implement Client Connectivity History Sync:** Fetch vendor equivalent of GET /devices/&#x7B;serial}/clients. Create/update DeviceClientHistory. Implement pagination/timespan logic. Implement data retention/cleanup strategy.
  - **Unit Test(s):** Verify DeviceClientHistory records created/updated. Test pagination/timespan logic.
- **Task 5.6: Implement WAN Uplink Performance Sync:** Fetch vendor equivalent of /lossAndLatencyHistory endpoints. Create WanLinkPerformanceLog entries. Handle pagination/timespans. Implement data retention/cleanup.
  - **Unit Test(s):** Verify WanLinkPerformanceLog records created. Test pagination/timespan logic.

## Phase 6: MT Sensor Sync (Read - Meraki API)

- **Task 6.1: Implement MT Sensor Reading Sync:** Fetch Meraki /sensors/readings/latest & /history. Perform upsert on EnvironmentalSensors (match by serial, define sensor type/label/units/thresholds). Populate EnvironmentalReadings with history. Update EnvironmentalSensors latest reading/status.
  - **Unit Test(s):** Verify EnvironmentalSensors created/updated. Verify EnvironmentalReadings populated. Test status update based on thresholds.
- **Task 6.2: Implement MT Sensor Health Sync:** Query Meraki API for sensor health (battery, connectivity). Update DeviceBattery and Devices.status for the MT sensor Device record.
  - **Unit Test(s):** Verify DeviceBattery and Devices.status updated correctly.

## Phase 7: Webhook Event Processing

- **Task 7.1: Implement Webhook Receiver Endpoint:** Create secure HTTP POST endpoint (e.g., /api/webhooks/meraki/&#x7B;instanceId}). Ensure it can handle vendor JSON payloads.
  - **Unit Test(s):** Test endpoint receives POST requests successfully. Test routing based on instance ID/token.
- **Task 7.2: Implement Webhook Validation:** Implement validation using shared secret stored for the IntegrationInstance. Reject requests with invalid secrets.
  - **Unit Test(s):** Test valid secret allows processing. Test invalid secret results in rejection (e.g., 401/403 response).
- **Task 7.3: Implement Webhook Event Parser:** Develop logic to parse different Meraki webhook event types (MT alerts, MX events, device status, etc.) identified in the payload.
  - **Unit Test(s):** Test parsing logic for various known Meraki webhook payload formats. Handle unknown formats gracefully.
- **Task 7.4: Implement Webhook Data Mapping:** Map parsed webhook data to create/update records: Alerts (critical events), DeviceEventLogs (network events), EnvironmentalReadings/EnvironmentalSensors (MT readings/thresholds), Devices.status. Queue actions for backend processing.
  - **Unit Test(s):** Test mapping logic creates/updates the correct records in the database based on different webhook event types.

## Phase 8: Configuration Monitoring & Alerting

- **Task 8.1: Implement Configuration Check Engine:** Develop scheduled service. Reads ComplianceRules targeting vendor configs (e.g., 'Meraki'). Queries synced data (DeviceConfigurationHistory, WirelessNetworks, FirewallRules, Meraki\* tables).
  - **Unit Test(s):** Test engine identifies relevant rules and queries correct schema tables.
- **Task 8.2: Implement Comparison Logic:** Implement comparison between actual state (from schema) and desired state in ComplianceRules.
  - **Unit Test(s):** Test comparison logic identifies compliant/non-compliant states correctly.
- Task 8.3: Implement DeviceComplianceResults Logging: Create/update DeviceComplianceResults based on comparison outcomes.
  - **Unit Test(s):** Verify DeviceComplianceResults records created/updated accurately.
- **Task 8.4: Implement Alerting Integration:** Develop logic for AlertProcessingRules to evaluate results or critical webhook events/polled logs and create Alerts.
  - **Unit Test(s):** Test rule evaluation triggers Alerts correctly.

## Phase 9: Cross-Cutting Concerns

- **Task 9.1: Centralized Audit Logging:** Ensure all sync operations, API calls, errors, webhook processing, config checks are logged to AuditLog with appropriate context (source\_platform='MerakiAPI', etc.).
  - **Unit Test(s):** Verify key actions generate expected AuditLog entries.
- **Task 9.2: Error Handling Framework:** Implement consistent error handling (try/catch, custom error types) for API calls and webhook processing. Update IntegrationInstances status/error messages. Integrate with queue retry logic.
  - **Unit Test(s):** Simulate API/processing errors; verify they are caught, logged, and instance status updated.
- **Task 9.3: Throttling Implementation:** Implement and test Meraki-specific rate limit handling (10 calls/sec/org) in the Meraki Client Wrapper (Task 2.1). Add monitoring for 429 errors.
  - **Unit Test(s):** Mock 429 responses; verify client wrapper waits/retries correctly according to Meraki limits.
- **Task 9.4: Security Implementation:** Ensure secure fetching/handling of API keys. Validate webhook shared secrets. Review code for security best practices.
  - **Unit Test(s):** Test credential storage/retrieval security. Test webhook validation logic. Code reviews are primary verification.

