/**
 * RBAC Policy Evaluation Engine
 *
 * Evaluates access control policies based on:
 * - Role-based permissions
 * - Resource-based access control
 * - Trust tier requirements
 * - Time-based and conditional policies
 * - Tenant context isolation
 *
 * Integrates with TenantContext for multi-tenant authorization and
 * Trust-engine for trust-based access decisions.
 *
 * @packageDocumentation
 */
import { z } from 'zod';
import type { ID, TrustLevel } from '../../common/types.js';
import { type RoleDefinition, type RoleAssignment, type TimeRestriction } from './roles.js';
import { type PermissionCheckRequest, type PermissionCheckResult } from './permissions.js';
/**
 * Access control policy types
 */
export declare const PolicyTypes: {
    /** Role-based permission check */
    readonly ROLE_BASED: "role_based";
    /** Resource-based permission check */
    readonly RESOURCE_BASED: "resource_based";
    /** Trust-tier requirement */
    readonly TRUST_BASED: "trust_based";
    /** Time-based restriction */
    readonly TIME_BASED: "time_based";
    /** Conditional policy */
    readonly CONDITIONAL: "conditional";
    /** Composite (multiple policies) */
    readonly COMPOSITE: "composite";
};
export type PolicyType = (typeof PolicyTypes)[keyof typeof PolicyTypes];
/**
 * Policy evaluation effect
 */
export declare const PolicyEffects: {
    readonly ALLOW: "allow";
    readonly DENY: "deny";
    readonly INDETERMINATE: "indeterminate";
    readonly NOT_APPLICABLE: "not_applicable";
};
export type PolicyEffect = (typeof PolicyEffects)[keyof typeof PolicyEffects];
/**
 * Policy combining algorithm
 */
export declare const CombiningAlgorithms: {
    /** First deny wins */
    readonly DENY_OVERRIDES: "deny_overrides";
    /** First allow wins */
    readonly PERMIT_OVERRIDES: "permit_overrides";
    /** All must allow */
    readonly UNANIMOUS: "unanimous";
    /** First applicable wins */
    readonly FIRST_APPLICABLE: "first_applicable";
    /** Priority-based (highest priority wins) */
    readonly PRIORITY_BASED: "priority_based";
};
export type CombiningAlgorithm = (typeof CombiningAlgorithms)[keyof typeof CombiningAlgorithms];
/**
 * Access control policy definition
 */
export interface AccessPolicy {
    /** Unique policy identifier */
    id: ID;
    /** Policy name */
    name: string;
    /** Policy description */
    description?: string;
    /** Policy type */
    type: PolicyType;
    /** Policy priority (higher = more important) */
    priority: number;
    /** Effect when policy matches */
    effect: PolicyEffect;
    /** Target subjects (who the policy applies to) */
    target?: PolicyTarget;
    /** Conditions for policy application */
    conditions?: PolicyConditions;
    /** Required permissions for allow */
    requiredPermissions?: string[];
    /** Required roles for allow */
    requiredRoles?: string[];
    /** Required trust tier */
    requiredTrustTier?: TrustLevel;
    /** Resource patterns this policy applies to */
    resourcePatterns?: string[];
    /** Time restrictions */
    timeRestrictions?: TimeRestriction[];
    /** Child policies (for composite) */
    childPolicies?: AccessPolicy[];
    /** Combining algorithm for child policies */
    combiningAlgorithm?: CombiningAlgorithm;
    /** Whether policy is enabled */
    enabled: boolean;
    /** Tenant scope (if tenant-specific) */
    tenantId?: ID;
    /** Metadata */
    metadata?: Record<string, unknown>;
    /** Creation timestamp */
    createdAt: string;
    /** Last update timestamp */
    updatedAt: string;
}
/**
 * Policy target (who the policy applies to)
 */
export interface PolicyTarget {
    /** Subject IDs */
    subjectIds?: ID[];
    /** Subject types */
    subjectTypes?: ('user' | 'agent' | 'service')[];
    /** Role IDs */
    roleIds?: string[];
    /** Tenant IDs */
    tenantIds?: ID[];
    /** Exclude these subjects */
    excludeSubjectIds?: ID[];
}
/**
 * Policy conditions
 */
export interface PolicyConditions {
    /** IP address restrictions */
    ipAddresses?: string[];
    /** Time window */
    timeWindow?: TimeRestriction;
    /** Custom attribute conditions */
    attributes?: Record<string, unknown>;
    /** Expression-based condition */
    expression?: string;
}
/**
 * Policy evaluation context
 */
export interface PolicyEvaluationContext {
    /** Subject making the request */
    subject: {
        id: ID;
        type: 'user' | 'agent' | 'service';
        trustTier: TrustLevel;
        roles: string[];
        permissions: Set<string>;
        attributes?: Record<string, unknown>;
    };
    /** Resource being accessed */
    resource: {
        id?: ID;
        type: string;
        action: string;
        tenantId?: ID;
        attributes?: Record<string, unknown>;
    };
    /** Environment context */
    environment: {
        timestamp: Date;
        ipAddress?: string;
        userAgent?: string;
        tenantId?: ID;
        requestId?: ID;
    };
}
/**
 * Policy evaluation result
 */
export interface PolicyEvaluationResult {
    /** Final effect */
    effect: PolicyEffect;
    /** Whether access is permitted */
    permitted: boolean;
    /** Policies that were evaluated */
    evaluatedPolicies: EvaluatedPolicy[];
    /** Policy that determined the outcome */
    decidingPolicy?: EvaluatedPolicy;
    /** Reason for the decision */
    reason: string;
    /** Missing requirements (if denied) */
    missingRequirements?: {
        permissions?: string[];
        roles?: string[];
        trustTier?: TrustLevel;
    };
    /** Evaluation duration */
    durationMs: number;
    /** Evaluation timestamp */
    evaluatedAt: string;
}
/**
 * Individual policy evaluation
 */
export interface EvaluatedPolicy {
    /** Policy ID */
    policyId: ID;
    /** Policy name */
    policyName: string;
    /** Policy type */
    policyType: PolicyType;
    /** Evaluation effect */
    effect: PolicyEffect;
    /** Whether policy matched the target */
    matched: boolean;
    /** Evaluation reason */
    reason?: string;
    /** Evaluation duration */
    durationMs: number;
}
export declare const policyTargetSchema: z.ZodObject<{
    subjectIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
    subjectTypes: z.ZodOptional<z.ZodArray<z.ZodEnum<["user", "agent", "service"]>, "many">>;
    roleIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
    tenantIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
    excludeSubjectIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
}, "strip", z.ZodTypeAny, {
    tenantIds?: string[];
    subjectIds?: string[];
    subjectTypes?: ("agent" | "user" | "service")[];
    roleIds?: string[];
    excludeSubjectIds?: string[];
}, {
    tenantIds?: string[];
    subjectIds?: string[];
    subjectTypes?: ("agent" | "user" | "service")[];
    roleIds?: string[];
    excludeSubjectIds?: string[];
}>;
export declare const policyConditionsSchema: z.ZodObject<{
    ipAddresses: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
    timeWindow: z.ZodOptional<z.ZodObject<{
        startTime: z.ZodString;
        endTime: z.ZodString;
        daysOfWeek: z.ZodArray<z.ZodNumber, "many">;
        timezone: z.ZodString;
    }, "strip", z.ZodTypeAny, {
        startTime?: string;
        endTime?: string;
        daysOfWeek?: number[];
        timezone?: string;
    }, {
        startTime?: string;
        endTime?: string;
        daysOfWeek?: number[];
        timezone?: string;
    }>>;
    attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
    expression: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
    expression?: string;
    attributes?: Record<string, unknown>;
    ipAddresses?: string[];
    timeWindow?: {
        startTime?: string;
        endTime?: string;
        daysOfWeek?: number[];
        timezone?: string;
    };
}, {
    expression?: string;
    attributes?: Record<string, unknown>;
    ipAddresses?: string[];
    timeWindow?: {
        startTime?: string;
        endTime?: string;
        daysOfWeek?: number[];
        timezone?: string;
    };
}>;
export declare const accessPolicySchema: z.ZodType<AccessPolicy>;
/**
 * RBAC Policy Engine options
 */
export interface PolicyEngineOptions {
    /** Default combining algorithm */
    defaultCombiningAlgorithm?: CombiningAlgorithm;
    /** Default effect when no policies match */
    defaultEffect?: PolicyEffect;
    /** Enable audit logging */
    enableAuditLogging?: boolean;
    /** Enable OpenTelemetry tracing */
    enableTracing?: boolean;
    /** Cache policy evaluations */
    enableCaching?: boolean;
    /** Cache TTL in milliseconds */
    cacheTtlMs?: number;
}
/**
 * RBAC Policy Evaluation Engine
 *
 * Provides comprehensive policy evaluation for access control decisions.
 * Supports multiple policy types and combining algorithms.
 */
export declare class RBACPolicyEngine {
    private policies;
    private roleRegistry;
    private permissionRegistry;
    private roleAssignments;
    private options;
    private auditLogger;
    private evaluationCache;
    constructor(options?: PolicyEngineOptions);
    /**
     * Initialize built-in roles and permissions
     */
    private initializeBuiltins;
    /**
     * Evaluate access request against all applicable policies
     */
    evaluate(context: PolicyEvaluationContext): Promise<PolicyEvaluationResult>;
    /**
     * Evaluate with OpenTelemetry tracing
     */
    evaluateWithTracing(context: PolicyEvaluationContext): Promise<PolicyEvaluationResult>;
    /**
     * Evaluate a single policy
     */
    private evaluatePolicy;
    /**
     * Evaluate role-based policy
     */
    private evaluateRoleBasedPolicy;
    /**
     * Evaluate resource-based policy
     */
    private evaluateResourceBasedPolicy;
    /**
     * Evaluate trust-based policy
     */
    private evaluateTrustBasedPolicy;
    /**
     * Evaluate time-based policy
     */
    private evaluateTimeBasedPolicy;
    /**
     * Evaluate conditional policy
     */
    private evaluateConditionalPolicy;
    /**
     * Evaluate composite policy (with child policies)
     */
    private evaluateCompositePolicy;
    /**
     * Check if a subject has specific permissions
     */
    checkPermissions(request: PermissionCheckRequest): Promise<PermissionCheckResult>;
    /**
     * Get all effective permissions for a subject
     */
    getSubjectPermissions(subjectId: ID, tenantId?: ID): Promise<Set<string>>;
    /**
     * Get all roles assigned to a subject
     */
    getSubjectRoles(subjectId: ID, tenantId?: ID): Promise<RoleDefinition[]>;
    /**
     * Add an access policy
     */
    addPolicy(policy: AccessPolicy): void;
    /**
     * Update an access policy
     */
    updatePolicy(policyId: ID, updates: Partial<AccessPolicy>): void;
    /**
     * Remove an access policy
     */
    removePolicy(policyId: ID): boolean;
    /**
     * Get a policy by ID
     */
    getPolicy(policyId: ID): AccessPolicy | undefined;
    /**
     * Get all policies
     */
    getAllPolicies(): AccessPolicy[];
    /**
     * Get enabled policies
     */
    getEnabledPolicies(): AccessPolicy[];
    /**
     * Add a custom role
     */
    addRole(role: RoleDefinition): void;
    /**
     * Update a custom role
     */
    updateRole(roleId: string, updates: Partial<RoleDefinition>): void;
    /**
     * Remove a custom role
     */
    removeRole(roleId: string): boolean;
    /**
     * Get a role by ID
     */
    getRole(roleId: string): RoleDefinition | undefined;
    /**
     * Get all roles
     */
    getAllRoles(): RoleDefinition[];
    /**
     * Assign a role to a subject
     */
    assignRole(assignment: RoleAssignment): void;
    /**
     * Revoke a role from a subject
     */
    revokeRole(subjectId: ID, roleId: string, tenantId?: ID): boolean;
    /**
     * Get role assignments for a subject
     */
    getRoleAssignments(subjectId: ID): RoleAssignment[];
    /**
     * Get applicable policies for a context
     */
    private getApplicablePolicies;
    /**
     * Check if a policy targets the subject
     */
    private policyTargetsSubject;
    /**
     * Check policy conditions
     */
    private checkConditions;
    /**
     * Check time restrictions
     */
    private checkTimeRestrictions;
    /**
     * Check a single time restriction
     */
    private checkTimeRestriction;
    /**
     * Combine policy effects using the specified algorithm
     */
    private combineEffects;
    /**
     * Match a pattern (supports wildcards)
     */
    private matchPattern;
    /**
     * Match IP address against a pattern.
     *
     * Supports:
     * - Wildcard '*' (matches any IP)
     * - CIDR notation for IPv4 (e.g., "192.168.1.0/24")
     * - CIDR notation for IPv6 (e.g., "fe80::/10")
     * - Exact string match as fallback
     *
     * When a CIDR pattern omits the prefix length, it defaults to
     * /32 for IPv4 and /128 for IPv6 (exact host match).
     */
    private matchIpAddress;
    /**
     * Determine whether `ip` falls within the network described by `cidr`.
     * `cidr` may be a bare IP (treated as /32 or /128) or "ip/prefix".
     */
    private static ipMatchesCidr;
    /** Returns true when the address string contains a colon (→ IPv6). */
    private static isIPv6;
    /**
     * Parse a dotted-quad IPv4 string into a 32-bit unsigned integer.
     * Returns null on invalid input.
     */
    private static ipv4ToNumber;
    /**
     * Expand an IPv6 address (handling :: shorthand) into a 128-element
     * bit array (array of 0 | 1).
     */
    private static ipv6ToBits;
    /**
     * Compare the first `prefixLen` bits of two 128-element bit arrays.
     */
    private static bitsMatchPrefix;
    /**
     * Get missing requirements for a denied request
     */
    private getMissingRequirements;
    /**
     * Build decision reason string
     */
    private buildDecisionReason;
    /**
     * Determine how permission was granted
     */
    private determineGrantSource;
    /**
     * Build cache key for evaluation context
     */
    private buildCacheKey;
    /**
     * Clear evaluation cache
     */
    private clearCache;
    /**
     * Log access decision for audit
     */
    private logAccessDecision;
    /**
     * Get engine statistics
     */
    getStats(): {
        totalPolicies: number;
        enabledPolicies: number;
        totalRoles: number;
        systemRoles: number;
        customRoles: number;
        totalAssignments: number;
        cacheSize: number;
    };
    /**
     * Destroy the engine and cleanup resources
     */
    destroy(): void;
}
/**
 * Create a new RBAC policy engine
 */
export declare function createRBACPolicyEngine(options?: PolicyEngineOptions): RBACPolicyEngine;
/**
 * Create a policy evaluation context
 */
export declare function createPolicyEvaluationContext(params: {
    subjectId: ID;
    subjectType: 'user' | 'agent' | 'service';
    trustTier: TrustLevel;
    roles: string[];
    permissions: string[];
    resourceType: string;
    resourceAction: string;
    resourceId?: ID;
    tenantId?: ID;
    ipAddress?: string;
    userAgent?: string;
    requestId?: ID;
    subjectAttributes?: Record<string, unknown>;
    resourceAttributes?: Record<string, unknown>;
}): PolicyEvaluationContext;
/**
 * Create an access policy
 */
export declare function createAccessPolicy(partial: Omit<AccessPolicy, 'createdAt' | 'updatedAt' | 'enabled'> & Partial<Pick<AccessPolicy, 'enabled'>>): AccessPolicy;
//# sourceMappingURL=policy-engine.d.ts.map