interactive: ids, limits, frames and the signed grant (rootfs plan 6)
Task 2 of rootfs apps Plan 6: the new package internal/interactive, the vocabulary the console door, the box side and the CLI share. Session ids (tty_ + 26 base32, runs' encoding), the grant key under the app's subtree, the limits (MaxFrame 64 KiB; RunMaxFrame 262,157 for the run relay of Task 16), Open/Status/End and their reasons, the binary frame protocol over x/net/websocket (kind byte first, a bound at both ends, text frames refused, NewServer accepts only carlos-interactive/1), and the signed grant in doorkey's wire shape under its own signature domain, with the box bearer's mint and constant-time match. go.mod unchanged (x/net v0.60.0).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+1,186
−0
internal/interactive/frames.go+159 −0internal/interactive/frames_test.go+286 −0internal/interactive/grant.go+147 −0internal/interactive/grant_test.go+220 −0internal/interactive/interactive.go+226 −0internal/interactive/interactive_test.go+148 −0
Intent
Attributed to this commit: 52.5 g CO₂e (6,884,672 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on rootfs-apps-6-interactive, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/interactive/frames.go b/internal/interactive/frames.go| new file mode 100644 |
| index 000000000..68a850652 |
| --- /dev/null |
| +++ b/internal/interactive/frames.go |
| @@ -0,0 +1,159 @@ |
| +package interactive |
| + |
| +import ( |
| + "context" |
| + "crypto/tls" |
| + "encoding/binary" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "slices" |
| + |
| + "golang.org/x/net/websocket" |
| +) |
| + |
| +// The frame kinds. Every frame is one binary WebSocket message: the kind |
| +// byte, then its payload. |
| +const ( |
| + KindData byte = 'd' // terminal bytes, either way |
| + KindResize byte = 'r' // ResizePayload, CLI to box |
| + KindAlive byte = 'k' // keepalive, empty, either way |
| + KindOpen byte = 'o' // an Open, CLI to console |
| + KindStatus byte = 's' // a Status, console to CLI |
| + KindEnd byte = 'x' // an End, the last frame |
| +) |
| + |
| +var ( |
| + // ErrFrameTooBig is SendFrame's refusal of a frame over its bound. The |
| + // receiving end refuses one with websocket.ErrFrameTooLarge. |
| + ErrFrameTooBig = errors.New("interactive: frame over the size limit") |
| + // ErrBadFrame is Receive's refusal of an empty or non-binary message. |
| + ErrBadFrame = errors.New("interactive: not a binary frame with a kind") |
| +) |
| + |
| +// Send sends one session frame, bounded by MaxFrame. |
| +func Send(ws *websocket.Conn, kind byte, payload []byte) error { |
| + return SendFrame(ws, kind, payload, MaxFrame) |
| +} |
| + |
| +// SendFrame sends kind and payload as one binary message, refusing with |
| +// ErrFrameTooBig, before writing anything, a frame whose kind byte and |
| +// payload together exceed maxFrame. |
| +func SendFrame(ws *websocket.Conn, kind byte, payload []byte, maxFrame int) error { |
| + if 1+len(payload) > maxFrame { |
| + return ErrFrameTooBig |
| + } |
| + msg := make([]byte, 1+len(payload)) |
| + msg[0] = kind |
| + copy(msg[1:], payload) |
| + return websocket.Message.Send(ws, msg) |
| +} |
| + |
| +// SendJSON sends v, JSON-encoded, as one session frame of kind. |
| +func SendJSON(ws *websocket.Conn, kind byte, v any) error { |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + return err |
| + } |
| + return Send(ws, kind, b) |
| +} |
| + |
| +// binaryOnly is websocket.Message's receive with the payload type kept: it |
| +// takes a binary message into a []byte and refuses a text one (and a |
| +// continuation, which no sender here writes) with ErrBadFrame. |
| +var binaryOnly = websocket.Codec{ |
| + Marshal: nil, // Receive only |
| + Unmarshal: func(data []byte, payloadType byte, v any) error { |
| + if payloadType != websocket.BinaryFrame { |
| + return ErrBadFrame |
| + } |
| + *(v.(*[]byte)) = data |
| + return nil |
| + }, |
| +} |
| + |
| +// Receive reads one frame. The bound is the connection's MaxPayloadBytes |
| +// (set by Dial, DialFrame and NewServer): a larger frame is |
| +// websocket.ErrFrameTooLarge. An empty message or a text message is |
| +// ErrBadFrame. |
| +func Receive(ws *websocket.Conn) (kind byte, payload []byte, err error) { |
| + var msg []byte |
| + if err := binaryOnly.Receive(ws, &msg); err != nil { |
| + return 0, nil, err |
| + } |
| + if len(msg) == 0 { |
| + return 0, nil, ErrBadFrame |
| + } |
| + return msg[0], msg[1:], nil |
| +} |
| + |
| +// ResizePayload is a KindResize payload: cols then rows, each a big-endian |
| +// uint16. |
| +func ResizePayload(cols, rows uint16) []byte { |
| + p := make([]byte, 4) |
| + binary.BigEndian.PutUint16(p[0:2], cols) |
| + binary.BigEndian.PutUint16(p[2:4], rows) |
| + return p |
| +} |
| + |
| +// ParseResize reads a KindResize payload. ok is false unless p is exactly 4 |
| +// bytes and both dimensions are in 1..1000. |
| +func ParseResize(p []byte) (cols, rows uint16, ok bool) { |
| + if len(p) != 4 { |
| + return 0, 0, false |
| + } |
| + cols = binary.BigEndian.Uint16(p[0:2]) |
| + rows = binary.BigEndian.Uint16(p[2:4]) |
| + if cols < 1 || cols > MaxCols || rows < 1 || rows > MaxRows { |
| + return 0, 0, false |
| + } |
| + return cols, rows, true |
| +} |
| + |
| +// NewServer is the WebSocket server every session door uses. Its handshake |
| +// accepts only a client that offers Subprotocol, and answers with it. It |
| +// does not check Origin, because every route behind it authenticates by |
| +// header. h starts with the connection bounded at MaxFrame; a run relay |
| +// handler raises ws.MaxPayloadBytes to RunMaxFrame itself. |
| +func NewServer(h func(*websocket.Conn)) websocket.Server { |
| + return websocket.Server{ |
| + Handshake: func(c *websocket.Config, _ *http.Request) error { |
| + if !slices.Contains(c.Protocol, Subprotocol) { |
| + return websocket.ErrBadWebSocketProtocol |
| + } |
| + c.Protocol = []string{Subprotocol} |
| + return nil |
| + }, |
| + Handler: func(ws *websocket.Conn) { |
| + ws.MaxPayloadBytes = MaxFrame |
| + h(ws) |
| + }, |
| + } |
| +} |
| + |
| +// Dial opens a session connection bounded at MaxFrame. |
| +func Dial(ctx context.Context, url, origin string, header http.Header) (*websocket.Conn, error) { |
| + return DialFrame(ctx, url, origin, header, MaxFrame) |
| +} |
| + |
| +// DialFrame opens a connection to url (ws or wss) offering Subprotocol, |
| +// with header sent on the upgrade request, receiving frames of at most |
| +// maxFrame bytes. TLS offers only http/1.1, since the upgrade is an |
| +// HTTP/1.1 request. |
| +func DialFrame(ctx context.Context, url, origin string, header http.Header, maxFrame int) (*websocket.Conn, error) { |
| + cfg, err := websocket.NewConfig(url, origin) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if header != nil { |
| + cfg.Header = header.Clone() |
| + } |
| + cfg.Protocol = []string{Subprotocol} |
| + cfg.TlsConfig = &tls.Config{NextProtos: []string{"http/1.1"}} |
| + ws, err := cfg.DialContext(ctx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + ws.MaxPayloadBytes = maxFrame |
| + return ws, nil |
| +} |
diff --git a/internal/interactive/frames_test.go b/internal/interactive/frames_test.go| new file mode 100644 |
| index 000000000..ccda9e616 |
| --- /dev/null |
| +++ b/internal/interactive/frames_test.go |
| @@ -0,0 +1,286 @@ |
| +package interactive |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/net/websocket" |
| + |
| + "github.com/carlosframework/platform/internal/runs" |
| +) |
| + |
| +const testOrigin = "http://127.0.0.1/" |
| + |
| +// echoServer serves NewServer at maxFrame, echoing every frame it receives |
| +// and sending websocket.ErrFrameTooLarge's text back as a KindEnd detail, |
| +// so a test can see the server refuse an oversized frame. |
| +func echoServer(t *testing.T, maxFrame int) *httptest.Server { |
| + t.Helper() |
| + srv := httptest.NewServer(NewServer(func(ws *websocket.Conn) { |
| + defer ws.Close() |
| + if ws.MaxPayloadBytes != MaxFrame { |
| + _ = SendJSON(ws, KindEnd, End{Reason: "wrong default", Exit: ws.MaxPayloadBytes}) |
| + return |
| + } |
| + ws.MaxPayloadBytes = maxFrame |
| + for { |
| + kind, payload, err := Receive(ws) |
| + switch { |
| + case errors.Is(err, websocket.ErrFrameTooLarge): |
| + _ = SendJSON(ws, KindEnd, End{Reason: EndRefused, Detail: "too large"}) |
| + continue |
| + case errors.Is(err, ErrBadFrame): |
| + _ = SendJSON(ws, KindEnd, End{Reason: EndRefused, Detail: "bad frame"}) |
| + continue |
| + case err != nil: |
| + return |
| + } |
| + if err := SendFrame(ws, kind, payload, maxFrame); err != nil { |
| + return |
| + } |
| + } |
| + })) |
| + t.Cleanup(srv.Close) |
| + return srv |
| +} |
| + |
| +func wsURL(t *testing.T, srv *httptest.Server) string { |
| + t.Helper() |
| + u, err := WebSocketURL(srv.URL + "/x") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return u |
| +} |
| + |
| +func dialT(t *testing.T, url string, maxFrame int) *websocket.Conn { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + ws, err := DialFrame(ctx, url, testOrigin, http.Header{HeaderToken: {"t"}}, maxFrame) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { ws.Close() }) |
| + _ = ws.SetDeadline(time.Now().Add(10 * time.Second)) |
| + return ws |
| +} |
| + |
| +func wantRefusal(t *testing.T, ws *websocket.Conn, detail string) { |
| + t.Helper() |
| + kind, payload, err := Receive(ws) |
| + if err != nil || kind != KindEnd || !bytes.Contains(payload, []byte(detail)) { |
| + t.Fatalf("Receive() = %q, %q, %v; want an End with %q", kind, payload, err, detail) |
| + } |
| +} |
| + |
| +func TestResizeRoundTrip(t *testing.T) { |
| + p := ResizePayload(120, 40) |
| + if len(p) != 4 { |
| + t.Fatalf("len = %d", len(p)) |
| + } |
| + if c, r, ok := ParseResize(p); c != 120 || r != 40 || !ok { |
| + t.Fatalf("ParseResize = %d, %d, %v", c, r, ok) |
| + } |
| + if _, _, ok := ParseResize(ResizePayload(1000, 1)); !ok { |
| + t.Error("1000x1 refused") |
| + } |
| + for name, p := range map[string][]byte{ |
| + "3 bytes": p[:3], |
| + "5 bytes": append(ResizePayload(80, 24), 0), |
| + "0x0": ResizePayload(0, 0), |
| + "cols 0": ResizePayload(0, 24), |
| + "1001 cols": ResizePayload(1001, 24), |
| + "1001 rows": ResizePayload(80, 1001), |
| + } { |
| + if _, _, ok := ParseResize(p); ok { |
| + t.Errorf("%s: ParseResize ok", name) |
| + } |
| + } |
| +} |
| + |
| +func TestFramesRoundTripAndRefuseOversize(t *testing.T) { |
| + srv := echoServer(t, MaxFrame) |
| + ws := dialT(t, wsURL(t, srv), MaxFrame) |
| + |
| + for _, f := range []struct { |
| + kind byte |
| + payload []byte |
| + }{ |
| + {KindData, []byte("ls -l\r")}, |
| + {KindResize, ResizePayload(120, 40)}, |
| + {KindAlive, nil}, |
| + {KindOpen, []byte(`{"schema":1}`)}, |
| + {KindStatus, []byte(`{"state":"started"}`)}, |
| + {KindEnd, []byte(`{"reason":"exited"}`)}, |
| + {KindData, bytes.Repeat([]byte{0xff}, MaxFrame-1)}, // exactly MaxFrame on the wire |
| + } { |
| + if err := Send(ws, f.kind, f.payload); err != nil { |
| + t.Fatalf("Send(%q): %v", f.kind, err) |
| + } |
| + kind, payload, err := Receive(ws) |
| + if err != nil || kind != f.kind || !bytes.Equal(payload, f.payload) { |
| + t.Fatalf("echo of %q (%d bytes) = %q (%d bytes), %v", f.kind, len(f.payload), kind, len(payload), err) |
| + } |
| + } |
| + |
| + if err := SendJSON(ws, KindStatus, Status{State: StateWaiting}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if kind, payload, err := Receive(ws); err != nil || kind != KindStatus || string(payload) != `{"state":"waiting"}` { |
| + t.Fatalf("SendJSON echo = %q, %q, %v", kind, payload, err) |
| + } |
| + |
| + // A frame of MaxFrame payload bytes is MaxFrame+1 on the wire: refused |
| + // before anything is written. |
| + if err := Send(ws, KindData, make([]byte, MaxFrame)); !errors.Is(err, ErrFrameTooBig) { |
| + t.Fatalf("Send of MaxFrame bytes = %v, want ErrFrameTooBig", err) |
| + } |
| + |
| + // A text message and an empty binary message are not frames. |
| + if err := websocket.Message.Send(ws, "d hello"); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantRefusal(t, ws, "bad frame") |
| + if err := websocket.Message.Send(ws, []byte{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantRefusal(t, ws, "bad frame") |
| + |
| + // A sender that ignores the bound: the receiver at MaxFrame refuses it, |
| + // and the connection still carries the next frame. |
| + if err := SendFrame(ws, KindData, make([]byte, MaxFrame), MaxFrame+1); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantRefusal(t, ws, "too large") |
| + if err := Send(ws, KindAlive, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if kind, _, err := Receive(ws); err != nil || kind != KindAlive { |
| + t.Fatalf("after an oversized frame: %q, %v", kind, err) |
| + } |
| +} |
| + |
| +func TestReceiveRefusesTextOnTheClient(t *testing.T) { |
| + srv := httptest.NewServer(NewServer(func(ws *websocket.Conn) { |
| + defer ws.Close() |
| + _ = websocket.Message.Send(ws, "x{}") |
| + _, _, _ = Receive(ws) |
| + })) |
| + t.Cleanup(srv.Close) |
| + ws := dialT(t, wsURL(t, srv), MaxFrame) |
| + if _, _, err := Receive(ws); !errors.Is(err, ErrBadFrame) { |
| + t.Fatalf("Receive of a text message = %v, want ErrBadFrame", err) |
| + } |
| +} |
| + |
| +func TestRunFramesCarryAFullChunk(t *testing.T) { |
| + full := make([]byte, RunChunkHeader+runs.ChunkBytes) // 262,156 |
| + if len(full) != 262156 { |
| + t.Fatalf("full payload is %d bytes", len(full)) |
| + } |
| + for i := range full { |
| + full[i] = byte(i * 7) |
| + } |
| + |
| + srv := echoServer(t, RunMaxFrame) |
| + ws := dialT(t, wsURL(t, srv), RunMaxFrame) |
| + if err := SendFrame(ws, KindData, full, RunMaxFrame); err != nil { |
| + t.Fatal(err) |
| + } |
| + kind, payload, err := Receive(ws) |
| + if err != nil || kind != KindData || !bytes.Equal(payload, full) { |
| + t.Fatalf("full chunk echo: %q, %d bytes, %v", kind, len(payload), err) |
| + } |
| + if err := SendFrame(ws, KindData, append(full, 0), RunMaxFrame); !errors.Is(err, ErrFrameTooBig) { |
| + t.Fatalf("one byte more = %v, want ErrFrameTooBig", err) |
| + } |
| + |
| + // The same full frame to a session receiver (MaxFrame) is refused there. |
| + small := echoServer(t, MaxFrame) |
| + ws2 := dialT(t, wsURL(t, small), MaxFrame) |
| + if err := SendFrame(ws2, KindData, full, RunMaxFrame); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantRefusal(t, ws2, "too large") |
| + |
| + // And a client dialled at MaxFrame refuses it from a RunMaxFrame server. |
| + ws3 := dialT(t, wsURL(t, srv), MaxFrame) |
| + if err := SendFrame(ws3, KindData, full, RunMaxFrame); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := Receive(ws3); !errors.Is(err, websocket.ErrFrameTooLarge) { |
| + t.Fatalf("MaxFrame client given a full run frame: %v, want websocket.ErrFrameTooLarge", err) |
| + } |
| +} |
| + |
| +func TestDialRefusesAnotherSubprotocol(t *testing.T) { |
| + other := httptest.NewServer(websocket.Server{ |
| + Handshake: func(c *websocket.Config, _ *http.Request) error { |
| + for _, p := range c.Protocol { |
| + if p == "x" { |
| + c.Protocol = []string{"x"} |
| + return nil |
| + } |
| + } |
| + return websocket.ErrBadWebSocketProtocol |
| + }, |
| + Handler: func(ws *websocket.Conn) { ws.Close() }, |
| + }) |
| + t.Cleanup(other.Close) |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + if ws, err := Dial(ctx, wsURL(t, other), testOrigin, nil); err == nil { |
| + ws.Close() |
| + t.Fatal("Dial to a server that wants subprotocol x succeeded") |
| + } |
| + |
| + // And NewServer refuses a client that does not offer Subprotocol. |
| + ours := echoServer(t, MaxFrame) |
| + cfg, err := websocket.NewConfig(wsURL(t, ours), testOrigin) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg.Protocol = []string{"x"} |
| + if ws, err := cfg.DialContext(ctx); err == nil { |
| + ws.Close() |
| + t.Fatal("NewServer accepted a client offering only x") |
| + } |
| + cfg.Protocol = nil |
| + if ws, err := cfg.DialContext(ctx); err == nil { |
| + ws.Close() |
| + t.Fatal("NewServer accepted a client offering no subprotocol") |
| + } |
| +} |
| + |
| +func TestDialSendsHeaders(t *testing.T) { |
| + got := make(chan string, 1) |
| + srv := httptest.NewServer(NewServer(func(ws *websocket.Conn) { |
| + got <- ws.Request().Header.Get(HeaderToken) + " " + ws.Config().Protocol[0] |
| + ws.Close() |
| + })) |
| + t.Cleanup(srv.Close) |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + ws, err := Dial(ctx, wsURL(t, srv), testOrigin, http.Header{HeaderToken: {"secret"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ws.Close() |
| + if ws.MaxPayloadBytes != MaxFrame { |
| + t.Errorf("Dial's MaxPayloadBytes = %d", ws.MaxPayloadBytes) |
| + } |
| + select { |
| + case s := <-got: |
| + if s != "secret "+Subprotocol { |
| + t.Fatalf("server saw %q", s) |
| + } |
| + case <-ctx.Done(): |
| + t.Fatal("handler never ran") |
| + } |
| +} |
diff --git a/internal/interactive/grant.go b/internal/interactive/grant.go| new file mode 100644 |
| index 000000000..ae6e26285 |
| --- /dev/null |
| +++ b/internal/interactive/grant.go |
| @@ -0,0 +1,147 @@ |
| +package interactive |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "net/url" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/controlname" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Grant is what the console writes to GrantKey to send the box that owns a |
| +// session's instance to the console's attach door. The console signs it, |
| +// and the box acts on it only once VerifyGrant has passed. |
| +type Grant struct { |
| + V int `json:"v"` // 1 |
| + ID string `json:"id"` |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| + Host string `json:"host"` |
| + Incarnation string `json:"incarnation"` |
| + Attach string `json:"attach"` // AttachURL(console origin, ID) |
| + Token string `json:"token"` // the box's bearer for the attach |
| + By string `json:"by"` |
| + IssuedAt time.Time `json:"issued_at"` |
| + PickupBy time.Time `json:"pickup_by"` |
| +} |
| + |
| +var ( |
| + ErrGrantSignature = errors.New("interactive: grant signature") |
| + ErrGrantShape = errors.New("interactive: grant shape") |
| + ErrGrantExpired = errors.New("interactive: grant past its pickup") |
| +) |
| + |
| +// grantDomain separates a grant's signature from every other record the |
| +// same key might sign (doorkey's "carlos door-keys v1\n", the channel |
| +// pointers), so no other signed object stands in for a grant. |
| +const grantDomain = "carlos-interactive-grant/1\n" |
| + |
| +// MaxGrantSkew is how far ahead of a verifier's clock a grant's IssuedAt |
| +// may be before VerifyGrant refuses it. |
| +const MaxGrantSkew = 2 * time.Minute |
| + |
| +// signedGrant is the wire form, doorkey's shape: the payload is the |
| +// base64 of the grant's JSON, and sig signs grantDomain + payload. |
| +type signedGrant struct { |
| + Payload string `json:"payload"` |
| + Sig string `json:"sig"` |
| +} |
| + |
| +// shape is every check on the grant itself, with no clock. |
| +func (g Grant) shape() error { |
| + if g.V != 1 || !ValidID(g.ID) || !release.ValidAccount(g.Account) || !release.ValidApp(g.App) || |
| + !controlname.ValidHostShape(g.Host) || g.Token == "" || |
| + g.IssuedAt.IsZero() || g.PickupBy.IsZero() || !g.PickupBy.After(g.IssuedAt) { |
| + return ErrGrantShape |
| + } |
| + // Attach must be an http(s) URL with a host whose path ends in the |
| + // door and this grant's own id, so a grant cannot point a box's bearer |
| + // anywhere else. |
| + u, err := url.Parse(g.Attach) |
| + if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || |
| + u.User != nil || u.RawQuery != "" || u.Fragment != "" || |
| + !strings.HasSuffix(g.Attach, AttachPathPrefix+g.ID) { |
| + return ErrGrantShape |
| + } |
| + return nil |
| +} |
| + |
| +// SignGrant produces the bucket object for g. It refuses a grant |
| +// VerifyGrant would refuse for its shape. |
| +func SignGrant(priv ed25519.PrivateKey, g Grant) ([]byte, error) { |
| + if len(priv) != ed25519.PrivateKeySize { |
| + return nil, errors.New("interactive: no signing key") |
| + } |
| + if err := g.shape(); err != nil { |
| + return nil, err |
| + } |
| + payload, err := json.Marshal(g) |
| + if err != nil { |
| + return nil, err |
| + } |
| + b64 := base64.StdEncoding.EncodeToString(payload) |
| + return json.Marshal(signedGrant{Payload: b64, |
| + Sig: base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(grantDomain+b64)))}) |
| +} |
| + |
| +// VerifyGrant is the box's read: the signature (ErrGrantSignature), the |
| +// shape and an IssuedAt no more than MaxGrantSkew ahead of now |
| +// (ErrGrantShape), and now not past PickupBy (ErrGrantExpired). |
| +func VerifyGrant(pub ed25519.PublicKey, wire []byte, now time.Time) (Grant, error) { |
| + if len(pub) != ed25519.PublicKeySize { |
| + return Grant{}, ErrGrantSignature |
| + } |
| + var w signedGrant |
| + if err := json.Unmarshal(wire, &w); err != nil { |
| + return Grant{}, ErrGrantSignature |
| + } |
| + sig, err := base64.StdEncoding.DecodeString(w.Sig) |
| + if err != nil || len(sig) != ed25519.SignatureSize || !ed25519.Verify(pub, []byte(grantDomain+w.Payload), sig) { |
| + return Grant{}, ErrGrantSignature |
| + } |
| + payload, err := base64.StdEncoding.DecodeString(w.Payload) |
| + if err != nil { |
| + return Grant{}, ErrGrantShape |
| + } |
| + var g Grant |
| + if err := json.Unmarshal(payload, &g); err != nil { |
| + return Grant{}, ErrGrantShape |
| + } |
| + if err := g.shape(); err != nil { |
| + return Grant{}, err |
| + } |
| + if g.IssuedAt.After(now.Add(MaxGrantSkew)) { |
| + return Grant{}, ErrGrantShape |
| + } |
| + if now.After(g.PickupBy) { |
| + return Grant{}, ErrGrantExpired |
| + } |
| + return g, nil |
| +} |
| + |
| +// MintToken mints a box bearer: 32 random bytes, base64url without |
| +// padding. The console keeps only hash, the SHA-256 of the token string, |
| +// and puts plain in the grant. |
| +func MintToken() (plain string, hash [32]byte, err error) { |
| + var b [32]byte |
| + if _, err := rand.Read(b[:]); err != nil { |
| + return "", [32]byte{}, err |
| + } |
| + plain = base64.RawURLEncoding.EncodeToString(b[:]) |
| + return plain, sha256.Sum256([]byte(plain)), nil |
| +} |
| + |
| +// TokenMatches reports, in constant time, whether plain is the token hash |
| +// was minted for. |
| +func TokenMatches(plain string, hash [32]byte) bool { |
| + got := sha256.Sum256([]byte(plain)) |
| + return subtle.ConstantTimeCompare(got[:], hash[:]) == 1 |
| +} |
diff --git a/internal/interactive/grant_test.go b/internal/interactive/grant_test.go| new file mode 100644 |
| index 000000000..4f39ad0af |
| --- /dev/null |
| +++ b/internal/interactive/grant_test.go |
| @@ -0,0 +1,220 @@ |
| +package interactive |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/doorkey" |
| +) |
| + |
| +func testKey(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) { |
| + t.Helper() |
| + pub, priv, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return pub, priv |
| +} |
| + |
| +var grantNow = time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) |
| + |
| +func testGrant() Grant { |
| + id := "tty_aaaaaaaaaaaaaaaaaaaaaaaaab" |
| + return Grant{ |
| + V: 1, ID: id, Account: "bah", App: "shop", Host: "shop-1.example.com", |
| + Incarnation: "inc-1", Attach: AttachURL("https://console.example.com", id), |
| + Token: "tok", By: "owner@example.com", |
| + IssuedAt: grantNow, PickupBy: grantNow.Add(PickupWindow), |
| + } |
| +} |
| + |
| +func TestGrantVerifies(t *testing.T) { |
| + pub, priv := testKey(t) |
| + g := testGrant() |
| + wire, err := SignGrant(priv, g) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := VerifyGrant(pub, wire, grantNow.Add(time.Second)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got != g { |
| + t.Fatalf("VerifyGrant = %+v, want %+v", got, g) |
| + } |
| + // Exactly at PickupBy is still in time; a box clock up to the skew |
| + // behind the console's still verifies. |
| + if _, err := VerifyGrant(pub, wire, g.PickupBy); err != nil { |
| + t.Errorf("at PickupBy: %v", err) |
| + } |
| + if _, err := VerifyGrant(pub, wire, grantNow.Add(-MaxGrantSkew)); err != nil { |
| + t.Errorf("issued %s ahead: %v", MaxGrantSkew, err) |
| + } |
| + // The wire form is doorkey's: payload is base64 JSON of the grant. |
| + var w struct{ Payload, Sig string } |
| + if err := json.Unmarshal(wire, &w); err != nil || w.Payload == "" || w.Sig == "" { |
| + t.Fatalf("wire = %s", wire) |
| + } |
| +} |
| + |
| +func TestGrantRefusesTamperWrongKeyAndExpiry(t *testing.T) { |
| + pub, priv := testKey(t) |
| + g := testGrant() |
| + wire, err := SignGrant(priv, g) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var w struct { |
| + Payload string `json:"payload"` |
| + Sig string `json:"sig"` |
| + } |
| + if err := json.Unmarshal(wire, &w); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, err := base64.StdEncoding.DecodeString(w.Payload) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := range raw { |
| + flipped := append([]byte(nil), raw...) |
| + flipped[i] ^= 0x01 |
| + tw, _ := json.Marshal(struct { |
| + Payload string `json:"payload"` |
| + Sig string `json:"sig"` |
| + }{base64.StdEncoding.EncodeToString(flipped), w.Sig}) |
| + if _, err := VerifyGrant(pub, tw, grantNow); !errors.Is(err, ErrGrantSignature) { |
| + t.Fatalf("payload byte %d flipped: %v, want ErrGrantSignature", i, err) |
| + } |
| + } |
| + |
| + otherPub, _ := testKey(t) |
| + if _, err := VerifyGrant(otherPub, wire, grantNow); !errors.Is(err, ErrGrantSignature) { |
| + t.Errorf("other key: %v, want ErrGrantSignature", err) |
| + } |
| + if _, err := VerifyGrant(nil, wire, grantNow); !errors.Is(err, ErrGrantSignature) { |
| + t.Errorf("no key: %v, want ErrGrantSignature", err) |
| + } |
| + if _, err := VerifyGrant(pub, []byte("not json"), grantNow); !errors.Is(err, ErrGrantSignature) { |
| + t.Errorf("garbage: %v, want ErrGrantSignature", err) |
| + } |
| + |
| + if _, err := VerifyGrant(pub, wire, g.PickupBy.Add(time.Nanosecond)); !errors.Is(err, ErrGrantExpired) { |
| + t.Errorf("past PickupBy: %v, want ErrGrantExpired", err) |
| + } |
| + if _, err := VerifyGrant(pub, wire, grantNow.Add(-MaxGrantSkew-time.Second)); !errors.Is(err, ErrGrantShape) { |
| + t.Errorf("issued in the future: %v, want ErrGrantShape", err) |
| + } |
| + |
| + // Shapes the signer itself refuses, and that VerifyGrant refuses even |
| + // when signed (signed here past SignGrant's check). |
| + bad := map[string]func(*Grant){ |
| + "evil attach": func(g *Grant) { g.Attach = "https://evil.example.com/x" }, |
| + "attach other id": func(g *Grant) { g.Attach = AttachURL("https://console.example.com", "tty_aaaaaaaaaaaaaaaaaaaaaaaaac") }, |
| + "attach ftp": func(g *Grant) { g.Attach = "ftp://console.example.com" + AttachPathPrefix + g.ID }, |
| + "attach no host": func(g *Grant) { g.Attach = "https://" + AttachPathPrefix + g.ID }, |
| + "attach query": func(g *Grant) { g.Attach = "https://evil.example.com/?u=" + AttachPathPrefix + g.ID }, |
| + "attach userinfo": func(g *Grant) { g.Attach = "https://console.example.com@evil.example.com" + AttachPathPrefix + g.ID }, |
| + "run id": func(g *Grant) { |
| + g.ID = "run_aaaaaaaaaaaaaaaaaaaaaaaaab" |
| + g.Attach = AttachURL("https://c.example.com", g.ID) |
| + }, |
| + "traversal id": func(g *Grant) { g.ID = "tty_../x"; g.Attach = AttachURL("https://c.example.com", g.ID) }, |
| + "bad host": func(g *Grant) { g.Host = "../etc" }, |
| + "empty host": func(g *Grant) { g.Host = "" }, |
| + "bad account": func(g *Grant) { g.Account = "../x" }, |
| + "bad app": func(g *Grant) { g.App = "" }, |
| + "v2": func(g *Grant) { g.V = 2 }, |
| + "no token": func(g *Grant) { g.Token = "" }, |
| + "pickup before issue": func(g *Grant) { g.PickupBy = g.IssuedAt }, |
| + "no issued": func(g *Grant) { g.IssuedAt = time.Time{} }, |
| + } |
| + for name, mut := range bad { |
| + bg := testGrant() |
| + mut(&bg) |
| + if _, err := SignGrant(priv, bg); !errors.Is(err, ErrGrantShape) { |
| + t.Errorf("%s: SignGrant = %v, want ErrGrantShape", name, err) |
| + } |
| + if _, err := VerifyGrant(pub, signUnchecked(t, priv, bg), grantNow); !errors.Is(err, ErrGrantShape) { |
| + t.Errorf("%s: VerifyGrant = %v, want ErrGrantShape", name, err) |
| + } |
| + } |
| +} |
| + |
| +// signUnchecked signs g as SignGrant does, without its shape check, so a |
| +// test can hand VerifyGrant a validly signed grant of a bad shape. |
| +func signUnchecked(t *testing.T, priv ed25519.PrivateKey, g Grant) []byte { |
| + t.Helper() |
| + payload, err := json.Marshal(g) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b64 := base64.StdEncoding.EncodeToString(payload) |
| + wire, err := json.Marshal(signedGrant{Payload: b64, |
| + Sig: base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(grantDomain+b64)))}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return wire |
| +} |
| + |
| +func TestADoorKeySignatureIsNotAGrant(t *testing.T) { |
| + pub, priv := testKey(t) |
| + _, entry, err := doorkey.NewToken("bah", "shop") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now().UTC() |
| + wire, err := doorkey.Sign(priv, doorkey.Record{V: 1, Account: "bah", App: "shop", Revision: 1, |
| + Keys: []doorkey.Entry{entry}, SignedAt: now, ExpiresAt: now.Add(doorkey.Lifetime)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := VerifyGrant(pub, wire, now); !errors.Is(err, ErrGrantSignature) { |
| + t.Fatalf("a door-key record under the same key: %v, want ErrGrantSignature", err) |
| + } |
| + |
| + // Nor does a grant's signature verify as a door-key record. |
| + gw, err := SignGrant(priv, testGrant()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := doorkey.Verify(pub, gw, grantNow); err == nil { |
| + t.Fatal("a grant verified as a door-key record") |
| + } |
| +} |
| + |
| +func TestTokenMatches(t *testing.T) { |
| + plain, hash, err := MintToken() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(plain) != 43 { |
| + t.Errorf("token is %d characters, want 43 (32 bytes, base64url)", len(plain)) |
| + } |
| + if b, err := base64.RawURLEncoding.DecodeString(plain); err != nil || len(b) != 32 { |
| + t.Errorf("token %q is not 32 bytes of base64url: %v", plain, err) |
| + } |
| + if !TokenMatches(plain, hash) { |
| + t.Fatal("the minted token does not match its hash") |
| + } |
| + other, otherHash, err := MintToken() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if other == plain || otherHash == hash { |
| + t.Fatal("two mints agree") |
| + } |
| + for _, bad := range []string{other, "", plain[:42], plain + "A"} { |
| + if TokenMatches(bad, hash) { |
| + t.Errorf("TokenMatches(%q) = true", bad) |
| + } |
| + } |
| + if TokenMatches(plain, [32]byte{}) { |
| + t.Error("matched the zero hash") |
| + } |
| +} |
diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go| new file mode 100644 |
| index 000000000..287edcba3 |
| --- /dev/null |
| +++ b/internal/interactive/interactive.go |
| @@ -0,0 +1,226 @@ |
| +// Package interactive is what the console, the box and the CLI share about |
| +// one interactive session (`carlos instances exec -it`, rootfs spec §5.10): |
| +// ids, the session's object under its app's subtree, the limits, the |
| +// messages that open and end a session, the WebSocket frame protocol |
| +// (frames.go) and the signed grant that sends a box to the console's attach |
| +// door (grant.go). Like package runs, it holds no policy beyond validation. |
| +package interactive |
| + |
| +import ( |
| + "crypto/rand" |
| + "encoding/base32" |
| + "errors" |
| + "io" |
| + "net/url" |
| + "regexp" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/runs" |
| +) |
| + |
| +const ( |
| + // Subprotocol is the WebSocket subprotocol every session connection |
| + // speaks; NewServer accepts no other. |
| + Subprotocol = "carlos-interactive/1" |
| + // MaxFrame bounds one session frame, kind byte included, at both ends. |
| + MaxFrame = 64 << 10 |
| + // RunChunkHeader is the header of a run relay's data frame: seq as a |
| + // big-endian uint64, the stream byte, then 3 reserved zero bytes. |
| + RunChunkHeader = 12 |
| + // RunMaxFrame is the run relay's frame bound (Task 16): the kind byte, |
| + // the header and one full output chunk, 262,157 bytes. Sessions keep |
| + // MaxFrame. |
| + RunMaxFrame = 1 + RunChunkHeader + runs.ChunkBytes |
| + |
| + KeepaliveEvery = 15 * time.Second |
| + KeepaliveLost = 45 * time.Second |
| + // PickupWindow is how long a granted session waits for its box to |
| + // attach: the run design's window. |
| + PickupWindow = runs.PickupWindow |
| + IdleTimeout = 30 * time.Minute |
| + // MaxDuration is the run design's maximum duration. |
| + MaxDuration = runs.MaxTimeout |
| + HangupGrace = 10 * time.Second |
| + OpenWait = 10 * time.Second |
| + |
| + DefaultTerm = "xterm-256color" |
| + DefaultCols, DefaultRows = 80, 24 |
| + MaxCols, MaxRows = 1000, 1000 |
| + |
| + // HeaderToken carries the box's bearer on the attach dial. |
| + HeaderToken = "X-Carlos-Session-Token" |
| + // AttachPathPrefix is the console's box door; a session's attach URL is |
| + // the console origin, this prefix and the session id. |
| + AttachPathPrefix = "/api/box/interactive/" |
| +) |
| + |
| +var idEnc = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding) |
| + |
| +var idShape = regexp.MustCompile(`^tty_[a-z2-7]{26}$`) |
| + |
| +// NewID mints a session id from r: "tty_" and 26 lowercase base32 |
| +// characters, the encoding of 16 random bytes (128 bits), as runs.NewID |
| +// does for a run. Production code mints with MintID; NewID takes a reader |
| +// only so a test can supply a fixed one. |
| +func NewID(r io.Reader) (string, error) { |
| + var b [16]byte |
| + if _, err := io.ReadFull(r, b[:]); err != nil { |
| + return "", err |
| + } |
| + return "tty_" + idEnc.EncodeToString(b[:]), nil |
| +} |
| + |
| +// MintID mints a session id from the operating system's cryptographic |
| +// random source. |
| +func MintID() (string, error) { return NewID(rand.Reader) } |
| + |
| +// ValidID reports whether id is a session id. Every id that passes is |
| +// exactly 30 bytes of [a-z2-7_], so it is one clean path element and one |
| +// clean URL path segment: no slash, no dot, never empty. |
| +func ValidID(id string) bool { return idShape.MatchString(id) } |
| + |
| +// Prefix is where an app's session grants live: under its own subtree, so |
| +// the owner gate maps onto them and app trash and purge sweep them. |
| +func Prefix(acct, app string) string { return release.AppPrefix(acct, app) + "interactive/" } |
| + |
| +// GrantKey is the object a session's signed grant is written to. It does |
| +// not check its arguments; callers validate acct, app and id first. |
| +func GrantKey(acct, app, id string) string { return Prefix(acct, app) + id + ".json" } |
| + |
| +// AttachURL is the console door a box dials for session id. origin is the |
| +// console's origin with no trailing slash. |
| +func AttachURL(origin, id string) string { return origin + AttachPathPrefix + id } |
| + |
| +// ErrNotHTTP is WebSocketURL's refusal of a URL that is not http or https. |
| +var ErrNotHTTP = errors.New("interactive: not an http or https URL") |
| + |
| +// WebSocketURL turns an http(s) URL into the ws(s) URL that dials it: |
| +// https becomes wss and http becomes ws. Any other scheme is refused. |
| +func WebSocketURL(httpURL string) (string, error) { |
| + u, err := url.Parse(httpURL) |
| + if err != nil { |
| + return "", err |
| + } |
| + switch u.Scheme { |
| + case "https": |
| + u.Scheme = "wss" |
| + case "http": |
| + u.Scheme = "ws" |
| + default: |
| + return "", ErrNotHTTP |
| + } |
| + if u.Host == "" { |
| + return "", ErrNotHTTP |
| + } |
| + return u.String(), nil |
| +} |
| + |
| +// Open is the CLI's first frame (KindOpen): what to run and the terminal |
| +// it runs in. Exactly one of Argv and Process names the command. |
| +type Open struct { |
| + Schema int `json:"schema"` // 1 |
| + Argv []string `json:"argv,omitempty"` |
| + Process string `json:"process,omitempty"` // "" or release.ProcessConsole |
| + Term string `json:"term"` |
| + Cols int `json:"cols"` |
| + Rows int `json:"rows"` |
| +} |
| + |
| +var ( |
| + ErrBadSchema = errors.New("interactive: unknown open schema") |
| + ErrNoCommand = errors.New("interactive: no command and no process") |
| + ErrProcessWithArgv = errors.New("interactive: both a command and a process") |
| + ErrBadProcess = errors.New("interactive: not the console process") |
| + ErrBadTerm = errors.New("interactive: not a terminal type") |
| + ErrBadSize = errors.New("interactive: terminal size outside 1 to 1000") |
| +) |
| + |
| +var termShape = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.+_-]{0,63}$`) |
| + |
| +// Normalized fills the defaults a CLI may leave out: DefaultTerm for an |
| +// empty Term, and 80x24 when either dimension is 0. |
| +func (o Open) Normalized() Open { |
| + if o.Term == "" { |
| + o.Term = DefaultTerm |
| + } |
| + if o.Cols == 0 || o.Rows == 0 { |
| + o.Cols, o.Rows = DefaultCols, DefaultRows |
| + } |
| + return o |
| +} |
| + |
| +// Check validates o as given; callers check o.Normalized(). An empty Term |
| +// or a 0 dimension is refused here, not defaulted. |
| +func (o Open) Check() error { |
| + if o.Schema != 1 { |
| + return ErrBadSchema |
| + } |
| + if o.Process != "" { |
| + if o.Process != release.ProcessConsole { |
| + return ErrBadProcess |
| + } |
| + if len(o.Argv) > 0 { |
| + return ErrProcessWithArgv |
| + } |
| + } else { |
| + if len(o.Argv) == 0 { |
| + return ErrNoCommand |
| + } |
| + if err := runs.CheckArgv(o.Argv); err != nil { |
| + return err |
| + } |
| + } |
| + if !termShape.MatchString(o.Term) { |
| + return ErrBadTerm |
| + } |
| + if o.Cols < 1 || o.Cols > MaxCols || o.Rows < 1 || o.Rows > MaxRows { |
| + return ErrBadSize |
| + } |
| + return nil |
| +} |
| + |
| +// Status is a KindStatus frame: how far the session has got before its |
| +// command runs. |
| +type Status struct { |
| + State string `json:"state"` |
| +} |
| + |
| +const ( |
| + StateWaiting = "waiting" |
| + StateStarting = "starting" |
| + StateStarted = "started" |
| +) |
| + |
| +// End is a KindEnd frame, the last frame of a session: why it ended and, |
| +// for EndExited, the command's exit status. |
| +type End struct { |
| + Reason string `json:"reason"` |
| + Exit int `json:"exit"` |
| + Refused string `json:"refused,omitempty"` |
| + Detail string `json:"detail,omitempty"` // a console sentence, a wake reason, a stop reason |
| + Started time.Time `json:"started,omitempty"` |
| + Ended time.Time `json:"ended"` |
| + Box string `json:"box,omitempty"` |
| +} |
| + |
| +// End reasons. |
| +const ( |
| + EndExited = "exited" |
| + EndIdle = "idle" |
| + EndLimit = "limit" |
| + EndHangup = "hangup" |
| + EndInterrupted = "interrupted" |
| + EndLost = "lost" |
| + EndExpired = "expired" |
| + EndCancelled = "cancelled" |
| + EndReplaced = "replaced" |
| + EndRefused = "refused" |
| +) |
| + |
| +// Why a session was refused, beside runs.Refused* (flat, claim, wake, |
| +// incarnation, import), which End.Refused also carries. |
| +const ( |
| + RefusedOff = "off" |
| + RefusedBusy = "busy" |
| +) |
diff --git a/internal/interactive/interactive_test.go b/internal/interactive/interactive_test.go| new file mode 100644 |
| index 000000000..b255b4b47 |
| --- /dev/null |
| +++ b/internal/interactive/interactive_test.go |
| @@ -0,0 +1,148 @@ |
| +package interactive |
| + |
| +import ( |
| + "bytes" |
| + "errors" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/runs" |
| +) |
| + |
| +func TestIDShape(t *testing.T) { |
| + id, err := NewID(bytes.NewReader(make([]byte, 16))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if id != "tty_aaaaaaaaaaaaaaaaaaaaaaaaaa" { |
| + t.Fatalf("NewID(zeros) = %q", id) |
| + } |
| + if !ValidID(id) { |
| + t.Fatalf("ValidID(%q) = false", id) |
| + } |
| + minted, err := MintID() |
| + if err != nil || !ValidID(minted) { |
| + t.Fatalf("MintID() = %q, %v", minted, err) |
| + } |
| + if _, err := NewID(bytes.NewReader(make([]byte, 15))); err == nil { |
| + t.Fatal("NewID with 15 bytes succeeded") |
| + } |
| + for _, bad := range []string{ |
| + "run_aaaaaaaaaaaaaaaaaaaaaaaaaa", |
| + "tty_", |
| + "tty_../x", |
| + "tty_" + strings.Repeat("a", 25), |
| + "tty_" + strings.Repeat("a", 27), |
| + "tty_AAAAAAAAAAAAAAAAAAAAAAAAAA", |
| + "tty_aaaaaaaaaaaaaaaaaaaaaaaaa1", |
| + "tty_aaaaaaaaaaaaaaaaaaaaaaaaaa\n", |
| + "", |
| + } { |
| + if ValidID(bad) { |
| + t.Errorf("ValidID(%q) = true", bad) |
| + } |
| + } |
| +} |
| + |
| +func TestKeysAndURLs(t *testing.T) { |
| + id := "tty_aaaaaaaaaaaaaaaaaaaaaaaaaa" |
| + if got, want := Prefix("bah", "shop"), release.AppPrefix("bah", "shop")+"interactive/"; got != want { |
| + t.Errorf("Prefix = %q, want %q", got, want) |
| + } |
| + if got, want := GrantKey("bah", "shop", id), release.AppPrefix("bah", "shop")+"interactive/"+id+".json"; got != want { |
| + t.Errorf("GrantKey = %q, want %q", got, want) |
| + } |
| + if got := AttachURL("https://console.example.com", id); got != "https://console.example.com/api/box/interactive/"+id { |
| + t.Errorf("AttachURL = %q", got) |
| + } |
| + for in, want := range map[string]string{ |
| + "https://console.example.com/api/cli/x": "wss://console.example.com/api/cli/x", |
| + "http://127.0.0.1:8080/a?b=c": "ws://127.0.0.1:8080/a?b=c", |
| + } { |
| + if got, err := WebSocketURL(in); err != nil || got != want { |
| + t.Errorf("WebSocketURL(%q) = %q, %v; want %q", in, got, err, want) |
| + } |
| + } |
| + for _, bad := range []string{"ftp://example.com/", "ws://example.com/", "example.com/x", "https:///x", "://"} { |
| + if got, err := WebSocketURL(bad); err == nil { |
| + t.Errorf("WebSocketURL(%q) = %q, want an error", bad, got) |
| + } |
| + } |
| +} |
| + |
| +func TestLimits(t *testing.T) { |
| + if RunMaxFrame != 262157 || RunChunkHeader+runs.ChunkBytes != 262156 { |
| + t.Fatalf("RunMaxFrame = %d", RunMaxFrame) |
| + } |
| + if MaxFrame != 65536 || PickupWindow != runs.PickupWindow || MaxDuration != runs.MaxTimeout { |
| + t.Fatal("limits drifted from the run design") |
| + } |
| +} |
| + |
| +func TestOpenCheck(t *testing.T) { |
| + ok := func(o Open) Open { |
| + if o.Schema == 0 { |
| + o.Schema = 1 |
| + } |
| + if o.Term == "" { |
| + o.Term = "xterm-256color" |
| + } |
| + if o.Cols == 0 { |
| + o.Cols = 120 |
| + } |
| + if o.Rows == 0 { |
| + o.Rows = 40 |
| + } |
| + return o |
| + } |
| + cases := []struct { |
| + name string |
| + o Open |
| + want error |
| + }{ |
| + {"no command", ok(Open{}), ErrNoCommand}, |
| + {"process with argv", ok(Open{Argv: []string{"sh"}, Process: release.ProcessConsole}), ErrProcessWithArgv}, |
| + {"web process", ok(Open{Process: "web"}), ErrBadProcess}, |
| + {"console process", ok(Open{Process: release.ProcessConsole}), nil}, |
| + {"argv", Open{Schema: 1, Argv: []string{"bin/rails", "console"}, Term: "xterm-256color", Cols: 120, Rows: 40}, nil}, |
| + {"schema 0", Open{Argv: []string{"sh"}, Term: "xterm", Cols: 80, Rows: 24}, ErrBadSchema}, |
| + {"schema 2", ok(Open{Schema: 2, Argv: []string{"sh"}}), ErrBadSchema}, |
| + {"term injection", ok(Open{Argv: []string{"sh"}, Term: "x;rm"}), ErrBadTerm}, |
| + {"term 65 bytes", ok(Open{Argv: []string{"sh"}, Term: strings.Repeat("x", 65)}), ErrBadTerm}, |
| + {"term 64 bytes", ok(Open{Argv: []string{"sh"}, Term: strings.Repeat("x", 64)}), nil}, |
| + {"term leading dash", ok(Open{Argv: []string{"sh"}, Term: "-x"}), ErrBadTerm}, |
| + {"cols 1001", ok(Open{Argv: []string{"sh"}, Cols: 1001}), ErrBadSize}, |
| + {"rows 1001", ok(Open{Argv: []string{"sh"}, Rows: 1001}), ErrBadSize}, |
| + {"cols negative", ok(Open{Argv: []string{"sh"}, Cols: -1}), ErrBadSize}, |
| + {"cols 1000 rows 1", ok(Open{Argv: []string{"sh"}, Cols: 1000, Rows: 1}), nil}, |
| + {"argv NUL", ok(Open{Argv: []string{"a\x00b"}}), runs.ErrArgNUL}, |
| + {"too many args", ok(Open{Argv: make([]string, runs.MaxArgs+1)}), runs.ErrTooManyArgs}, |
| + } |
| + for _, c := range cases { |
| + if err := c.o.Check(); !errors.Is(err, c.want) || (c.want == nil && err != nil) { |
| + t.Errorf("%s: Check() = %v, want %v", c.name, err, c.want) |
| + } |
| + } |
| + |
| + // Check refuses what Normalized would default; Normalized fills it. |
| + raw := Open{Schema: 1, Argv: []string{"sh"}} |
| + if err := raw.Check(); !errors.Is(err, ErrBadTerm) { |
| + t.Errorf("unnormalized Check() = %v, want ErrBadTerm", err) |
| + } |
| + raw.Term = "xterm" |
| + if err := raw.Check(); !errors.Is(err, ErrBadSize) { |
| + t.Errorf("Cols 0 Check() = %v, want ErrBadSize", err) |
| + } |
| + n := Open{Schema: 1, Argv: []string{"sh"}, Cols: 0, Rows: 50}.Normalized() |
| + if n.Term != DefaultTerm || n.Cols != 80 || n.Rows != 24 { |
| + t.Errorf("Normalized() = %+v", n) |
| + } |
| + if err := n.Check(); err != nil { |
| + t.Errorf("normalized Check() = %v", err) |
| + } |
| + kept := Open{Schema: 1, Argv: []string{"sh"}, Term: "vt100", Cols: 132, Rows: 50}.Normalized() |
| + if kept.Term != "vt100" || kept.Cols != 132 || kept.Rows != 50 { |
| + t.Errorf("Normalized() changed a full Open: %+v", kept) |
| + } |
| +} |