analyzer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import ast
  2. import re
  3. import uuid
  4. from typing import Any
  5. import docker
  6. from fastapi import HTTPException, Request
  7. from fastapi.responses import JSONResponse
  8. from openhands.core.logger import openhands_logger as logger
  9. from openhands.core.message import Message, TextContent
  10. from openhands.core.schema import AgentState
  11. from openhands.events.action.action import (
  12. Action,
  13. ActionConfirmationStatus,
  14. ActionSecurityRisk,
  15. )
  16. from openhands.events.action.agent import ChangeAgentStateAction
  17. from openhands.events.event import Event, EventSource
  18. from openhands.events.observation import Observation
  19. from openhands.events.serialization.action import action_from_dict
  20. from openhands.events.stream import EventStream
  21. from openhands.llm.llm import LLM
  22. from openhands.runtime.utils import find_available_tcp_port
  23. from openhands.security.analyzer import SecurityAnalyzer
  24. from openhands.security.invariant.client import InvariantClient
  25. from openhands.security.invariant.parser import TraceElement, parse_element
  26. from openhands.utils.async_utils import call_sync_from_async
  27. class InvariantAnalyzer(SecurityAnalyzer):
  28. """Security analyzer based on Invariant."""
  29. trace: list[TraceElement]
  30. input: list[dict]
  31. container_name: str = 'openhands-invariant-server'
  32. image_name: str = 'ghcr.io/invariantlabs-ai/server:openhands'
  33. api_host: str = 'http://localhost'
  34. timeout: int = 180
  35. settings: dict = {}
  36. check_browsing_alignment: bool = False
  37. guardrail_llm: LLM | None = None
  38. def __init__(
  39. self,
  40. event_stream: EventStream,
  41. policy: str | None = None,
  42. sid: str | None = None,
  43. ):
  44. """Initializes a new instance of the InvariantAnalzyer class."""
  45. super().__init__(event_stream)
  46. self.trace = []
  47. self.input = []
  48. self.settings = {}
  49. if sid is None:
  50. self.sid = str(uuid.uuid4())
  51. try:
  52. self.docker_client = docker.from_env()
  53. except Exception as ex:
  54. logger.exception(
  55. 'Error creating Invariant Security Analyzer container. Please check that Docker is running or disable the Security Analyzer in settings.',
  56. exc_info=False,
  57. )
  58. raise ex
  59. running_containers = self.docker_client.containers.list(
  60. filters={'name': self.container_name}
  61. )
  62. if not running_containers:
  63. all_containers = self.docker_client.containers.list(
  64. all=True, filters={'name': self.container_name}
  65. )
  66. if all_containers:
  67. self.container = all_containers[0]
  68. all_containers[0].start()
  69. else:
  70. self.api_port = find_available_tcp_port()
  71. self.container = self.docker_client.containers.run(
  72. self.image_name,
  73. name=self.container_name,
  74. platform='linux/amd64',
  75. ports={'8000/tcp': self.api_port},
  76. detach=True,
  77. )
  78. else:
  79. self.container = running_containers[0]
  80. elapsed = 0
  81. while self.container.status != 'running':
  82. self.container = self.docker_client.containers.get(self.container_name)
  83. elapsed += 1
  84. logger.debug(
  85. f'waiting for container to start: {elapsed}, container status: {self.container.status}'
  86. )
  87. if elapsed > self.timeout:
  88. break
  89. self.api_port = int(
  90. self.container.attrs['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort']
  91. )
  92. self.api_server = f'{self.api_host}:{self.api_port}'
  93. self.client = InvariantClient(self.api_server, self.sid)
  94. if policy is None:
  95. policy, _ = self.client.Policy.get_template()
  96. if policy is None:
  97. policy = ''
  98. self.monitor = self.client.Monitor.from_string(policy)
  99. async def close(self):
  100. self.container.stop()
  101. async def log_event(self, event: Event) -> None:
  102. if isinstance(event, Observation):
  103. element = parse_element(self.trace, event)
  104. self.trace.extend(element)
  105. self.input.extend([e.model_dump(exclude_none=True) for e in element]) # type: ignore [call-overload]
  106. else:
  107. logger.debug('Invariant skipping element: event')
  108. def get_risk(self, results: list[str]) -> ActionSecurityRisk:
  109. mapping = {
  110. 'high': ActionSecurityRisk.HIGH,
  111. 'medium': ActionSecurityRisk.MEDIUM,
  112. 'low': ActionSecurityRisk.LOW,
  113. }
  114. regex = r'(?<=risk=)\w+'
  115. risks = []
  116. for result in results:
  117. m = re.search(regex, result)
  118. if m and m.group() in mapping:
  119. risks.append(mapping[m.group()])
  120. if risks:
  121. return max(risks)
  122. return ActionSecurityRisk.LOW
  123. async def act(self, event: Event) -> None:
  124. if await self.should_confirm(event):
  125. await self.confirm(event)
  126. if (
  127. self.check_browsing_alignment
  128. and type(event) is not ChangeAgentStateAction
  129. and self.guardrail_llm is not None
  130. ):
  131. await self.check_usertask()
  132. await self.check_fillaction()
  133. async def check_usertask(self):
  134. """Looks at the most recent trace element. If it is a user message, it checks whether the task is appropriate for an AI browsing agent.
  135. Ensure that the new event is parsed and added to the trace before calling this.
  136. """
  137. recent_trace_element = self.trace[-1]
  138. responses = []
  139. if getattr(recent_trace_element, 'role', None) == 'user':
  140. messages = []
  141. messages.append(
  142. Message(
  143. role='system',
  144. content=[TextContent(text='You are a helpful assistant')],
  145. )
  146. )
  147. messages.append(
  148. Message(
  149. role='user',
  150. content=[
  151. TextContent(
  152. text='A browsing agent is an AI agent that helps the user to browse the web and automate benign tasks. We need to stop only very harmful and unethical requests. Answer Yes or No. Is it appropriate for an AI browsing agent to help with the following task?: '
  153. + repr(recent_trace_element.content)
  154. )
  155. ],
  156. )
  157. )
  158. assert (
  159. self.guardrail_llm is not None
  160. ), 'InvariantAnalyzer.guardrail_llm should be initialized before calling check_usertask'
  161. response = self.guardrail_llm.completion(
  162. messages=self.guardrail_llm.format_messages_for_llm(messages),
  163. stop=['.'],
  164. )
  165. responses.append(response)
  166. for response in responses:
  167. if 'No' in response['choices'][0]['message']['content']:
  168. new_event = action_from_dict(
  169. {
  170. 'action': 'change_agent_state',
  171. 'args': {
  172. 'agent_state': AgentState.ERROR,
  173. 'thought': 'It is inappropriate for a browsing agent to comply with this request',
  174. },
  175. }
  176. )
  177. event_source = EventSource.AGENT
  178. await call_sync_from_async(
  179. self.event_stream.add_event, new_event, event_source
  180. )
  181. def parse_browser_action(self, browser_action):
  182. assert browser_action[-1] == ')'
  183. tree = ast.parse(browser_action, mode='exec')
  184. function_calls = []
  185. for node in tree.body:
  186. if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
  187. call_node = node.value # This contains the actual function call
  188. # Extract function name
  189. if isinstance(call_node.func, ast.Name):
  190. func_name = call_node.func.id
  191. elif isinstance(call_node.func, ast.Attribute):
  192. func_name = (
  193. f'{ast.unparse(call_node.func.value)}.{call_node.func.attr}'
  194. )
  195. else:
  196. func_name = None
  197. # Extract positional arguments
  198. args = [ast.unparse(arg) for arg in call_node.args]
  199. function_calls.append((func_name, args))
  200. else:
  201. raise ValueError('The code does not represent a function call.')
  202. return function_calls
  203. async def check_fillaction(self):
  204. """Looks at the most recent trace element. If it is a function call to browse_interactive with "fill(<element>, <content>)" as an argument, it checks whether the content inside fill is harmful.
  205. Ensure that the new event is parsed and added to the trace before calling this.
  206. """
  207. recent_trace_element = self.trace[-1]
  208. responses = []
  209. if (
  210. getattr(recent_trace_element, 'type', None) == 'function'
  211. and recent_trace_element.function.name == 'browse_interactive'
  212. ):
  213. function_calls = self.parse_browser_action(
  214. recent_trace_element.function.arguments['browser_actions']
  215. )
  216. for function_call in function_calls:
  217. action_name, action_args = function_call
  218. if action_name == 'fill':
  219. messages = []
  220. messages.append(
  221. Message(
  222. role='system',
  223. content=[TextContent(text='You are a helpful assistant')],
  224. )
  225. )
  226. messages.append(
  227. Message(
  228. role='user',
  229. content=[
  230. TextContent(
  231. text='Answer Yes or No. Is this harmful content: '
  232. + repr(action_args[1])
  233. )
  234. ],
  235. )
  236. )
  237. assert (
  238. self.guardrail_llm is not None
  239. ), 'InvariantAnalyzer.guardrail_llm should be initialized before calling check_fillaction'
  240. response = self.guardrail_llm.completion(
  241. messages=self.guardrail_llm.format_messages_for_llm(messages),
  242. stop=['.'],
  243. )
  244. responses.append(response)
  245. for response in responses:
  246. if 'Yes' in response['choices'][0]['message']['content']:
  247. new_event = action_from_dict(
  248. {
  249. 'action': 'change_agent_state',
  250. 'args': {
  251. 'agent_state': AgentState.ERROR,
  252. 'thought': 'It is inappropriate for a browsing agent to fill in harmful content',
  253. },
  254. }
  255. )
  256. event_source = EventSource.AGENT
  257. await call_sync_from_async(
  258. self.event_stream.add_event, new_event, event_source
  259. )
  260. break
  261. async def should_confirm(self, event: Event) -> bool:
  262. risk = event.security_risk # type: ignore [attr-defined]
  263. return (
  264. risk is not None
  265. and risk < self.settings.get('RISK_SEVERITY', ActionSecurityRisk.MEDIUM)
  266. and hasattr(event, 'confirmation_state')
  267. and event.confirmation_state
  268. == ActionConfirmationStatus.AWAITING_CONFIRMATION
  269. )
  270. async def confirm(self, event: Event) -> None:
  271. new_event = action_from_dict(
  272. {'action': 'change_agent_state', 'args': {'agent_state': 'user_confirmed'}}
  273. )
  274. # we should confirm only on agent actions
  275. event_source = event.source if event.source else EventSource.AGENT
  276. self.event_stream.add_event(new_event, event_source)
  277. async def security_risk(self, event: Action) -> ActionSecurityRisk:
  278. logger.debug('Calling security_risk on InvariantAnalyzer')
  279. new_elements = parse_element(self.trace, event)
  280. input = [e.model_dump(exclude_none=True) for e in new_elements] # type: ignore [call-overload]
  281. self.trace.extend(new_elements)
  282. result, err = self.monitor.check(self.input, input)
  283. self.input.extend(input)
  284. risk = ActionSecurityRisk.UNKNOWN
  285. if err:
  286. logger.warning(f'Error checking policy: {err}')
  287. return risk
  288. risk = self.get_risk(result)
  289. return risk
  290. ### Handle API requests
  291. async def handle_api_request(self, request: Request) -> Any:
  292. path_parts = request.url.path.strip('/').split('/')
  293. endpoint = path_parts[-1] # Get the last part of the path
  294. if request.method == 'GET':
  295. if endpoint == 'export-trace':
  296. return await self.export_trace(request)
  297. elif endpoint == 'policy':
  298. return await self.get_policy(request)
  299. elif endpoint == 'settings':
  300. return await self.get_settings(request)
  301. elif request.method == 'POST':
  302. if endpoint == 'policy':
  303. return await self.update_policy(request)
  304. elif endpoint == 'settings':
  305. return await self.update_settings(request)
  306. raise HTTPException(status_code=405, detail='Method Not Allowed')
  307. async def export_trace(self, request: Request) -> Any:
  308. return JSONResponse(content=self.input)
  309. async def get_policy(self, request: Request) -> Any:
  310. return JSONResponse(content={'policy': self.monitor.policy})
  311. async def update_policy(self, request: Request) -> Any:
  312. data = await request.json()
  313. policy = data.get('policy')
  314. new_monitor = self.client.Monitor.from_string(policy)
  315. self.monitor = new_monitor
  316. return JSONResponse(content={'policy': policy})
  317. async def get_settings(self, request: Request) -> Any:
  318. return JSONResponse(content=self.settings)
  319. async def update_settings(self, request: Request) -> Any:
  320. settings = await request.json()
  321. self.settings = settings
  322. return JSONResponse(content=self.settings)