Skip to content

Commit

Permalink
Enable authentication for runtime environments (#4179)
Browse files Browse the repository at this point in the history
Co-authored-by: Xingyao Wang <[email protected]>
  • Loading branch information
rbren and xingyaoww authored Oct 3, 2024
1 parent 9641bfb commit 9c95d0f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
22 changes: 21 additions & 1 deletion openhands/runtime/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@
from pathlib import Path

import pexpect
from fastapi import FastAPI, HTTPException, Request, UploadFile
from fastapi import Depends, FastAPI, HTTPException, Request, UploadFile
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.security import APIKeyHeader
from pydantic import BaseModel
from starlette.exceptions import HTTPException as StarletteHTTPException
from uvicorn import run
Expand Down Expand Up @@ -63,6 +64,15 @@ class ActionRequest(BaseModel):
]
SOFT_TIMEOUT_SECONDS = 5

SESSION_API_KEY = os.environ.get('SESSION_API_KEY')
api_key_header = APIKeyHeader(name='X-Session-API-Key', auto_error=False)


def verify_api_key(api_key: str = Depends(api_key_header)):
if SESSION_API_KEY and api_key != SESSION_API_KEY:
raise HTTPException(status_code=403, detail='Invalid API Key')
return api_key


class RuntimeClient:
"""RuntimeClient is running inside docker sandbox.
Expand Down Expand Up @@ -609,6 +619,16 @@ async def one_request_at_a_time(request: Request, call_next):
response = await call_next(request)
return response

@app.middleware('http')
async def authenticate_requests(request: Request, call_next):
if request.url.path != '/alive' and request.url.path != '/server_info':
try:
verify_api_key(request.headers.get('X-Session-API-Key'))
except HTTPException as e:
return e
response = await call_next(request)
return response

@app.get('/server_info')
async def get_server_info():
assert client is not None
Expand Down
5 changes: 5 additions & 0 deletions openhands/runtime/remote/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ def __init__(
f'Sandbox started. Runtime ID: {self.runtime_id}, URL: {self.runtime_url}'
)

if 'session_api_key' in start_response:
self.session.headers.update(
{'X-Session-API-Key': start_response['session_api_key']}
)

# Initialize the eventstream and env vars
super().__init__(
config, event_stream, sid, plugins, env_vars, status_message_callback
Expand Down

0 comments on commit 9c95d0f

Please sign in to comment.