File size: 10,235 Bytes
6c7e606
d2a0c5e
 
6c7e606
189570d
 
d2a0c5e
189570d
6c7e606
6756da2
6c7e606
6756da2
d2a0c5e
 
72e3e77
 
d2a0c5e
 
6756da2
d2a0c5e
7cfde2b
189570d
6756da2
693bb03
 
6c7e606
d2a0c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e92bf6
7cfde2b
d2a0c5e
 
 
4e92bf6
 
d2a0c5e
 
4e92bf6
 
 
 
d2a0c5e
 
4e92bf6
 
d2a0c5e
 
4e92bf6
 
d2a0c5e
 
4e92bf6
 
 
 
d2a0c5e
6756da2
4e92bf6
 
d2a0c5e
 
4e92bf6
693bb03
 
 
 
4e92bf6
7cfde2b
 
 
4e92bf6
6756da2
 
 
 
 
 
 
 
4e92bf6
6756da2
 
 
 
 
d2a0c5e
6756da2
 
 
 
 
 
 
 
 
 
 
6c7e606
6756da2
 
 
 
 
 
6c7e606
d2a0c5e
 
 
 
 
6c7e606
6756da2
 
6c7e606
7cfde2b
4e92bf6
7cfde2b
 
 
 
6756da2
6c7e606
d2a0c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6756da2
d2a0c5e
 
6756da2
72e3e77
6756da2
693bb03
6756da2
72e3e77
6756da2
 
4e92bf6
6756da2
 
 
 
 
 
 
 
 
 
 
d2a0c5e
 
 
 
 
 
 
 
 
 
6c7e606
72e3e77
 
73939b2
 
d2a0c5e
73939b2
7cfde2b
 
 
 
 
 
d2a0c5e
7cfde2b
 
 
d2a0c5e
6c7e606
d2a0c5e
 
 
6756da2
d2a0c5e
6756da2
 
d2a0c5e
 
 
 
 
 
 
 
 
 
6756da2
d2a0c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
6756da2
7cfde2b
d2a0c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7cfde2b
d2a0c5e
 
6c7e606
6756da2
189570d
 
72e3e77
189570d
72e3e77
6756da2
693bb03
4e92bf6
 
 
693bb03
6756da2
72e3e77
aedd0be
7cfde2b
72e3e77
aedd0be
7cfde2b
 
6756da2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
ARF OSS v3.3.9 - Enterprise Lead Generation Engine (API Only)
Compatible with Pydantic V2
"""

import os
import sys
import json
import uuid
import hashlib
import logging
import sqlite3
import requests
import fcntl
from datetime import datetime
from typing import Dict, List, Optional, Any, Tuple
from contextlib import contextmanager
from enum import Enum

# FastAPI and Pydantic
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

# ============== INFRASTRUCTURE GOVERNANCE MODULE IMPORTS ==============
from infrastructure import (
    AzureInfrastructureSimulator,
    RegionAllowedPolicy,
    CostThresholdPolicy,
    ProvisionResourceIntent,
    DeployConfigurationIntent,
    GrantAccessIntent,
    ResourceType,
    Environment,
    RecommendedAction,
)
import yaml

# ============== SINGLE INSTANCE LOCK (per port) ==============
PORT = int(os.environ.get('PORT', 7860))
LOCK_FILE = f'/tmp/arf_app_{PORT}.lock'
try:
    lock_fd = open(LOCK_FILE, 'w')
    fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (IOError, OSError):
    print(f"Another instance is already running on port {PORT}. Exiting.")
    sys.exit(1)
# ==============================================================

# ============== CONFIGURATION (Pydantic V2) ==============
class Settings(BaseSettings):
    """Centralized configuration using Pydantic Settings V2"""
    
    # Hugging Face settings (aliased to match expected env vars)
    hf_space_id: str = Field(default='local', alias='SPACE_ID')
    hf_token: str = Field(default='', alias='HF_TOKEN')
    
    # Persistence - HF persistent storage
    data_dir: str = Field(
        default='/data' if os.path.exists('/data') else './data',
        alias='DATA_DIR'
    )
    
    # Lead generation (kept for reference, but UI removed)
    lead_email: str = "petter2025us@outlook.com"
    calendly_url: str = "https://calendly.com/petter2025us/arf-demo"
    
    # Webhook for lead alerts (set in HF secrets)
    slack_webhook: str = Field(default='', alias='SLACK_WEBHOOK')
    sendgrid_api_key: str = Field(default='', alias='SENDGRID_API_KEY')
    
    # Security
    api_key: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        alias='ARF_API_KEY'
    )
    
    # ARF defaults
    default_confidence_threshold: float = 0.9
    default_max_risk: str = "MEDIUM"
    
    # Pydantic V2 configuration
    model_config = SettingsConfigDict(
        populate_by_name=True,
        extra='ignore',
        env_prefix='',
        case_sensitive=False
    )

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        os.makedirs(self.data_dir, exist_ok=True)

settings = Settings()

# ============== LOGGING ==============
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(f'{settings.data_dir}/arf.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger('arf.oss')

# ============== ENUMS & TYPES (from original ARF) ==============
class RiskLevel(str, Enum):
    LOW = "LOW"
    MEDIUM = "MEDIUM"
    HIGH = "HIGH"
    CRITICAL = "CRITICAL"

class ExecutionLevel(str, Enum):
    AUTONOMOUS_LOW = "AUTONOMOUS_LOW"
    AUTONOMOUS_HIGH = "AUTONOMOUS_HIGH"
    SUPERVISED = "SUPERVISED"
    OPERATOR_REVIEW = "OPERATOR_REVIEW"

class LeadSignal(str, Enum):
    HIGH_RISK_BLOCKED = "high_risk_blocked"
    NOVEL_ACTION = "novel_action"
    POLICY_VIOLATION = "policy_violation"
    CONFIDENCE_LOW = "confidence_low"
    REPEATED_FAILURE = "repeated_failure"

# ============== ORIGINAL ARF COMPONENTS (unchanged) ==============
# ... (BayesianRiskEngine, PolicyEngine, RAGMemory classes as in your original file) ...
# To keep this message concise, I'm omitting the long original classes.
# They remain exactly as you had them. The full file would include them here.
# For brevity, I'll place a placeholder.

# ============== AUTHENTICATION ==============
security = HTTPBearer()

async def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
    if credentials.credentials != settings.api_key:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid API key"
        )
    return credentials.credentials

# ============== PYDANTIC MODELS (existing) ==============
# ... (ActionRequest, ConfigUpdateRequest, GateResult, EvaluationResponse, LeadSignalResponse) ...

# ============== NEW INFRASTRUCTURE MODELS ==============
class InfrastructureIntentRequest(BaseModel):
    intent_type: str  # "provision", "deploy", "grant"
    resource_type: Optional[str] = None
    region: Optional[str] = None
    size: Optional[str] = None
    environment: str = "PROD"
    requester: str
    # For deploy intent
    config_content: Optional[Dict[str, Any]] = None
    # For grant intent
    permission: Optional[str] = None
    target: Optional[str] = None

class InfrastructureEvaluationResponse(BaseModel):
    recommended_action: str  # "approve", "deny", "escalate", "defer"
    justification: str
    policy_violations: List[str]
    estimated_cost: Optional[float]
    risk_score: float
    confidence_score: float
    evaluation_details: Dict[str, Any]

# ============== FASTAPI APP ==============
app = FastAPI(
    title="ARF OSS Real Engine (API Only)",
    version="3.3.9",
    description="Real ARF OSS components for enterprise lead generation – backend API only.",
    contact={
        "name": "ARF Sales",
        "email": settings.lead_email,
    }
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize original ARF components
# ... (risk_engine, policy_engine, memory as in original) ...

# ============== INFRASTRUCTURE SIMULATOR INSTANCE (cached) ==============
# For simplicity, we use a default policy. In production, you might load from config.
_default_policy = RegionAllowedPolicy(regions={"eastus", "westeurope"}) & CostThresholdPolicy(500.0)
infra_simulator = AzureInfrastructureSimulator(
    policy=_default_policy,
    pricing_file="pricing.yml" if os.path.exists("pricing.yml") else None
)

# ============== API ENDPOINTS ==============

@app.get("/")
async def root():
    return {"service": "ARF OSS API", "version": "3.3.9", "status": "operational", "docs": "/docs"}

@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "version": "3.3.9",
        "edition": "OSS",
        "memory_entries": 0,  # simplified
        "timestamp": datetime.utcnow().isoformat()
    }

# ... existing ARF endpoints (get_config, update_config, evaluate_action, etc.) ...

# ============== NEW INFRASTRUCTURE EVALUATION ENDPOINT ==============
@app.post("/api/v1/infrastructure/evaluate", dependencies=[Depends(verify_api_key)], response_model=InfrastructureEvaluationResponse)
async def evaluate_infrastructure_intent(request: InfrastructureIntentRequest):
    """
    Evaluate an infrastructure change intent against policies, cost, and risk.
    """
    try:
        # Map request to appropriate intent type
        if request.intent_type == "provision":
            if not all([request.resource_type, request.region, request.size]):
                raise HTTPException(400, "Missing fields for provision intent")
            intent = ProvisionResourceIntent(
                resource_type=ResourceType(request.resource_type.lower()),
                region=request.region,
                size=request.size,
                requester=request.requester,
                environment=Environment(request.environment.lower())
            )
        elif request.intent_type == "deploy":
            intent = DeployConfigurationIntent(
                service_name=request.resource_type or "unknown",
                change_scope="canary",  # default; could be made configurable
                deployment_target=Environment(request.environment.lower()),
                configuration=request.config_content or {},
                requester=request.requester
            )
        elif request.intent_type == "grant":
            intent = GrantAccessIntent(
                principal=request.requester,
                permission_level=request.permission or "read",
                resource_scope=request.target or "/",
                justification="Requested via API"
            )
        else:
            raise HTTPException(400, f"Unknown intent type: {request.intent_type}")

        # Evaluate using the simulator
        healing_intent = infra_simulator.evaluate(intent)

        # Transform to response model
        return InfrastructureEvaluationResponse(
            recommended_action=healing_intent.recommended_action.value,
            justification=healing_intent.justification,
            policy_violations=healing_intent.policy_violations,
            estimated_cost=healing_intent.cost_projection,
            risk_score=healing_intent.risk_score or 0.0,
            confidence_score=healing_intent.confidence_score,
            evaluation_details=healing_intent.evaluation_details
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Infrastructure evaluation failed: {e}", exc_info=True)
        raise HTTPException(500, detail=str(e))

# ============== MAIN ENTRY POINT ==============
if __name__ == "__main__":
    import uvicorn

    port = int(os.environ.get('PORT', 7860))

    logger.info("="*60)
    logger.info("πŸš€ ARF OSS v3.3.9 (API Only) Starting")
    logger.info(f"πŸ“Š Data directory: {settings.data_dir}")
    logger.info(f"πŸ“§ Lead email: {settings.lead_email}")
    logger.info(f"πŸ”‘ API Key: {settings.api_key[:8]}... (set in HF secrets)")
    logger.info(f"🌐 Serving API at: http://0.0.0.0:{port}")
    logger.info("="*60)

    uvicorn.run(
        "hf_demo:app",
        host="0.0.0.0",
        port=port,
        log_level="info",
        reload=False
    )