*/ private array $routes = array(); /** * Ability classifiers, in registration order. * * @var list */ private array $abilities = array(); /** * Fact providers, in registration order. * * @var list>, provide: callable, entity_types: list}> */ private array $facts = array(); /** * Every declared fact, by name. * * @var array> */ private array $catalog = array(); /** * Fact namespaces and the extension that owns each. * * @var array */ private array $namespaces = array(); /** * Labelers by entity type. * * @var array */ private array $labelers = array(); /** * Entity providers by entity type. * * @var array */ private array $providers = array(); /** * Replay providers by id. * * @var array */ private array $replays = array(); /** * Approval claims by entity type: the capability that decides the * type's holds, and the escalations that raise it. * * @var array>, capability: string}>}> */ private array $approvals = array(); /** * Batch expanders, in registration order (AF-25.11). * * @var list */ private array $batches = array(); /** * Extensions' default rules, in registration order (AF-25.10). * * @var list}> */ private array $defaults = array(); /** * Extensions' scan checks, by id. * * @var array */ private array $checks = array(); /** * Most default rules one registration may carry. */ public const MAX_DEFAULT_RULES = 64; /** * Decisions a default rule may make: restrictive ones only. */ private const DEFAULT_DECISIONS = array( 'DENY', 'REQUIRE_APPROVAL', 'EVALUATE_AI' ); /** * Capabilities a claim may not name: the meta capability the claims * feed, which would recurse, and those every logged-in user holds. */ private const BLANKET_CAPABILITIES = array( 'adaf_review_holds', 'read', 'exist' ); /** * A scan check id: a slug starting with a letter, so it never becomes an * integer array key. */ private const CHECK_PATTERN = '/^[a-z][a-z0-9_]{0,63}$/D'; /** * Capability shape a claim may name: what WordPress roles grant. */ private const CAPABILITY_PATTERN = '/^[a-z0-9_-]{1,64}$/D'; /** * Most escalations one claim may carry. */ private const MAX_ESCALATIONS = 16; /** * Classify REST actions whose route matches a pattern. * * The classifier receives the core's descriptor and returns a * Classification, or null to leave it to the next classifier. * * @param string $extension_id Registering extension. * @param string $pattern PCRE pattern matched against the route. * @param callable $classifier fn( ActionDescriptor ): ?Classification. */ public function add_route_classifier( string $extension_id, string $pattern, callable $classifier ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( ! self::is_pattern( $pattern ) ) { self::refuse( __METHOD__, __( 'The route pattern is not a valid regular expression.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $this->routes[] = array( 'id' => $extension_id, 'pattern' => $pattern, 'classify' => $classifier, ); return true; } /** * Expand a REST batch request into the writes it carries (AF-25.11). * * The expander receives the core's descriptor of the batch and returns * a list of `{method, route, input}` - one REST write per item - or null * when the request is not a batch after all. Each item is classified, * given facts and decided as that single request would be; the batch's * decision is the strictest of its own and its items'. * * @param string $extension_id Registering extension. * @param string $pattern PCRE pattern matched against the route. * @param callable $expander fn( ActionDescriptor ): ?list}>. */ public function add_batch_expander( string $extension_id, string $pattern, callable $expander ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( ! self::is_pattern( $pattern ) ) { self::refuse( __METHOD__, __( 'The route pattern is not a valid regular expression.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $this->batches[] = array( 'id' => $extension_id, 'pattern' => $pattern, 'expand' => $expander, ); return true; } /** * Classify abilities, and MCP tool calls naming them, by name prefix. * * @param string $extension_id Registering extension. * @param string $prefix Ability name prefix, such as "woocommerce/". * @param callable $classifier fn( ActionDescriptor ): ?Classification. */ public function add_ability_classifier( string $extension_id, string $prefix, callable $classifier ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( '' === $prefix ) { self::refuse( __METHOD__, __( 'The ability prefix is empty.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $this->abilities[] = array( 'id' => $extension_id, 'prefix' => $prefix, 'classify' => $classifier, ); return true; } /** * Compute facts about actions (AF-25.2, AF-25.3). * * The provider receives the classified descriptor and returns a map of * fact name => value, using only the names declared here. Each name is * `namespace.name`; a namespace has one owner. A declaration gives the * fact's type - number, money (integer minor units), string, bool or * list (of scalars) - and a label, and for money optionally its * `decimals` (0 to 4, default 2) and `currency` symbol, which the rule * builder uses to show amounts in currency units. The declarations are * the fact catalog: what rules may name, and what makes a rule dormant * when its extension is inactive. * * @param string $extension_id Registering extension. * @param array> $facts Declared facts, by name. * @param callable $provider fn( ActionDescriptor ): array. * @param list $entity_types Entity types it applies to; empty for all. */ public function add_fact_provider( string $extension_id, array $facts, callable $provider, array $entity_types = array() ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( array() === $facts ) { self::refuse( __METHOD__, __( 'A fact provider declares at least one fact.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $declared = array(); foreach ( $facts as $name => $entry ) { $checked = self::declaration( $name, $entry ); if ( is_string( $checked ) ) { self::refuse( __METHOD__, $checked ); return false; } $namespace = strstr( (string) $name, '.', true ); if ( isset( $this->catalog[ $name ] ) || ( isset( $this->namespaces[ $namespace ] ) && $this->namespaces[ $namespace ] !== $extension_id ) ) { self::refuse( __METHOD__, __( 'Another extension already owns this fact namespace.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $declared[ (string) $name ] = array( 'extension' => $extension_id ) + $checked; } foreach ( array_keys( $declared ) as $name ) { $this->namespaces[ (string) strstr( $name, '.', true ) ] = $extension_id; } $this->catalog = array_merge( $this->catalog, $declared ); $this->facts[] = array( 'id' => $extension_id, 'facts' => $declared, 'provide' => $provider, 'entity_types' => array_values( $entity_types ), ); return true; } /** * A fact declaration, normalized, or why it is refused. * * @param mixed $name Fact name. * @param mixed $entry Its declaration. * @return array{type: string, label: string, decimals?: int, currency?: string}|string */ private static function declaration( mixed $name, mixed $entry ): array|string { if ( ! is_string( $name ) || 1 !== preg_match( self::FACT_PATTERN, $name ) ) { return __( 'A fact name must be namespace.name in lowercase letters, digits and underscores.', 'agentic-daisy-ai-agent-firewall' ); } if ( ! is_array( $entry ) || ! isset( $entry['type'] ) || ! in_array( $entry['type'], self::FACT_TYPES, true ) ) { return __( 'A fact declares a type: number, money, string, bool or list.', 'agentic-daisy-ai-agent-firewall' ); } if ( ! isset( $entry['label'] ) || ! is_string( $entry['label'] ) || '' === trim( $entry['label'] ) ) { return __( 'A fact declares a label.', 'agentic-daisy-ai-agent-firewall' ); } $allowed = 'money' === $entry['type'] ? array( 'type', 'label', 'decimals', 'currency' ) : array( 'type', 'label' ); if ( array() !== array_diff( array_keys( $entry ), $allowed ) ) { return __( 'A fact declaration has a key it may not carry.', 'agentic-daisy-ai-agent-firewall' ); } $checked = array( 'type' => $entry['type'], 'label' => $entry['label'], ); if ( 'money' !== $entry['type'] ) { return $checked; } $decimals = $entry['decimals'] ?? 2; if ( ! is_int( $decimals ) || $decimals < 0 || $decimals > 4 ) { return __( 'A money fact has 0 to 4 decimals.', 'agentic-daisy-ai-agent-firewall' ); } $checked['decimals'] = $decimals; if ( isset( $entry['currency'] ) ) { if ( ! is_string( $entry['currency'] ) || '' === $entry['currency'] || strlen( $entry['currency'] ) > 8 ) { return __( 'A money fact\'s currency is a short symbol.', 'agentic-daisy-ai-agent-firewall' ); } $checked['currency'] = $entry['currency']; } return $checked; } /** * Name the targets of one entity type in the ledger. * * @param string $extension_id Registering extension. * @param string $entity_type Entity type it names. * @param callable $labeler fn( ActionDescriptor ): ?string. */ public function add_labeler( string $extension_id, string $entity_type, callable $labeler ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( 1 !== preg_match( self::ENTITY_PATTERN, $entity_type ) ) { self::refuse( __METHOD__, __( 'The entity type is not a valid slug.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $this->labelers[ $entity_type ] = $labeler; return true; } /** * Supply drift, snapshot, undo and reversibility for one entity type * (AF-25.4). One provider per type, and never a core type: the core * guards those itself, and a classification may not retarget them * either (AF-25.1). * * @param string $extension_id Registering extension. * @param string $entity_type Entity type it provides for. * @param EntityProvider $provider The provider. */ public function add_entity_provider( string $extension_id, string $entity_type, EntityProvider $provider ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( 1 !== preg_match( self::ENTITY_PATTERN, $entity_type ) || in_array( $entity_type, RuleSchema::CORE_ENTITY_TYPES, true ) ) { self::refuse( __METHOD__, __( 'An entity provider is for an extension\'s own entity type, not a core one.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } if ( isset( $this->providers[ $entity_type ] ) ) { self::refuse( __METHOD__, __( 'Another extension already provides for this entity type.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $this->providers[ $entity_type ] = $provider; return true; } /** * The provider for an entity type, if an extension registered one. * * @param string $entity_type Entity type. */ public function entity_provider( string $entity_type ): ?EntityProvider { return $this->providers[ $entity_type ] ?? null; } /** * Run writes held at an effect hook under this id (AF-25.5). The id is * what Api::hold_at_effect() is given and the hold records; one * provider per id. * * @param string $extension_id Registering extension. * @param string $provider_id A slug naming the provider. * @param ReplayProvider $provider The provider. */ public function add_replay_provider( string $extension_id, string $provider_id, ReplayProvider $provider ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( 1 !== preg_match( self::ID_PATTERN, $provider_id ) || isset( $this->replays[ $provider_id ] ) ) { self::refuse( __METHOD__, __( 'A replay provider id is a lowercase slug no other provider uses.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $this->replays[ $provider_id ] = $provider; return true; } /** * Add a check to the exposure scan (AF-25.14). It runs after the * built-in checks; its id, read once here, is a slug no built-in or * earlier check uses, and every finding it reports is filed under it. * * @param string $extension_id Registering extension. * @param Check $check The check. */ public function add_scan_check( string $extension_id, Check $check ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } try { $id = $check->id(); } catch ( \Throwable ) { $id = ''; } if ( 1 !== preg_match( self::CHECK_PATTERN, $id ) || isset( $this->checks[ $id ] ) || in_array( $id, CheckSet::BUILT_IN_IDS, true ) ) { self::refuse( __METHOD__, __( 'A scan check id is a lowercase slug, starting with a letter, that no other check uses.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $this->checks[ $id ] = new ExtensionCheck( $id, $check ); return true; } /** * Extensions' scan checks, in registration order. * * @return list */ public function scan_checks(): array { return array_values( $this->checks ); } /** * Name the capability that approves or rejects holds on one entity type * (AF-25.8, ADR-18 §8), in place of manage_options. Escalations raise it * by fact: the first whose conditions hold names the capability, and one * that cannot be evaluated raises it to manage_options. * * One claim per type, never `unknown`. A claim on a core type adds to * manage_options rather than replacing it: deciding then needs both. * * @param string $extension_id Registering extension. * @param string $entity_type Entity type claimed. * @param string $capability Capability that decides its holds. * @param list> $escalations {when: conditions, capability}, in order. */ public function add_approval_capability( string $extension_id, string $entity_type, string $capability, array $escalations = array() ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( 1 !== preg_match( self::ENTITY_PATTERN, $entity_type ) || 'unknown' === $entity_type ) { self::refuse( __METHOD__, __( 'An approval capability is claimed for a valid entity type other than unknown.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } if ( isset( $this->approvals[ $entity_type ] ) ) { self::refuse( __METHOD__, __( 'Another extension already claims approval for this entity type.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $valid = self::escalations( $escalations ); if ( ! self::claimable( $capability ) || null === $valid ) { self::refuse( __METHOD__, __( 'An approval capability is a capability slug, and each escalation is {when, capability} with valid conditions.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } $this->approvals[ $entity_type ] = array( 'extension' => $extension_id, 'capability' => $capability, 'escalations' => $valid, ); return true; } /** * Whether a claim may name this capability: a slug, and not one that * would recurse or that every logged-in user holds. * * @param string $capability Capability. */ private static function claimable( string $capability ): bool { return 1 === preg_match( self::CAPABILITY_PATTERN, $capability ) && ! in_array( $capability, self::BLANKET_CAPABILITIES, true ) && ! str_starts_with( $capability, 'level_' ); } /** * Escalations in their stored shape, or null when any is malformed. * * @param array $escalations Declared escalations. * @return list>, capability: string}>|null */ private static function escalations( array $escalations ): ?array { if ( ! array_is_list( $escalations ) || count( $escalations ) > self::MAX_ESCALATIONS ) { return null; } $valid = array(); foreach ( $escalations as $index => $escalation ) { $when = is_array( $escalation ) ? ( $escalation['when'] ?? null ) : null; $capability = is_array( $escalation ) ? ( $escalation['capability'] ?? null ) : null; if ( ! is_array( $escalation ) || 2 !== count( $escalation ) || ! is_array( $when ) || array() === $when || ! array_is_list( $when ) || ! is_string( $capability ) || ! self::claimable( $capability ) || array() !== Conditions::validate( $index, $when, null ) ) { return null; } /** @var list> $when Validated above. */ $valid[] = array( 'when' => $when, 'capability' => $capability, ); } return $valid; } /** * Who may decide a hold on this action: the capability, and whether * manage_options is needed as well. An unclaimed type is * manage_options alone. * * A claim applies to a type another extension's classifier gave the * action only if the claim is that extension's own: otherwise any * classifier could move a hold to a weaker approver. * * @param ActionDescriptor $action The held action, with its facts. * @param string|null $classified_by Extension whose classifier * retyped the action, if any. * @return array{capability: string, admin: bool} */ public function approval_requirement( ActionDescriptor $action, ?string $classified_by = null ): array { $claim = $this->approvals[ $action->entity_type ] ?? null; if ( null === $claim || ( null !== $classified_by && $classified_by !== $claim['extension'] ) ) { return array( 'capability' => 'manage_options', 'admin' => false, ); } $capability = $claim['capability']; foreach ( $claim['escalations'] as $escalation ) { $holds = Conditions::holds( $escalation['when'], $action->facts, $this->catalog ); if ( false !== $holds ) { // Unknown escalates as far as it can go. $capability = true === $holds ? $escalation['capability'] : 'manage_options'; break; } } return array( 'capability' => $capability, 'admin' => 'manage_options' !== $capability && in_array( $action->entity_type, RuleSchema::CORE_ENTITY_TYPES, true ), ); } /** * Whether an extension claims approval for this entity type. * * @param string $entity_type Entity type. */ public function claims( string $entity_type ): bool { return isset( $this->approvals[ $entity_type ] ); } /** * Every capability a claim can require, sorted: holding any one is what * lets a user into the Approvals page. * * @return list */ public function approval_capabilities(): array { $capabilities = array(); foreach ( $this->approvals as $claim ) { $capabilities[] = $claim['capability']; foreach ( $claim['escalations'] as $escalation ) { $capabilities[] = $escalation['capability']; } } $capabilities = array_values( array_unique( $capabilities ) ); sort( $capabilities, SORT_STRING ); return $capabilities; } /** * Ship default rules for the extension's own entity types (AF-25.10). * * They apply after every stored rule, network and site, and before the * built-in defaults: a store owner's explicit rule still overrides them. * Each rule is validated as a stored rule is, and may only restrict - * DENY, REQUIRE_APPROVAL or EVALUATE_AI - on a `match.entity_type` the * core does not own. Limits and budgets are refused: they count across * the ledger, so they belong in rules the owner can see and edit. One * bad rule refuses the whole call. * * @param string $extension_id Registering extension. * @param list> $rules Rules, in evaluation order. */ public function add_default_rules( string $extension_id, array $rules ): bool { if ( ! $this->admits( __METHOD__, $extension_id ) ) { return false; } if ( ! array_is_list( $rules ) || count( $rules ) > self::MAX_DEFAULT_RULES || array() !== PolicyEvaluator::validate_rules( $rules, null ) ) { self::refuse( __METHOD__, __( 'Default rules are a list of at most 64 valid rules.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } foreach ( $rules as $rule ) { if ( ! self::restrictive_default( $rule ) ) { self::refuse( __METHOD__, __( 'A default rule names an entity type the firewall does not own, decides DENY, REQUIRE_APPROVAL or EVALUATE_AI, and carries no limit or budget.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } } foreach ( $rules as $rule ) { $this->defaults[] = array( 'extension' => $extension_id, 'rule' => $rule, ); } return true; } /** * Whether a valid rule is one an extension may ship as a default. * * @param array $rule A rule validate_rules() accepted. */ private static function restrictive_default( array $rule ): bool { $type = $rule['match']['entity_type'] ?? null; return is_string( $type ) && ! in_array( $type, RuleSchema::CORE_ENTITY_TYPES, true ) && ! in_array( $type, RuleSchema::HIGH_RISK_ENTITIES, true ) && in_array( $rule['decision'] ?? null, self::DEFAULT_DECISIONS, true ) && ! array_key_exists( 'limit', $rule ) && ! array_key_exists( 'budget', $rule ); } /** * Extensions' default rules, in registration order. * * @return list}> */ public function default_rules(): array { return $this->defaults; } /** * The replay provider registered under an id, if any. * * @param string $provider_id Provider id. */ public function replay_provider( string $provider_id ): ?ReplayProvider { return $this->replays[ $provider_id ] ?? null; } /** * Close registration. Called by the firewall right after * `adaf_register_extensions` fires. */ public function seal(): void { $this->sealed = true; } /** * Whether registration has closed. */ public function sealed(): bool { return $this->sealed; } /** * Route classifiers, in registration order. * * @return list */ public function route_classifiers(): array { return $this->routes; } /** * Batch expanders, in registration order. * * @return list */ public function batch_expanders(): array { return $this->batches; } /** * Ability classifiers, in registration order. * * @return list */ public function ability_classifiers(): array { return $this->abilities; } /** * Fact providers, in registration order. * * @return list>, provide: callable, entity_types: list}> */ public function fact_providers(): array { return $this->facts; } /** * The fact catalog: every declared fact by name, with the extension that * declared it, its type and label, and money's precision. * * @return array> */ public function fact_catalog(): array { return $this->catalog; } /** * The labeler for an entity type, if an extension registered one. * * @param string $entity_type Entity type. */ public function labeler_for( string $entity_type ): ?callable { return $this->labelers[ $entity_type ] ?? null; } /** * Whether a registration may proceed: open, and from a valid id. * * @param string $method Registering method, for the notice. * @param string $extension_id Registering extension. */ private function admits( string $method, string $extension_id ): bool { if ( $this->sealed ) { self::refuse( $method, __( 'Extensions register on adaf_register_extensions; registration is closed.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } if ( 1 !== preg_match( self::ID_PATTERN, $extension_id ) ) { self::refuse( $method, __( 'The extension id must be a lowercase slug.', 'agentic-daisy-ai-agent-firewall' ) ); return false; } return true; } /** * Whether a string compiles as a PCRE pattern. An invalid one raises a * warning rather than an exception, so the warning is caught here, at * registration, instead of on a live request. * * @param string $pattern Candidate pattern. */ private static function is_pattern( string $pattern ): bool { $valid = true; // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler -- Scoped to one preg_match and restored at once. set_error_handler( static function () use ( &$valid ): bool { $valid = false; return true; } ); $matched = preg_match( $pattern, '' ); restore_error_handler(); return $valid && false !== $matched; } /** * Report a refused registration to the developer. * * @param string $method Registering method. * @param string $message Why. */ private static function refuse( string $method, string $message ): void { _doing_it_wrong( esc_html( $method ), esc_html( $message ), '2.1.0' ); } }