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
|
# File 'lib/shared_tools/tools/secure_tool_template.rb', line 66
def execute(user_input:, operation_type: 'read', timeout_seconds: 30)
execution_id = SecureRandom.uuid
start_time = Time.now
@logger.info("SecureToolTemplate#execute operation_type=#{operation_type} execution_id=#{execution_id}")
begin
validate_input_length(user_input)
sanitized_input = sanitize_input(user_input)
validate_permissions(operation_type)
check_rate_limits(execution_id)
log_tool_usage(execution_id, operation_type, sanitized_input)
timeout = validate_timeout(timeout_seconds)
result = execute_with_timeout(sanitized_input, operation_type, timeout)
sanitized_result = sanitize_output(result)
execution_time = (Time.now - start_time).round(3)
@logger.info("Operation completed successfully in #{execution_time}s")
{
success: true,
result: sanitized_result,
operation_type: operation_type,
execution_id: execution_id,
execution_time_seconds: execution_time,
executed_at: Time.now.iso8601
}
rescue SecurityError => e
@logger.error("Security violation: #{e.message}")
log_security_violation(e, execution_id, user_input)
{
success: false,
error: "Security violation: Access denied",
error_type: "security",
violation_logged: true,
execution_id: execution_id
}
rescue Timeout::Error => e
@logger.error("Operation timeout after #{timeout_seconds}s")
{
success: false,
error: "Operation exceeded timeout of #{timeout_seconds} seconds",
error_type: "timeout",
execution_id: execution_id
}
rescue ArgumentError => e
@logger.error("Validation error: #{e.message}")
{
success: false,
error: e.message,
error_type: "validation",
execution_id: execution_id
}
rescue => e
@logger.error("Tool execution failed: #{e.class} - #{e.message}")
{
success: false,
error: "Tool execution failed: #{e.message}",
error_type: e.class.name,
execution_id: execution_id
}
end
end
|