-
Notifications
You must be signed in to change notification settings - Fork 3
Remote command execution in microVM instances via vsock #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
1d4efc9
Add Dockerfile for initial ramdisk environment
sjmiller609 9aec6db
Exec API
sjmiller609 5012cc3
Fix exec test
sjmiller609 d0e84c2
Use websocket
sjmiller609 402fc87
Fix vsocket protocol handling and remove initrd versioning
sjmiller609 927fc3c
Fix comment
sjmiller609 f3a06e0
Fix non deterministic test result
sjmiller609 0c5c031
Improve error message from test
sjmiller609 ca4296e
More logging
sjmiller609 5b379dc
Switch to gRPC over vsock
sjmiller609 f30d5d9
Build before test
sjmiller609 e443a1f
Extract exec, avoid circular dependency
sjmiller609 1138b30
Add README
sjmiller609 9f0dd46
POC cli for exec
sjmiller609 c5eda8b
Improvements
sjmiller609 a521e9e
Must use GET
sjmiller609 919e165
chroot before running exec-agent, and wip to fix signal handling
sjmiller609 05b363f
Delete partially working: user, window resizing
sjmiller609 0d6ef47
Delete redundant README
sjmiller609 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/go-chi/chi/v5" | ||
| "github.com/gorilla/websocket" | ||
| "github.com/onkernel/hypeman/lib/exec" | ||
| "github.com/onkernel/hypeman/lib/instances" | ||
| "github.com/onkernel/hypeman/lib/logger" | ||
| ) | ||
|
|
||
| var upgrader = websocket.Upgrader{ | ||
| ReadBufferSize: 32 * 1024, | ||
| WriteBufferSize: 32 * 1024, | ||
| CheckOrigin: func(r *http.Request) bool { | ||
| // Allow all origins for now - can be tightened in production | ||
| return true | ||
| }, | ||
| } | ||
|
|
||
| // ExecRequest represents the JSON body for exec requests | ||
| type ExecRequest struct { | ||
| Command []string `json:"command"` | ||
| TTY bool `json:"tty"` | ||
| Env map[string]string `json:"env,omitempty"` | ||
| Cwd string `json:"cwd,omitempty"` | ||
| Timeout int32 `json:"timeout,omitempty"` // seconds | ||
| } | ||
|
|
||
| // ExecHandler handles exec requests via WebSocket for bidirectional streaming | ||
| func (s *ApiService) ExecHandler(w http.ResponseWriter, r *http.Request) { | ||
| ctx := r.Context() | ||
| log := logger.FromContext(ctx) | ||
| startTime := time.Now() | ||
|
|
||
| instanceID := chi.URLParam(r, "id") | ||
|
|
||
| // Get instance | ||
| inst, err := s.InstanceManager.GetInstance(ctx, instanceID) | ||
| if err != nil { | ||
| if err == instances.ErrNotFound { | ||
| http.Error(w, `{"code":"not_found","message":"instance not found"}`, http.StatusNotFound) | ||
| return | ||
| } | ||
| log.ErrorContext(ctx, "failed to get instance", "error", err) | ||
| http.Error(w, `{"code":"internal_error","message":"failed to get instance"}`, http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| if inst.State != instances.StateRunning { | ||
| http.Error(w, fmt.Sprintf(`{"code":"invalid_state","message":"instance must be running (current state: %s)"}`, inst.State), http.StatusConflict) | ||
| return | ||
| } | ||
|
|
||
| // Upgrade to WebSocket first | ||
| ws, err := upgrader.Upgrade(w, r, nil) | ||
| if err != nil { | ||
| log.ErrorContext(ctx, "websocket upgrade failed", "error", err) | ||
| return | ||
| } | ||
| defer ws.Close() | ||
|
|
||
| // Read JSON request from first WebSocket message | ||
| msgType, message, err := ws.ReadMessage() | ||
| if err != nil { | ||
| log.ErrorContext(ctx, "failed to read exec request", "error", err) | ||
| ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"error":"failed to read request: %v"}`, err))) | ||
| return | ||
| } | ||
|
|
||
| if msgType != websocket.TextMessage { | ||
| log.ErrorContext(ctx, "expected text message with JSON request", "type", msgType) | ||
| ws.WriteMessage(websocket.TextMessage, []byte(`{"error":"first message must be JSON text"}`)) | ||
| return | ||
| } | ||
|
|
||
| // Parse JSON request | ||
| var execReq ExecRequest | ||
| if err := json.Unmarshal(message, &execReq); err != nil { | ||
| log.ErrorContext(ctx, "invalid JSON request", "error", err) | ||
| ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"error":"invalid JSON: %v"}`, err))) | ||
| return | ||
| } | ||
|
|
||
| // Default command if not specified | ||
| if len(execReq.Command) == 0 { | ||
| execReq.Command = []string{"/bin/sh"} | ||
| } | ||
|
|
||
| // Get JWT subject for audit logging (if available) | ||
| subject := "unknown" | ||
| if claims, ok := r.Context().Value("claims").(map[string]interface{}); ok { | ||
| if sub, ok := claims["sub"].(string); ok { | ||
| subject = sub | ||
| } | ||
| } | ||
|
|
||
| // Audit log: exec session started | ||
| log.InfoContext(ctx, "exec session started", | ||
| "instance_id", instanceID, | ||
| "subject", subject, | ||
| "command", execReq.Command, | ||
| "tty", execReq.TTY, | ||
| "cwd", execReq.Cwd, | ||
| "timeout", execReq.Timeout, | ||
| ) | ||
|
|
||
| // Create WebSocket read/writer wrapper | ||
| wsConn := &wsReadWriter{ws: ws, ctx: ctx} | ||
|
|
||
| // Execute via vsock | ||
| exit, err := exec.ExecIntoInstance(ctx, inst.VsockSocket, exec.ExecOptions{ | ||
| Command: execReq.Command, | ||
| Stdin: wsConn, | ||
| Stdout: wsConn, | ||
| Stderr: wsConn, | ||
| TTY: execReq.TTY, | ||
| Env: execReq.Env, | ||
| Cwd: execReq.Cwd, | ||
| Timeout: execReq.Timeout, | ||
| }) | ||
|
|
||
| duration := time.Since(startTime) | ||
|
|
||
| if err != nil { | ||
| log.ErrorContext(ctx, "exec failed", | ||
| "error", err, | ||
| "instance_id", instanceID, | ||
| "subject", subject, | ||
| "duration_ms", duration.Milliseconds(), | ||
| ) | ||
| // Send error message over WebSocket before closing | ||
| ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("Error: %v", err))) | ||
| return | ||
| } | ||
|
|
||
| // Audit log: exec session ended | ||
| log.InfoContext(ctx, "exec session ended", | ||
| "instance_id", instanceID, | ||
| "subject", subject, | ||
| "exit_code", exit.Code, | ||
| "duration_ms", duration.Milliseconds(), | ||
| ) | ||
|
|
||
| // Send close frame with exit code in JSON | ||
| closeMsg := fmt.Sprintf(`{"exitCode":%d}`, exit.Code) | ||
| ws.WriteMessage(websocket.TextMessage, []byte(closeMsg)) | ||
| } | ||
|
|
||
| // wsReadWriter wraps a WebSocket connection to implement io.ReadWriter | ||
| type wsReadWriter struct { | ||
| ws *websocket.Conn | ||
| ctx context.Context | ||
| reader io.Reader | ||
| mu sync.Mutex | ||
| } | ||
|
|
||
| func (w *wsReadWriter) Read(p []byte) (n int, err error) { | ||
| w.mu.Lock() | ||
| defer w.mu.Unlock() | ||
|
|
||
| // If we have a pending reader, continue reading from it | ||
| if w.reader != nil { | ||
| n, err = w.reader.Read(p) | ||
| if err != io.EOF { | ||
| return n, err | ||
| } | ||
| // EOF means we finished this message, get next one | ||
| w.reader = nil | ||
| } | ||
|
|
||
| // Read next WebSocket message | ||
| messageType, data, err := w.ws.ReadMessage() | ||
| if err != nil { | ||
| return 0, err | ||
| } | ||
|
|
||
| // Only handle binary and text messages | ||
| if messageType != websocket.BinaryMessage && messageType != websocket.TextMessage { | ||
| return 0, fmt.Errorf("unexpected message type: %d", messageType) | ||
| } | ||
|
|
||
| // Create reader for this message | ||
| w.reader = bytes.NewReader(data) | ||
| return w.reader.Read(p) | ||
| } | ||
|
|
||
| func (w *wsReadWriter) Write(p []byte) (n int, err error) { | ||
| if err := w.ws.WriteMessage(websocket.BinaryMessage, p); err != nil { | ||
| return 0, err | ||
| } | ||
| return len(p), nil | ||
| } | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we have switched to https://github.com/coder/websocket in the API since it seems to be a little bit more modern (supports ctx) and more actively maintained
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok will look into that if maybe a good follow up