Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions backend/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ func envOr(key, fallback string) string {
return fallback
}

func parseDurationOr(s string, fallback time.Duration) time.Duration {
d, err := time.ParseDuration(s)
if err != nil {
return fallback
}
return d
}

func main() {
var (
port = flag.String("port", envOr("PORT", "8080"), "listen port (env PORT)")
Expand All @@ -36,7 +44,8 @@ func main() {
oidcClientID = flag.String("oidc-client-id", envOr("OIDC_CLIENT_ID", ""), "OIDC client ID (env OIDC_CLIENT_ID)")
staticDir = flag.String("static-dir", envOr("STATIC_DIR", ""), "frontend static assets directory (env STATIC_DIR)")
authDisabled = flag.Bool("auth-disabled", envOr("AUTH_DISABLED", "false") == "true", "skip OIDC validation — dev only (env AUTH_DISABLED)")
origins = flag.String("allowed-origins", envOr("ALLOWED_ORIGINS", "http://localhost:3000"), "comma-separated CORS origins (env ALLOWED_ORIGINS)")
origins = flag.String("allowed-origins", envOr("ALLOWED_ORIGINS", "http://localhost:3000"), "comma-separated CORS origins (env ALLOWED_ORIGINS)")
terminalIdleTimeout = flag.Duration("terminal-idle-timeout", parseDurationOr(envOr("TERMINAL_IDLE_TIMEOUT", "30m"), 30*time.Minute), "terminal session idle timeout (env TERMINAL_IDLE_TIMEOUT)")
)
flag.Parse()

Expand Down Expand Up @@ -90,7 +99,7 @@ func main() {
}
defer sdkClient.Close()

app := api.NewApp(sdkClient, authMiddleware, *staticDir, strings.Split(*origins, ","))
app := api.NewApp(sdkClient, authMiddleware, *staticDir, strings.Split(*origins, ","), *terminalIdleTimeout)

addr := ":" + *port
slog.Info("openshell-dashboard BFF listening",
Expand Down
1 change: 1 addition & 0 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.25.1
require (
github.com/coreos/go-oidc/v3 v3.20.0
github.com/go-chi/chi/v5 v5.3.1
github.com/gorilla/websocket v1.5.3
github.com/rhuss/openshell-sdk-go v0.3.1
google.golang.org/grpc v1.82.1
)
Expand Down
2 changes: 2 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rhuss/openshell-sdk-go v0.3.1 h1:OwHWofN59X//KKiAn5h7X95YUfqfmfJ1t1Yd2gPFF38=
Expand Down
22 changes: 17 additions & 5 deletions backend/internal/api/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
package api

import (
"context"
"net/http"
"os"
"path/filepath"
"strings"
"time"

"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
Expand All @@ -22,15 +24,21 @@ type App struct {
staticDir string
// allowedOrigins for CORS, e.g. the webpack dev server origin.
allowedOrigins []string
// terminalIdleTimeout is how long a terminal session can be idle before auto-disconnect.
terminalIdleTimeout time.Duration
// tickets stores short-lived, single-use WebSocket auth tickets.
tickets *ticketStore
}

// NewApp builds the application.
func NewApp(client openshell.ClientInterface, authMiddleware *auth.Middleware, staticDir string, allowedOrigins []string) *App {
func NewApp(client openshell.ClientInterface, authMiddleware *auth.Middleware, staticDir string, allowedOrigins []string, terminalIdleTimeout time.Duration) *App {
return &App{
client: client,
auth: authMiddleware,
staticDir: staticDir,
allowedOrigins: allowedOrigins,
client: client,
auth: authMiddleware,
staticDir: staticDir,
allowedOrigins: allowedOrigins,
terminalIdleTimeout: terminalIdleTimeout,
tickets: newTicketStore(context.Background()),
}
}

Expand All @@ -50,9 +58,13 @@ func (app *App) Routes() http.Handler {
// BFF liveness (does not call the gateway).
r.Get("/healthz", app.GetHealthz)

// Terminal uses ticket-based auth (not bearer tokens), so it sits outside the auth middleware group.
r.Get("/workspaces/{workspace}/sandboxes/{name}/terminal", app.Terminal)

r.Group(func(r chi.Router) {
r.Use(app.auth.Handler)

r.Post("/auth/ws-ticket", app.IssueTicket)
r.Get("/auth/userinfo", app.GetUserInfo)
r.Get("/auth/whoami", app.GetWhoAmI)
r.Get("/gateway", app.GetGateway)
Expand Down
235 changes: 235 additions & 0 deletions backend/internal/api/terminal_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
package api

import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"strconv"
"sync"
"time"

"github.com/go-chi/chi/v5"
"github.com/gorilla/websocket"

"github.com/Gkrumbach07/openshell-dashboard/backend/internal/auth"
)

type resizeMessage struct {
Type string `json:"type"`
Cols uint32 `json:"cols"`
Rows uint32 `json:"rows"`
}

func (app *App) wsUpgrader() websocket.Upgrader {
return websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
for _, allowed := range app.allowedOrigins {
if origin == allowed {
return true
}
}
return false
},
}
}

const (
maxCols uint32 = 500
maxRows uint32 = 200
wsReadLimit int64 = 64 * 1024
)

func (app *App) Terminal(w http.ResponseWriter, r *http.Request) {
workspace := chi.URLParam(r, "workspace")
name := chi.URLParam(r, "name")

ticketStr := r.URL.Query().Get("ticket")
if ticketStr == "" {
writeError(w, http.StatusUnauthorized, "unauthorized", "missing ticket")
return
}
jwt, claims, ok := app.tickets.validate(ticketStr)
if !ok {
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid, expired, or already-used ticket")
return
}

ctx := auth.WithToken(r.Context(), jwt)
ctx = auth.WithClaims(ctx, claims)

cols := uint32(80)
rows := uint32(24)
if c, err := strconv.ParseUint(r.URL.Query().Get("cols"), 10, 32); err == nil {
cols = uint32(c)
}
if ro, err := strconv.ParseUint(r.URL.Query().Get("rows"), 10, 32); err == nil {
rows = uint32(ro)
}
if cols > maxCols {
cols = maxCols
}
if rows > maxRows {
rows = maxRows
}
command := r.URL.Query().Get("command")
if command == "" {
command = "/bin/bash"
}

upgrader := app.wsUpgrader()
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
slog.Error("websocket upgrade failed", "error", err)
return
}
defer ws.Close()
ws.SetReadLimit(wsReadLimit)

var wsMu sync.Mutex
wsWrite := func(msgType int, data []byte) error {
wsMu.Lock()
defer wsMu.Unlock()
return ws.WriteMessage(msgType, data)
}
wsClose := func(code int, reason string) {
wsMu.Lock()
defer wsMu.Unlock()
ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(code, reason))
}

userEmail := ""
if claims != nil {
userEmail = claims.Email
}
startTime := time.Now()
slog.Info("terminal session opened",
"user", userEmail,
"workspace", workspace,
"sandbox", name,
"cols", cols,
"rows", rows,
"command", command,
)

var closeOnce sync.Once
logClose := func(reason string) {
closeOnce.Do(func() {
logSessionClose(userEmail, workspace, name, startTime, reason)
})
}

ctx, cancel := context.WithCancel(ctx)
defer cancel()

session, err := app.client.Exec().Interactive(ctx, workspace, name, []string{command}, cols, rows)
if err != nil {
slog.Error("interactive session failed", "error", err)
wsClose(websocket.CloseInternalServerErr, "failed to start shell")
logClose("error")
return
}
defer session.Close()

idleReset := make(chan struct{}, 1)
idleTimeout := app.terminalIdleTimeout
if idleTimeout == 0 {
idleTimeout = 30 * time.Minute
}

// session.Read -> WS
go func() {
defer cancel()
buf := make([]byte, 4096)
for {
n, err := session.Read(buf)
if n > 0 {
if writeErr := wsWrite(websocket.BinaryMessage, buf[:n]); writeErr != nil {
logClose("client_disconnect")
return
}
select {
case idleReset <- struct{}{}:
default:
}
}
if err != nil {
if err == io.EOF {
exitCode, _ := session.ExitCode()
wsClose(websocket.CloseNormalClosure, "exit:"+strconv.Itoa(exitCode))
logClose("exit")
} else {
wsClose(websocket.CloseGoingAway, "sandbox disconnected")
logClose("disconnect")
}
return
}
}
}()

// Idle timeout monitor
go func() {
timer := time.NewTimer(idleTimeout)
defer timer.Stop()
for {
select {
case <-timer.C:
wsClose(websocket.CloseNormalClosure, "idle timeout")
logClose("idle_timeout")
cancel()
return
case <-idleReset:
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer.Reset(idleTimeout)
case <-ctx.Done():
return
}
}
}()

// WS -> session.Write/Resize
for {
msgType, data, err := ws.ReadMessage()
if err != nil {
cancel()
logClose("client_disconnect")
return
}
select {
case idleReset <- struct{}{}:
default:
}
if msgType == websocket.TextMessage {
var resize resizeMessage
if json.Unmarshal(data, &resize) == nil && resize.Type == "resize" {
session.Resize(resize.Cols, resize.Rows)
continue
}
}
if _, err := session.Write(data); err != nil {
cancel()
logClose("write_error")
return
}
}
}

func logSessionClose(user, workspace, sandbox string, start time.Time, reason string) {
slog.Info("terminal session closed",
"user", user,
"workspace", workspace,
"sandbox", sandbox,
"duration", time.Since(start).Round(time.Millisecond).String(),
"reason", reason,
)
}
Loading