Skip to main content

CampaignManager

Struct CampaignManager 

Source
pub struct CampaignManager { /* private fields */ }
Expand description

Main orchestrator for campaign correlation.

Coordinates fingerprint indexing, campaign detection, and state management. This is the entry point for the correlation subsystem.

§Thread Safety

All methods are thread-safe and can be called concurrently. The manager uses lock-free data structures (DashMap) and atomic counters for high-performance concurrent access.

§Registration vs Detection

  • Registration (register_* methods): Called per-request, must be FAST. Only updates indexes, no detection logic.
  • Detection (run_detection_cycle): Called periodically by background worker or on-demand. Processes all detectors and applies campaign updates.

§Detectors (ordered by weight)

  1. Attack Sequence (50) - Same attack payloads across actors
  2. Auth Token (45) - Same JWT structure/issuer across IPs
  3. HTTP Fingerprint (40) - Identical browser fingerprint (JA4H)
  4. TLS Fingerprint (35) - Same TLS signature (JA4)
  5. Behavioral Similarity (30) - Identical navigation/timing patterns
  6. Timing Correlation (25) - Coordinated request timing (botnets)
  7. Network Proximity (15) - Same ASN or /24 subnet

Implementations§

Source§

impl CampaignManager

Source

pub fn new() -> Self

Create a new campaign manager with default configuration.

Source

pub fn with_config(config: ManagerConfig) -> Self

Create a new campaign manager with custom configuration.

Source

pub fn set_access_list_manager( &mut self, manager: Arc<ParkingLotRwLock<AccessListManager>>, )

Set the AccessListManager for automated mitigation.

Source

pub fn set_telemetry_client(&mut self, client: Arc<TelemetryClient>)

Set the TelemetryClient for cross-tenant correlation.

Source

pub fn register_ja4(&self, ip: IpAddr, fingerprint: String)

Register a JA4 fingerprint for an IP address.

Called during request processing - must be fast. Only updates indexes, no detection logic is run.

§Arguments
  • ip - The IP address of the client
  • fingerprint - The JA4 TLS fingerprint
Source

pub fn register_ja4_arc(&self, ip: IpAddr, fingerprint: Arc<str>)

Register a JA4 fingerprint using Arc to reduce allocations.

Optimized version for callers who already have an Arc fingerprint. This avoids cloning the fingerprint string when it’s already reference-counted.

§Arguments
  • ip - The IP address of the client
  • fingerprint - The JA4 TLS fingerprint as Arc
Source

pub fn register_combined(&self, ip: IpAddr, fingerprint: String)

Register a combined (JA4+JA4H) fingerprint for an IP address.

Combined fingerprints provide higher confidence correlation due to increased specificity.

§Arguments
  • ip - The IP address of the client
  • fingerprint - The combined fingerprint hash
Source

pub fn register_combined_arc(&self, ip: IpAddr, fingerprint: Arc<str>)

Register a combined fingerprint using Arc to reduce allocations.

Optimized version for callers who already have an Arc fingerprint. This avoids cloning the fingerprint string when it’s already reference-counted.

§Arguments
  • ip - The IP address of the client
  • fingerprint - The combined fingerprint hash as Arc
Source

pub fn register_fingerprints( &self, ip: IpAddr, ja4: Option<String>, ja4h: Option<String>, )

Register both JA4 and JA4H fingerprints.

Convenience method for registering both fingerprint types in one call.

§Arguments
  • ip - The IP address of the client
  • ja4 - Optional JA4 TLS fingerprint
  • ja4h - Optional JA4H HTTP fingerprint (used in combined hash)
Source

pub fn record_attack( &self, ip: IpAddr, payload_hash: String, attack_type: String, path: String, )

Record an attack payload observation for campaign correlation.

Called when an attack is detected (SQLi, XSS, etc.) to correlate identical payloads across different IPs. Weight: 50 (highest signal).

§Arguments
  • ip - The IP address of the attacker
  • payload_hash - Hash of the normalized attack payload
  • attack_type - Classification (sqli, xss, path_traversal, etc.)
  • path - Target path of the attack
Source

pub fn record_token(&self, ip: IpAddr, jwt: &str)

Record a JWT token observation for campaign correlation.

Called when a JWT is seen in request headers. Correlates IPs using tokens with identical structure or issuer. Weight: 45.

§Arguments
  • ip - The IP address of the client
  • jwt - The raw JWT string (header.payload.signature)
Source

pub fn record_request(&self, ip: IpAddr, method: &str, path: &str)

Record a request for behavioral and timing analysis.

Should be called for every request to build behavioral patterns and detect timing correlations. Updates multiple detectors:

  • Behavioral detector (weight: 30) - navigation patterns
  • Timing detector (weight: 25) - request synchronization
  • Network detector (weight: 15) - subnet correlation
§Arguments
  • ip - The IP address of the client
  • method - HTTP method (GET, POST, etc.)
  • path - Request path
Source

pub fn record_request_full( &self, ip: IpAddr, method: &str, path: &str, ja4: Option<&str>, jwt: Option<&str>, )

Record a request with full context for all applicable detectors.

Convenience method that records data to multiple detectors at once. Call this during request processing to capture all correlation signals.

§Arguments
  • ip - The IP address of the client
  • method - HTTP method
  • path - Request path
  • ja4 - Optional JA4 TLS fingerprint
  • jwt - Optional JWT from Authorization header
Source

pub fn record_relation(&self, entity_a: &str, entity_b: &str)

Record a relationship for graph correlation.

Records a connection between two entities (e.g., IP and Fingerprint) to build the correlation graph.

§Arguments
  • entity_a - First entity ID (e.g., “ip:1.2.3.4”)
  • entity_b - Second entity ID (e.g., “fp:abc12345”)
Source

pub fn calculate_campaign_score(&self, campaign: &Campaign) -> f64

Calculate weighted campaign score from all correlation reasons.

The score is computed as the weighted average of all correlation reasons, where each reason’s contribution is: weight * confidence / total_reasons

§Arguments
  • campaign - The campaign to score
§Returns

A score between 0.0 and 50.0 (max weight * max confidence)

Source

pub async fn run_detection_cycle(&self) -> DetectorResult<usize>

Run all 7 detectors in parallel and process updates with weighted scoring.

Called periodically by background worker or on-demand. Detectors run concurrently for improved performance (~70ms savings at scale):

  1. Attack Sequence (50) - Same attack payloads
  2. Auth Token (45) - Same JWT structure/issuer
  3. HTTP Fingerprint (40) - Identical JA4H
  4. TLS Fingerprint (35) - Same JA4
  5. Behavioral Similarity (30) - Navigation patterns
  6. Timing Correlation (25) - Synchronized requests
  7. Network Proximity (15) - Same ASN/subnet
§Returns

Number of campaign updates processed.

§Errors

Returns an error if any detector fails critically.

Source

pub async fn get_cached_groups(&self, threshold: usize) -> Vec<FingerprintGroup>

Get fingerprint groups above threshold with caching.

This method caches the results of get_groups_above_threshold() for 100ms to avoid repeated expensive O(n) scans during a single detection cycle. Multiple detectors can use the same cached result within the TTL window.

§Arguments
  • threshold - Minimum number of IPs required for a group
§Returns

Vector of fingerprint groups above the threshold.

Source

pub async fn invalidate_group_cache(&self)

Invalidate the fingerprint groups cache.

Called when significant changes occur that would affect group composition.

Source

pub fn should_trigger_detection(&self, ip: &IpAddr) -> bool

Check if an IP should trigger immediate detection.

Used for event-driven detection on new requests. Checks all 7 detectors to see if any threshold has been reached that warrants immediate analysis.

§Arguments
  • ip - The IP address to check
§Returns

true if immediate detection should be triggered.

Source

pub fn get_campaigns(&self) -> Vec<Campaign>

Get all active campaigns for API response.

Returns campaigns with Detected or Active status.

Source

pub fn get_all_campaigns(&self) -> Vec<Campaign>

Get all campaigns (including resolved/dormant).

Source

pub fn snapshot(&self) -> Vec<Campaign>

Create a snapshot of all campaigns for persistence.

Returns all campaigns regardless of status.

Source

pub fn restore(&self, campaigns: Vec<Campaign>)

Restore campaigns from a snapshot.

Clears existing state and loads the provided campaigns.

Source

pub fn get_campaign(&self, id: &str) -> Option<Campaign>

Get a specific campaign by ID.

§Arguments
  • id - The campaign ID to retrieve
§Returns

The campaign if found, None otherwise.

Source

pub fn get_campaign_actors(&self, campaign_id: &str) -> Vec<IpAddr>

Get IPs that are members of a campaign.

§Arguments
  • campaign_id - The campaign ID to query
§Returns

Vector of IP addresses in the campaign.

Source

pub fn get_campaign_graph(&self, campaign_id: &str) -> Value

Get the correlation graph for a campaign.

Source

pub fn get_campaign_graph_paginated( &self, campaign_id: &str, limit: Option<usize>, offset: Option<usize>, hash_identifiers: bool, ) -> PaginatedGraph

Get the correlation graph for a campaign with pagination and identifier hashing. P1 fix: Supports pagination to prevent memory exhaustion and hashes identifiers to prevent information disclosure.

Source

pub fn stats(&self) -> ManagerStats

Get current statistics.

Returns a snapshot of manager statistics including index and store stats.

Source

pub fn start_background_worker(self: Arc<Self>) -> JoinHandle<()>

Start background detection worker.

Returns a handle that can be used to await worker completion. The worker runs detection cycles at the configured interval until the manager is dropped or shutdown is signaled.

§Returns

JoinHandle for the background task.

Source

pub fn shutdown(&self)

Signal the background worker to shut down.

Source

pub fn is_shutdown(&self) -> bool

Check if shutdown has been signaled.

Source

pub fn remove_ip(&self, ip: &IpAddr)

Remove an IP from tracking (called when entity is evicted).

Cleans up the IP from:

  • Fingerprint index
  • Any associated campaigns
§Arguments
  • ip - The IP address to remove
Source

pub fn index(&self) -> &Arc<FingerprintIndex>

Get the fingerprint index (for integration with EntityManager).

Allows direct access to the index for advanced use cases.

Source

pub fn store(&self) -> &Arc<CampaignStore>

Get the campaign store (for integration).

Allows direct access to the store for advanced use cases.

Source

pub fn config(&self) -> &ManagerConfig

Get the current configuration.

Source

pub fn resolve_campaign( &self, campaign_id: &str, reason: &str, ) -> Result<(), DetectorError>

Resolve a campaign.

§Arguments
  • campaign_id - The campaign ID to resolve
  • reason - The reason for resolution
§Returns

Ok(()) if successful, Err if campaign not found or already resolved.

Source

pub fn clear(&self)

Clear all state (primarily for testing).

Clears fingerprint index, campaign store, and detector state.

Trait Implementations§

Source§

impl Default for CampaignManager

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,