<?php
/**
 * Copyright (с) Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2025 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * https://www.cloudlinux.com/legal/
 */

namespace CloudLinux\Imunify\App\Bot;

/**
 * Six-category bot classification engine.
 *
 * Composes the UA signature matcher, anti-spoofing real-IP resolver, bot-IP
 * range lookups, datacenter detector, and header anomaly scorer into a
 * single classify() call that returns one of the six Category constants.
 *
 * Decision pipeline (order matters):
 *   1. Honeypot triggered                              -> MALICIOUS_BOT
 *   2. UA matches malicious tool signature             -> MALICIOUS_BOT
 *   3. UA matches search-engine signature + IP in bundled range -> VERIFIED_SEARCH_ENGINE
 *      UA matches search-engine signature + IP not in range, but rDNS verifier
 *                                          forward-confirms a provider suffix -> VERIFIED_SEARCH_ENGINE
 *      UA matches search-engine signature otherwise   -> UNVERIFIED_BOT
 *   4. UA matches ai-crawler signature + IP matches    -> VERIFIED_AI_CRAWLER
 *      UA matches ai-crawler signature + IP not in range, but rDNS verifier
 *                                          forward-confirms a provider suffix -> VERIFIED_AI_CRAWLER
 *      UA matches ai-crawler signature + IP not in range, but ClaudeBot UA
 *                                          from datacenter IP (weak verify)   -> VERIFIED_AI_CRAWLER
 *      UA matches ai-crawler signature otherwise      -> UNVERIFIED_BOT
 *   5. Empty / whitespace-only UA                      -> UNVERIFIED_BOT
 *   6. Datacenter IP + at least one header anomaly     -> UNKNOWN_AUTOMATED
 *   7. Otherwise                                       -> HUMAN
 *
 * The real client IP is determined by RealIpResolver before any verification
 * step runs, so forged CDN headers from a direct attacker never succeed in
 * impersonating a verified bot provider.
 *
 * @since 4.0.0
 */
class Classifier {

	/**
	 * Minimum header anomaly score that promotes a datacenter-origin
	 * request to Unknown Automated. One anomaly is a very low bar,
	 * intentionally — the classifier only reaches this branch when no
	 * bot UA matched, so a genuinely clean browser request from a
	 * datacenter IP is still left as HUMAN.
	 */
	const UNKNOWN_AUTOMATED_MIN_ANOMALIES = 1;

	/**
	 * UA signature matcher configured with malicious / search-engine / ai-crawler categories.
	 *
	 * @var UserAgentSignatures
	 */
	private $ua_signatures;

	/**
	 * Anti-spoofing resolver used to derive the real client IP before verification.
	 *
	 * @var RealIpResolver
	 */
	private $real_ip_resolver;

	/**
	 * Bot-IP lookup restricted to verified search-engine providers.
	 *
	 * @var IpRangeLookup
	 */
	private $search_engine_ips;

	/**
	 * Bot-IP lookup restricted to verified AI-crawler providers.
	 *
	 * @var IpRangeLookup
	 */
	private $ai_crawler_ips;

	/**
	 * Datacenter IP detector driving the Unknown Automated signal.
	 *
	 * @var DatacenterDetector
	 */
	private $datacenter;

	/**
	 * Optional rDNS verifier for search-engine providers whose IP ranges
	 * are not bundled (Yandex, Baidu, Sogou, Seznam, Naver, Mojeek).
	 *
	 * @var RdnsVerifier|null
	 */
	private $rdns_verifier;

	/**
	 * Optional rDNS verifier for AI-crawler providers whose IP ranges
	 * are not bundled (Amazonbot, CCBot, Bytespider, YouBot).
	 *
	 * @var RdnsVerifier|null
	 */
	private $ai_rdns_verifier;

	/**
	 * Wire up the classifier over its component primitives.
	 *
	 * @param UserAgentSignatures $ua_signatures     UA matcher with malicious / search-engine / ai-crawler categories.
	 * @param RealIpResolver      $real_ip_resolver  Anti-spoofing client-IP resolver.
	 * @param IpRangeLookup       $search_engine_ips Bot-IP lookup for verified search engines.
	 * @param IpRangeLookup       $ai_crawler_ips    Bot-IP lookup for verified AI crawlers.
	 * @param DatacenterDetector  $datacenter        Datacenter IP detector for Unknown Automated signal.
	 * @param RdnsVerifier|null   $rdns_verifier     Optional FCrDNS verifier for non-bundled search-engine providers.
	 * @param RdnsVerifier|null   $ai_rdns_verifier  Optional FCrDNS verifier for non-bundled AI-crawler providers.
	 */
	public function __construct(
		$ua_signatures,
		$real_ip_resolver,
		$search_engine_ips,
		$ai_crawler_ips,
		$datacenter,
		$rdns_verifier = null,
		$ai_rdns_verifier = null
	) {
		$this->ua_signatures     = $ua_signatures;
		$this->real_ip_resolver  = $real_ip_resolver;
		$this->search_engine_ips = $search_engine_ips;
		$this->ai_crawler_ips    = $ai_crawler_ips;
		$this->datacenter        = $datacenter;
		$this->rdns_verifier     = $rdns_verifier;
		$this->ai_rdns_verifier  = $ai_rdns_verifier;
	}

	/**
	 * Classify a request into one of the six Category values.
	 *
	 * @param array  $headers            Request headers (case-insensitive keys).
	 * @param string $remote_addr        Socket peer IP.
	 * @param string $server_protocol    Value of $_SERVER['SERVER_PROTOCOL'] (e.g. "HTTP/2.0").
	 * @param bool   $honeypot_triggered Whether the pipeline detected a honeypot hit.
	 * @return string One of the Category constants.
	 */
	public function classify( $headers, $remote_addr, $server_protocol = '', $honeypot_triggered = false ) {
		if ( true === $honeypot_triggered ) {
			return Category::MALICIOUS_BOT;
		}

		$normalised = RealIpResolver::normaliseHeaders( $headers );
		$ua         = isset( $normalised['user-agent'] ) && is_string( $normalised['user-agent'] )
			? $normalised['user-agent']
			: '';
		$client_ip  = $this->real_ip_resolver->resolveFromNormalised( $normalised, $remote_addr );

		// Check UA categories in Classifier's documented priority order rather
		// than delegating to UserAgentSignatures::classify(), which returns the
		// first match in *its* registration order. Bundled token lists overlap
		// (e.g. "Scrapy" in ai-crawler and malicious), so enforcing priority
		// here is load-bearing: a UA that matches both categories must take
		// the higher-priority classification.
		if ( $this->ua_signatures->matchesCategory( $ua, UserAgentSignatures::CATEGORY_MALICIOUS ) ) {
			return Category::MALICIOUS_BOT;
		}

		if ( $this->ua_signatures->matchesCategory( $ua, UserAgentSignatures::CATEGORY_SEARCH_ENGINE ) ) {
			if ( null !== $this->search_engine_ips->find( $client_ip ) ) {
				return Category::VERIFIED_SEARCH_ENGINE;
			}
			// Bundled IP range missed — fall through to forward-confirmed
			// reverse DNS for providers whose ranges we don't ship
			// (Yandex/Baidu/Sogou/Seznam/Naver/Mojeek). The verifier is
			// optional; when not wired, behaviour matches Phase-0: UA
			// match without IP confirmation drops to UNVERIFIED_BOT.
			if ( null !== $this->rdns_verifier && $this->rdns_verifier->verifyAgainstUa( $client_ip, $ua ) ) {
				return Category::VERIFIED_SEARCH_ENGINE;
			}
			return Category::UNVERIFIED_BOT;
		}

		if ( $this->ua_signatures->matchesCategory( $ua, UserAgentSignatures::CATEGORY_AI_CRAWLER ) ) {
			if ( null !== $this->ai_crawler_ips->find( $client_ip ) ) {
				return Category::VERIFIED_AI_CRAWLER;
			}
			if ( null !== $this->ai_rdns_verifier && $this->ai_rdns_verifier->verifyAgainstUa( $client_ip, $ua ) ) {
				return Category::VERIFIED_AI_CRAWLER;
			}
			if ( $this->isClaudeBot( $ua ) && 'aws' === $this->datacenter->provider( $client_ip ) ) {
				return Category::VERIFIED_AI_CRAWLER;
			}
			return Category::UNVERIFIED_BOT;
		}

		// Empty / whitespace-only UA is a strong bot signal: well-behaved
		// HTTP clients identify themselves, including most CLI tools
		// (curl, wget) and headless browsers. Empty-UA traffic from any
		// IP is overwhelmingly automated. Wordfence's reference design
		// treats it as "always crawler"; we land it as UNVERIFIED_BOT
		// (BALANCED preset → 2 req/min) rather than HUMAN. Allowlist
		// matchers run BEFORE classify() in Pipeline::runInner, so
		// wp-cron loopbacks, monitoring services with documented
		// empty-UA quirks, and similar internals stay unaffected.
		if ( '' === trim( $ua ) ) {
			return Category::UNVERIFIED_BOT;
		}

		if ( $this->datacenter->isDatacenter( $client_ip ) ) {
			$anomalies = HeaderAnomalyScorer::scoreFromNormalised( $normalised, $server_protocol );
			if ( $anomalies >= self::UNKNOWN_AUTOMATED_MIN_ANOMALIES ) {
				return Category::UNKNOWN_AUTOMATED;
			}
		}

		return Category::HUMAN;
	}

	/**
	 * Check whether the UA identifies as ClaudeBot.
	 *
	 * @param string $ua User-Agent string.
	 * @return bool
	 */
	private function isClaudeBot( $ua ) {
		return 1 === preg_match( '/\bClaudeBot\b/i', $ua );
	}
}
