Add Remote relay library and secure settings storage
Add bounded NVDA-v2 framing, TLS transport, peer validation, speech and Braille decoding, and private transport fixtures. Store settings and explicitly remembered endpoint-bound keys using owner-only atomic files. Include the implementation plan and status records. Remote remains a source library without an installable package or desktop integration.
This commit is contained in:
1 parent
bc305993b8
commit
63e84e9ac7
20 files changed
+3984
No files matched your search
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
type gesture struct {
|
||||
action string // Empty means unsupported; never dispatch the wire script name.
|
||||
index int
|
||||
}
|
||||
|
||||
func decodeGesture(f fields) (gesture, error) {
|
||||
var g gesture
|
||||
var path []string
|
||||
if f.optional("scriptPath", &path) != nil {
|
||||
return g, errProtocol
|
||||
}
|
||||
if len(path) != 0 && len(path) != 3 {
|
||||
return g, errProtocol
|
||||
}
|
||||
for _, part := range path {
|
||||
if len(part) == 0 || !boundedText(part, 128) {
|
||||
return g, errProtocol
|
||||
}
|
||||
}
|
||||
var indexes []int
|
||||
if _, ok := f["cellIndexes"]; ok {
|
||||
var err error
|
||||
indexes, err = f.integers("cellIndexes", maxCells, 0, maxCells-1)
|
||||
if err != nil {
|
||||
return g, err
|
||||
}
|
||||
}
|
||||
index, hasLegacy := 0, false
|
||||
if _, hasLegacy = f["routingIndex"]; hasLegacy {
|
||||
var err error
|
||||
index, err = f.number("routingIndex", 0, maxCells-1, false)
|
||||
if err != nil {
|
||||
return g, err
|
||||
}
|
||||
}
|
||||
if hasLegacy && len(indexes) > 0 && (len(indexes) != 1 || indexes[0] != index) {
|
||||
return g, errProtocol
|
||||
}
|
||||
if len(path) != 3 || path[0] != "globalCommands" || path[1] != "GlobalCommands" {
|
||||
return g, nil
|
||||
}
|
||||
switch path[2] {
|
||||
case "braille_scrollBack":
|
||||
g.action = "pan-left"
|
||||
case "braille_scrollForward":
|
||||
g.action = "pan-right"
|
||||
case "braille_routeTo":
|
||||
if len(indexes) == 1 {
|
||||
index = indexes[0]
|
||||
} else if len(indexes) > 1 || !hasLegacy {
|
||||
return g, nil
|
||||
}
|
||||
g.action, g.index = "route", index
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Package remote implements the relay side of the Remote Tentacle. It has no
|
||||
// desktop access; reader integration must supply consent and effect ownership.
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
maxRelayFrame = 1 << 20 // Excludes the terminating LF.
|
||||
maxTextBytes = 8192
|
||||
maxCells = 4096
|
||||
maxSequence = 1024
|
||||
maxPeers = 16 // Parsing bound; session policy permits only one peer.
|
||||
)
|
||||
|
||||
// Errors deliberately contain no server-controlled text, credentials or output.
|
||||
var (
|
||||
errProtocol = errors.New("invalid remote relay message")
|
||||
errLimit = errors.New("remote relay limit exceeded")
|
||||
errPeer = errors.New("remote peer membership or origin changed")
|
||||
errState = errors.New("remote connection is not ready")
|
||||
errStale = errors.New("stale remote connection generation")
|
||||
)
|
||||
|
||||
type role string
|
||||
|
||||
const (
|
||||
controller role = "master"
|
||||
controlled role = "slave"
|
||||
)
|
||||
|
||||
func (r role) valid() bool { return r == controller || r == controlled }
|
||||
|
||||
type peer struct {
|
||||
ID int `json:"id"`
|
||||
Role role `json:"connection_type"`
|
||||
}
|
||||
|
||||
type message struct {
|
||||
kind string
|
||||
origin int // Zero denotes absent metadata, never a peer identity.
|
||||
payload any
|
||||
}
|
||||
|
||||
type membership struct {
|
||||
channel string
|
||||
peers []peer
|
||||
}
|
||||
|
||||
type keyTransition struct {
|
||||
VK int `json:"vk_code"`
|
||||
Extended bool `json:"extended"`
|
||||
Pressed bool `json:"pressed"`
|
||||
Scan *int `json:"scan_code,omitempty"`
|
||||
}
|
||||
|
||||
type brailleInfo struct {
|
||||
Name string `json:"name"`
|
||||
Cells int `json:"numCells"`
|
||||
}
|
||||
|
||||
// readFrame also rejects a final, unterminated fragment on EOF.
|
||||
func readFrame(r *bufio.Reader) ([]byte, error) {
|
||||
var frame []byte
|
||||
for {
|
||||
part, err := r.ReadSlice('\n')
|
||||
if len(frame)+len(part) > maxRelayFrame+1 {
|
||||
return nil, errLimit
|
||||
}
|
||||
frame = append(frame, part...)
|
||||
if err == nil {
|
||||
return frame[:len(frame)-1], nil
|
||||
}
|
||||
if errors.Is(err, bufio.ErrBufferFull) {
|
||||
continue
|
||||
}
|
||||
if errors.Is(err, io.EOF) && len(frame) != 0 {
|
||||
return nil, io.ErrUnexpectedEOF
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Validate before unmarshalling, including ignored fields. JSON object keys
|
||||
// must be unique even when escaped differently; every collection is bounded.
|
||||
func validateJSON(data []byte) error {
|
||||
if len(data) > maxRelayFrame {
|
||||
return errLimit
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return errProtocol
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(data))
|
||||
d.UseNumber()
|
||||
nodes := 0
|
||||
var walk func(int) error
|
||||
walk = func(depth int) error {
|
||||
nodes++
|
||||
if depth > 24 || nodes > 16384 {
|
||||
return errLimit
|
||||
}
|
||||
token, err := d.Token()
|
||||
if err != nil {
|
||||
return errProtocol
|
||||
}
|
||||
delim, composite := token.(json.Delim)
|
||||
if !composite {
|
||||
return nil
|
||||
}
|
||||
if delim != '[' && delim != '{' {
|
||||
return errProtocol
|
||||
}
|
||||
keys := make(map[string]bool)
|
||||
for count := 0; d.More(); count++ {
|
||||
if count >= maxCells {
|
||||
return errLimit
|
||||
}
|
||||
if delim == '{' {
|
||||
key, err := d.Token()
|
||||
name, ok := key.(string)
|
||||
if err != nil || !ok || keys[name] {
|
||||
return errProtocol
|
||||
}
|
||||
keys[name] = true
|
||||
}
|
||||
if err := walk(depth + 1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
end, err := d.Token()
|
||||
if err != nil || delim == '[' && end != json.Delim(']') || delim == '{' && end != json.Delim('}') {
|
||||
return errProtocol
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := walk(0); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := d.Token(); err != io.EOF {
|
||||
return errProtocol
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type fields map[string]json.RawMessage
|
||||
|
||||
func object(data []byte) (fields, error) {
|
||||
var f fields
|
||||
if json.Unmarshal(data, &f) != nil || f == nil {
|
||||
return nil, errProtocol
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (f fields) required(name string, dst any) error {
|
||||
data, ok := f[name]
|
||||
if !ok || bytes.Equal(data, []byte("null")) || json.Unmarshal(data, dst) != nil {
|
||||
return errProtocol
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f fields) optional(name string, dst any) error {
|
||||
if _, ok := f[name]; !ok {
|
||||
return nil
|
||||
}
|
||||
return f.required(name, dst)
|
||||
}
|
||||
|
||||
func (f fields) number(name string, min, max int, optional bool) (int, error) {
|
||||
var n int
|
||||
var err error
|
||||
if optional {
|
||||
err = f.optional(name, &n)
|
||||
} else {
|
||||
err = f.required(name, &n)
|
||||
}
|
||||
if err != nil || n < min || n > max {
|
||||
return 0, errProtocol
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func boundedText(s string, limit int) bool { return len(s) <= limit && utf8.ValidString(s) }
|
||||
|
||||
func (f fields) integers(name string, count, min, max int) ([]int, error) {
|
||||
var raw []json.RawMessage
|
||||
if f.required(name, &raw) != nil {
|
||||
return nil, errProtocol
|
||||
}
|
||||
if len(raw) > count {
|
||||
return nil, errLimit
|
||||
}
|
||||
values := make([]int, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
n, err := (fields{"value": item}).number("value", min, max, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values = append(values, n)
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func decodePeer(raw []byte) (peer, error) {
|
||||
f, err := object(raw)
|
||||
if err != nil {
|
||||
return peer{}, err
|
||||
}
|
||||
var p peer
|
||||
p.ID, err = f.number("id", 1, 2147483647, false)
|
||||
if err != nil || f.required("connection_type", &p.Role) != nil || !p.Role.valid() {
|
||||
return peer{}, errProtocol
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func decodeMessage(data []byte) (message, error) {
|
||||
if err := validateJSON(data); err != nil {
|
||||
return message{}, err
|
||||
}
|
||||
f, err := object(data)
|
||||
if err != nil {
|
||||
return message{}, err
|
||||
}
|
||||
var m message
|
||||
if f.required("type", &m.kind) != nil || len(m.kind) == 0 || len(m.kind) > 64 {
|
||||
return m, errProtocol
|
||||
}
|
||||
for _, c := range m.kind {
|
||||
if c < 33 || c > 126 {
|
||||
return m, errProtocol
|
||||
}
|
||||
}
|
||||
if _, ok := f["origin"]; ok {
|
||||
m.origin, err = f.number("origin", 1, 2147483647, false)
|
||||
if err != nil {
|
||||
return message{}, err
|
||||
}
|
||||
}
|
||||
switch m.kind {
|
||||
case "channel_joined":
|
||||
var v membership
|
||||
if f.required("channel", &v.channel) != nil || len(v.channel) == 0 || !boundedText(v.channel, 512) {
|
||||
return m, errProtocol
|
||||
}
|
||||
var clients []json.RawMessage
|
||||
if f.optional("clients", &clients) != nil || len(clients) > maxPeers {
|
||||
return m, errProtocol
|
||||
}
|
||||
ids := make(map[int]bool)
|
||||
for _, raw := range clients {
|
||||
p, err := decodePeer(raw)
|
||||
if err != nil || ids[p.ID] {
|
||||
return m, errProtocol
|
||||
}
|
||||
ids[p.ID] = true
|
||||
v.peers = append(v.peers, p)
|
||||
}
|
||||
// Legacy IDs alone cannot establish a peer's role. If both variants are
|
||||
// present, they must describe exactly the same membership.
|
||||
if _, ok := f["user_ids"]; ok {
|
||||
var legacy []int
|
||||
if f.required("user_ids", &legacy) != nil || len(legacy) != len(ids) {
|
||||
return m, errProtocol
|
||||
}
|
||||
for _, id := range legacy {
|
||||
if !ids[id] {
|
||||
return m, errProtocol
|
||||
}
|
||||
delete(ids, id)
|
||||
}
|
||||
}
|
||||
m.payload = v
|
||||
case "client_joined", "client_left":
|
||||
p, err := decodePeer(f["client"])
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
if _, ok := f["user_id"]; ok {
|
||||
id, err := f.number("user_id", 1, 2147483647, false)
|
||||
if err != nil || id != p.ID {
|
||||
return m, errProtocol
|
||||
}
|
||||
}
|
||||
m.payload = p
|
||||
case "speak":
|
||||
m.payload, err = decodeSpeech(f)
|
||||
case "cancel", "ping", "version_mismatch", "nvda_not_connected":
|
||||
case "pause_speech":
|
||||
var pause bool
|
||||
err = f.required("switch", &pause)
|
||||
m.payload = pause
|
||||
case "key":
|
||||
var k keyTransition
|
||||
k.VK, err = f.number("vk_code", 1, 255, false)
|
||||
if err != nil || f.required("extended", &k.Extended) != nil || f.required("pressed", &k.Pressed) != nil {
|
||||
return m, errProtocol
|
||||
}
|
||||
if _, ok := f["scan_code"]; ok {
|
||||
scan, err := f.number("scan_code", 0, 65535, false)
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
k.Scan = &scan
|
||||
}
|
||||
m.payload = k
|
||||
case "set_braille_info":
|
||||
// A controlled peer also sends this with no fields to request geometry.
|
||||
var v brailleInfo
|
||||
if f.optional("name", &v.Name) != nil || !boundedText(v.Name, 256) {
|
||||
return m, errProtocol
|
||||
}
|
||||
v.Cells, err = f.number("numCells", 0, maxCells, true)
|
||||
m.payload = v
|
||||
case "set_display_size":
|
||||
m.payload, err = f.integers("sizes", maxPeers, 0, maxCells)
|
||||
case "display":
|
||||
// []byte would encode as base64, not NVDA's integer array.
|
||||
m.payload, err = f.integers("cells", maxCells, 0, 255)
|
||||
case "braille_input":
|
||||
m.payload, err = decodeGesture(f)
|
||||
case "set_clipboard_text":
|
||||
var text string
|
||||
if f.required("text", &text) != nil {
|
||||
return m, errProtocol
|
||||
}
|
||||
if !boundedText(text, maxTextBytes) {
|
||||
return m, errLimit
|
||||
}
|
||||
m.payload = text
|
||||
case "motd":
|
||||
var text string
|
||||
var force bool
|
||||
if f.required("motd", &text) != nil || !boundedText(text, maxTextBytes) || f.optional("force_display", &force) != nil {
|
||||
return m, errProtocol
|
||||
}
|
||||
// Neither the text nor force_display may authorize a local UI action.
|
||||
case "error":
|
||||
var text string
|
||||
if f.required("message", &text) != nil || !boundedText(text, maxTextBytes) {
|
||||
return m, errProtocol
|
||||
}
|
||||
// Server text is untrusted and never becomes an error or UI instruction.
|
||||
default:
|
||||
// Optional extensions (including wave, tone, send_SAS and index) are
|
||||
// inert. Their JSON still passed all structural/resource checks.
|
||||
}
|
||||
return m, err
|
||||
}
|
||||
|
||||
// encodeMessage is for peer traffic only; the transport owns authentication.
|
||||
// It refuses origin metadata because the relay assigns that field.
|
||||
func encodeMessage(kind string, payload any) ([]byte, error) {
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, errProtocol
|
||||
}
|
||||
f, err := object(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, exists := f["origin"]; exists {
|
||||
return nil, errProtocol
|
||||
}
|
||||
if _, exists := f["type"]; exists {
|
||||
return nil, errProtocol
|
||||
}
|
||||
f["type"], _ = json.Marshal(kind)
|
||||
data, err = json.Marshal(f)
|
||||
if err != nil {
|
||||
return nil, errProtocol
|
||||
}
|
||||
if _, err = decodeMessage(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch kind {
|
||||
case "speak", "cancel", "pause_speech", "key", "set_braille_info", "set_display_size", "display", "braille_input", "set_clipboard_text":
|
||||
return append(data, '\n'), nil
|
||||
default:
|
||||
return nil, errProtocol
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func mustMessage(t *testing.T, data string) message {
|
||||
t.Helper()
|
||||
m, err := decodeMessage([]byte(data))
|
||||
if err != nil {
|
||||
t.Fatalf("decode fixture: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestProtocolFixtures(t *testing.T) {
|
||||
f, err := os.Open("testdata/nvda-v2.jsonl")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
r := bufio.NewReader(f)
|
||||
count := 0
|
||||
for {
|
||||
frame, err := readFrame(r)
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := decodeMessage(frame); err != nil {
|
||||
t.Fatalf("fixture %d: %v", count+1, err)
|
||||
}
|
||||
count++
|
||||
}
|
||||
if count != 23 {
|
||||
t.Fatalf("fixture count: %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpeechSemantics(t *testing.T) {
|
||||
m := mustMessage(t, `{"type":"speak","origin":7,"priority":2,"sequence":[" hello ",["CharacterModeCommand",{"state":true,"isDefault":false}],"é ",["LangChangeCommand",{"lang":"fr_FR","isDefault":false}],"monde",["LangChangeCommand",{"lang":null}],["EndUtteranceCommand",{}],["PitchCommand",{"offset":4}]," "]}`)
|
||||
s := m.payload.(speech)
|
||||
want := []speechPart{
|
||||
{kind: "text", text: " hello "}, {kind: "characters", characters: true},
|
||||
{kind: "text", text: "é "}, {kind: "language", text: "fr_FR"},
|
||||
{kind: "text", text: "monde"}, {kind: "language"}, {kind: "end"}, {kind: "text", text: " "},
|
||||
}
|
||||
if !reflect.DeepEqual(s.parts, want) || s.priority != 2 || s.unsupported != 1 {
|
||||
t.Fatalf("speech semantics: %#v", s)
|
||||
}
|
||||
if s := mustMessage(t, `{"type":"speak","sequence":["text"]}`).payload.(speech); s.priority != 0 {
|
||||
t.Fatal("absent priority must default to normal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMembershipVariants(t *testing.T) {
|
||||
for _, fixture := range []string{
|
||||
`{"type":"channel_joined","channel":"fixture","user_ids":[]}`,
|
||||
`{"type":"channel_joined","channel":"fixture","clients":[]}`,
|
||||
`{"type":"channel_joined","channel":"fixture","clients":[{"id":7,"connection_type":"slave","version":"extra"}],"user_ids":[7]}`,
|
||||
`{"type":"client_left","client":{"id":7,"connection_type":"slave"},"user_id":7}`,
|
||||
} {
|
||||
mustMessage(t, fixture)
|
||||
}
|
||||
for _, fixture := range []string{
|
||||
`{"type":"channel_joined","channel":"fixture","user_ids":[7]}`,
|
||||
`{"type":"channel_joined","channel":"fixture","clients":null}`,
|
||||
`{"type":"channel_joined","channel":"fixture","clients":[{"id":7,"connection_type":"slave"},{"id":7,"connection_type":"slave"}]}`,
|
||||
`{"type":"channel_joined","channel":"fixture","clients":[{"id":7,"connection_type":"slave"}],"user_ids":[8]}`,
|
||||
`{"type":"client_joined","client":{"id":7,"connection_type":"other"}}`,
|
||||
`{"type":"client_joined","client":{"id":7,"connection_type":"slave"},"user_id":8}`,
|
||||
`{"type":"client_left","user_id":7}`,
|
||||
} {
|
||||
if _, err := decodeMessage([]byte(fixture)); err == nil {
|
||||
t.Errorf("accepted invalid membership: %s", fixture)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectMalformedMessages(t *testing.T) {
|
||||
for _, fixture := range []string{
|
||||
`null`, `[]`, `{}`, `{"type":null}`, `{"type":"key","type":"cancel"}`,
|
||||
`{"type":"cancel","\u0074ype":"speak"}`, `{"type":"cancel"} {}`,
|
||||
`{"type":"cancel","extra":{"x":1,"x":2}}`, `{"type":"cancel","origin":0}`,
|
||||
`{"type":"cancel","origin":true}`, `{"type":"cancel","origin":1.0}`,
|
||||
`{"type":"key","vk_code":65,"extended":false}`,
|
||||
`{"type":"key","vk_code":256,"extended":false,"pressed":true}`,
|
||||
`{"type":"key","vk_code":65,"extended":0,"pressed":true}`,
|
||||
`{"type":"key","vk_code":65,"extended":false,"pressed":true,"scan_code":null}`,
|
||||
`{"type":"speak","priority":"normal","sequence":[]}`,
|
||||
`{"type":"speak","priority":null,"sequence":[]}`,
|
||||
`{"type":"speak","priority":3,"sequence":[]}`,
|
||||
`{"type":"speak","sequence":[null]}`,
|
||||
`{"type":"speak","sequence":[{"name":"CharacterModeCommand","state":true}]}`,
|
||||
`{"type":"speak","sequence":[["CharacterModeCommand",{}]]}`,
|
||||
`{"type":"speak","sequence":[["LangChangeCommand",{"lang":{}}]]}`,
|
||||
`{"type":"speak","sequence":[["LangChangeCommand",{"lang":"en\n"}]]}`,
|
||||
`{"type":"pause_speech","switch":1}`, `{"type":"display","cells":[256]}`,
|
||||
`{"type":"display","cells":"AA=="}`, `{"type":"display","cells":[-1]}`,
|
||||
`{"type":"display","cells":[null]}`, `{"type":"display","cells":null}`,
|
||||
`{"type":"set_display_size","sizes":[-1]}`,
|
||||
`{"type":"set_braille_info","numCells":4097}`,
|
||||
`{"type":"set_clipboard_text","text":false}`,
|
||||
`{"type":"motd","message":"incorrect field"}`,
|
||||
`{"type":"motd","motd":"text","force_display":1}`,
|
||||
`{"type":"braille_input","scriptPath":["globalCommands"]}`,
|
||||
`{"type":"braille_input","routingIndex":-1}`,
|
||||
`{"type":"braille_input","routingIndex":2,"cellIndexes":[3]}`,
|
||||
} {
|
||||
if _, err := decodeMessage([]byte(fixture)); err == nil {
|
||||
t.Errorf("accepted malformed fixture: %s", fixture)
|
||||
}
|
||||
}
|
||||
if _, err := decodeMessage([]byte("{\"type\":\"cancel\",\"x\":\"\xff\"}")); err == nil {
|
||||
t.Fatal("accepted invalid UTF-8")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectionAndTextBounds(t *testing.T) {
|
||||
for _, fixture := range []string{
|
||||
`{"type":"unknown","extra":` + strings.Repeat("[", 26) + "0" + strings.Repeat("]", 26) + "}",
|
||||
`{"type":"display","cells":[` + strings.Repeat("0,", maxCells) + "0]}",
|
||||
`{"type":"speak","sequence":[` + strings.Repeat(`"",`, maxSequence) + `""]}`,
|
||||
`{"type":"set_clipboard_text","text":"` + strings.Repeat("x", maxTextBytes+1) + `"}`,
|
||||
} {
|
||||
if _, err := decodeMessage([]byte(fixture)); err == nil {
|
||||
t.Fatal("accepted oversized content")
|
||||
}
|
||||
}
|
||||
mustMessage(t, `{"type":"set_clipboard_text","text":"`+strings.Repeat("é", maxTextBytes/2)+`"}`)
|
||||
}
|
||||
|
||||
func TestBrailleAllowlist(t *testing.T) {
|
||||
cases := []struct {
|
||||
fields string
|
||||
want gesture
|
||||
}{
|
||||
{`"scriptPath":["globalCommands","GlobalCommands","braille_scrollBack"]`, gesture{action: "pan-left"}},
|
||||
{`"scriptPath":["globalCommands","GlobalCommands","braille_scrollForward"]`, gesture{action: "pan-right"}},
|
||||
{`"scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"routingIndex":3`, gesture{action: "route", index: 3}},
|
||||
{`"scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"cellIndexes":[3],"routingIndex":3`, gesture{action: "route", index: 3}},
|
||||
{`"scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"cellIndexes":[3,4]`, gesture{}},
|
||||
{`"scriptPath":["globalCommands","GlobalCommands","kb:windows+r"]`, gesture{}},
|
||||
{`"scriptPath":["plugin","GlobalPlugin","braille_scrollBack"]`, gesture{}},
|
||||
{`"dots":7,"space":true`, gesture{}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
g := mustMessage(t, `{"type":"braille_input",`+tc.fields+`}`).payload.(gesture)
|
||||
if g != tc.want {
|
||||
t.Errorf("gesture: got %#v want %#v", g, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type fragmentReader struct{ io.Reader }
|
||||
|
||||
func (r fragmentReader) Read(p []byte) (int, error) {
|
||||
if len(p) > 3 {
|
||||
p = p[:3]
|
||||
}
|
||||
return r.Reader.Read(p)
|
||||
}
|
||||
|
||||
func TestFraming(t *testing.T) {
|
||||
r := bufio.NewReaderSize(fragmentReader{strings.NewReader("first\nsecond\npartial")}, 16)
|
||||
for _, want := range []string{"first", "second"} {
|
||||
got, err := readFrame(r)
|
||||
if err != nil || string(got) != want {
|
||||
t.Fatalf("fragmented read: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
if _, err := readFrame(r); !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
t.Fatalf("unterminated frame: %v", err)
|
||||
}
|
||||
for _, n := range []int{maxRelayFrame, maxRelayFrame + 1} {
|
||||
got, err := readFrame(bufio.NewReader(strings.NewReader(strings.Repeat("x", n) + "\n")))
|
||||
if n == maxRelayFrame && (err != nil || len(got) != n) || n > maxRelayFrame && !errors.Is(err, errLimit) {
|
||||
t.Fatalf("boundary %d: %v", n, err)
|
||||
}
|
||||
}
|
||||
if _, err := readFrame(bufio.NewReader(strings.NewReader(strings.Repeat("x", maxRelayFrame+8192)))); !errors.Is(err, errLimit) {
|
||||
t.Fatalf("unbounded no-newline read: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutboundFrames(t *testing.T) {
|
||||
frame, err := encodeMessage("key", keyTransition{VK: 65, Pressed: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m, err := decodeMessage(bytes.TrimSuffix(frame, []byte{'\n'}))
|
||||
if err != nil || m.payload.(keyTransition).Scan != nil {
|
||||
t.Fatalf("key roundtrip: %v", err)
|
||||
}
|
||||
frame, err = encodeMessage("display", struct {
|
||||
Cells []int `json:"cells"`
|
||||
}{[]int{0, 128, 255}})
|
||||
if err != nil || !bytes.Contains(frame, []byte(`[0,128,255]`)) {
|
||||
t.Fatal("cells must remain JSON integers")
|
||||
}
|
||||
for _, p := range []any{map[string]any{"origin": 7}, map[string]any{"type": "key"}, nil} {
|
||||
if _, err := encodeMessage("cancel", p); err == nil {
|
||||
t.Fatal("accepted metadata override")
|
||||
}
|
||||
}
|
||||
if _, err := encodeMessage("send_SAS", struct{}{}); err == nil {
|
||||
t.Fatal("encoded unsupported effect")
|
||||
}
|
||||
}
|
||||
|
||||
func FuzzDecodeMessage(f *testing.F) {
|
||||
for _, s := range []string{`{"type":"cancel","origin":7}`, `{"type":"speak","sequence":["text"]}`, `{"type":"display","cells":[0,255]}`, `null`} {
|
||||
f.Add([]byte(s))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
m, err := decodeMessage(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if !json.Valid(data) || m.kind == "" {
|
||||
t.Fatal("accepted invalid message")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
// session is a single-owner relay membership state machine, not a reader access
|
||||
// lease. Only core may authorize desktop effects. Every delivery and send must
|
||||
// separately recheck that lease after this layer has checked the relay epoch.
|
||||
type session struct {
|
||||
role role
|
||||
epoch uint64
|
||||
state string // joining, waiting, ready, suspended, closed
|
||||
peer peer
|
||||
ignored uint64 // Saturating counter; never stores untrusted diagnostic text.
|
||||
}
|
||||
|
||||
func newSession(r role, epoch uint64) (*session, error) {
|
||||
if !r.valid() || epoch == 0 {
|
||||
return nil, errProtocol
|
||||
}
|
||||
return &session{role: r, epoch: epoch, state: "joining"}, nil
|
||||
}
|
||||
|
||||
func (s *session) suspend(err error) (bool, error) {
|
||||
s.state, s.peer = "suspended", peer{}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func (s *session) close() { s.state, s.peer = "closed", peer{} }
|
||||
|
||||
// accept returns true only for an understood peer payload. Membership and
|
||||
// keepalive messages update state but never become desktop effects. A rejected
|
||||
// current-epoch message suspends the connection until an explicit new session.
|
||||
func (s *session) accept(epoch uint64, m message) (bool, error) {
|
||||
if epoch != s.epoch {
|
||||
return false, errStale
|
||||
}
|
||||
if s.state == "closed" || s.state == "suspended" {
|
||||
return false, errState
|
||||
}
|
||||
switch m.kind {
|
||||
case "channel_joined":
|
||||
v, ok := m.payload.(membership)
|
||||
if !ok || s.state != "joining" || len(v.peers) > 1 {
|
||||
return s.suspend(errPeer)
|
||||
}
|
||||
s.state = "waiting"
|
||||
if len(v.peers) == 1 {
|
||||
if v.peers[0].Role == s.role {
|
||||
return s.suspend(errPeer)
|
||||
}
|
||||
s.peer, s.state = v.peers[0], "ready"
|
||||
}
|
||||
return false, nil
|
||||
case "client_joined":
|
||||
p, ok := m.payload.(peer)
|
||||
if !ok || s.state != "waiting" || p.Role == s.role || m.origin != 0 && m.origin != p.ID {
|
||||
return s.suspend(errPeer)
|
||||
}
|
||||
s.peer, s.state = p, "ready"
|
||||
return false, nil
|
||||
case "client_left":
|
||||
// Even an unexpected departure signals an ambiguous membership history.
|
||||
return s.suspend(errPeer)
|
||||
case "error", "version_mismatch", "nvda_not_connected":
|
||||
return s.suspend(errProtocol)
|
||||
case "ping", "motd":
|
||||
if m.origin != 0 {
|
||||
return s.suspend(errPeer)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if s.state != "ready" || m.origin != s.peer.ID {
|
||||
return s.suspend(errPeer)
|
||||
}
|
||||
if !knownEffect(m.kind) {
|
||||
if s.ignored != ^uint64(0) {
|
||||
s.ignored++
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if !roleCanSend(s.peer.Role, m.kind) {
|
||||
return s.suspend(errPeer)
|
||||
}
|
||||
if g, ok := m.payload.(gesture); ok && g.action == "" {
|
||||
if s.ignored != ^uint64(0) {
|
||||
s.ignored++
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func knownEffect(kind string) bool {
|
||||
switch kind {
|
||||
case "speak", "cancel", "pause_speech", "display", "key", "braille_input", "set_display_size", "set_braille_info", "set_clipboard_text":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func roleCanSend(r role, kind string) bool {
|
||||
switch kind {
|
||||
case "set_braille_info", "set_clipboard_text":
|
||||
return r.valid()
|
||||
case "speak", "cancel", "pause_speech", "display":
|
||||
return r == controlled
|
||||
case "key", "braille_input", "set_display_size":
|
||||
return r == controller
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *session) allowSend(epoch uint64, kind string) error {
|
||||
if epoch != s.epoch {
|
||||
return errStale
|
||||
}
|
||||
if s.state != "ready" {
|
||||
return errState
|
||||
}
|
||||
if !roleCanSend(s.role, kind) {
|
||||
return errProtocol
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func readySession(t *testing.T, r role) *session {
|
||||
t.Helper()
|
||||
s, err := newSession(r, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opposite := controller
|
||||
if r == controller {
|
||||
opposite = controlled
|
||||
}
|
||||
_, err = s.accept(1, message{kind: "channel_joined", payload: membership{peers: []peer{{ID: 7, Role: opposite}}}})
|
||||
if err != nil || s.state != "ready" {
|
||||
t.Fatalf("ready: %v", err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestSessionRoleDirections(t *testing.T) {
|
||||
for _, r := range []role{controller, controlled} {
|
||||
for _, kind := range []string{"speak", "cancel", "pause_speech", "display", "key", "braille_input", "set_braille_info", "set_display_size", "set_clipboard_text"} {
|
||||
s := readySession(t, r)
|
||||
want := roleCanSend(s.peer.Role, kind)
|
||||
accepted, err := s.accept(1, message{kind: kind, origin: 7})
|
||||
if accepted != want || (err == nil) != want {
|
||||
t.Fatalf("role %s kind %s: %v %v", r, kind, accepted, err)
|
||||
}
|
||||
if !want && s.state != "suspended" {
|
||||
t.Fatal("wrong role did not suspend")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionMembershipAndEpoch(t *testing.T) {
|
||||
s, _ := newSession(controller, 9)
|
||||
if _, err := s.accept(8, message{kind: "client_left"}); !errors.Is(err, errStale) || s.state != "joining" {
|
||||
t.Fatal("old epoch changed session")
|
||||
}
|
||||
if _, err := s.accept(9, mustMessage(t, `{"type":"channel_joined","channel":"fixture","user_ids":[]}`)); err != nil || s.state != "waiting" {
|
||||
t.Fatal("empty channel should wait")
|
||||
}
|
||||
if err := s.allowSend(9, "key"); !errors.Is(err, errState) {
|
||||
t.Fatal("sent without peer")
|
||||
}
|
||||
if _, err := s.accept(9, mustMessage(t, `{"type":"client_joined","origin":7,"user_id":7,"client":{"id":7,"connection_type":"slave"}}`)); err != nil || s.state != "ready" {
|
||||
t.Fatal("peer did not become ready")
|
||||
}
|
||||
if err := s.allowSend(8, "key"); !errors.Is(err, errStale) {
|
||||
t.Fatal("sent old epoch")
|
||||
}
|
||||
if err := s.allowSend(9, "key"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.accept(9, mustMessage(t, `{"type":"client_left","origin":7,"client":{"id":7,"connection_type":"slave"}}`)); !errors.Is(err, errPeer) || s.peer.ID != 0 || s.state != "suspended" {
|
||||
t.Fatal("departure did not revoke peer")
|
||||
}
|
||||
if _, err := s.accept(9, mustMessage(t, `{"type":"client_joined","client":{"id":8,"connection_type":"slave"}}`)); !errors.Is(err, errState) {
|
||||
t.Fatal("silently resumed")
|
||||
}
|
||||
if err := s.allowSend(9, "key"); !errors.Is(err, errState) {
|
||||
t.Fatal("sent after departure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionFailsClosed(t *testing.T) {
|
||||
for _, fixture := range []string{
|
||||
`{"type":"speak","sequence":["text"]}`,
|
||||
`{"type":"speak","origin":8,"sequence":["text"]}`,
|
||||
`{"type":"client_joined","client":{"id":8,"connection_type":"slave"}}`,
|
||||
`{"type":"client_joined","client":{"id":7,"connection_type":"slave"}}`,
|
||||
`{"type":"channel_joined","channel":"fixture"}`,
|
||||
`{"type":"ping","origin":7}`,
|
||||
`{"type":"error","message":"private server content"}`,
|
||||
} {
|
||||
s := readySession(t, controller)
|
||||
if ok, err := s.accept(1, mustMessage(t, fixture)); err == nil || ok || s.state != "suspended" {
|
||||
t.Errorf("did not suspend: %s", fixture)
|
||||
}
|
||||
}
|
||||
for _, peers := range [][]peer{{{ID: 7, Role: controller}}, {{ID: 7, Role: controlled}, {ID: 8, Role: controlled}}} {
|
||||
s, _ := newSession(controller, 1)
|
||||
if _, err := s.accept(1, message{kind: "channel_joined", payload: membership{peers: peers}}); err == nil {
|
||||
t.Fatal("accepted unsafe membership")
|
||||
}
|
||||
}
|
||||
s, _ := newSession(controlled, 1)
|
||||
if _, err := s.accept(1, mustMessage(t, `{"type":"key","origin":7,"vk_code":65,"pressed":true,"extended":false}`)); err == nil {
|
||||
t.Fatal("effect before handshake")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionIgnoresUnsupportedEffects(t *testing.T) {
|
||||
s := readySession(t, controlled)
|
||||
for _, fixture := range []string{
|
||||
`{"type":"send_SAS","origin":7}`,
|
||||
`{"type":"wave","origin":7,"fileName":"do-not-open.wav"}`,
|
||||
`{"type":"braille_input","origin":7,"scriptPath":["globalCommands","GlobalCommands","kb:windows+r"]}`,
|
||||
} {
|
||||
if ok, err := s.accept(1, mustMessage(t, fixture)); ok || err != nil {
|
||||
t.Fatalf("unsupported effect: %v %v", ok, err)
|
||||
}
|
||||
}
|
||||
if s.ignored != 3 {
|
||||
t.Fatal("missing bounded diagnostic count")
|
||||
}
|
||||
s.close()
|
||||
if _, err := s.accept(1, mustMessage(t, `{"type":"cancel","origin":7}`)); !errors.Is(err, errState) {
|
||||
t.Fatal("closed session accepted output")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
var errSettings = errors.New("remote settings are unavailable or unsafe")
|
||||
|
||||
const maxSettingsBytes = 8 * 1024
|
||||
|
||||
// No key, lease, peer, startup-connect or reusable session consent belongs in
|
||||
// ordinary settings. Saved pins are trust decisions bound to a single endpoint.
|
||||
type settings struct {
|
||||
Version int `toml:"version"`
|
||||
Role string `toml:"role"`
|
||||
Host string `toml:"host"`
|
||||
Port int `toml:"port"`
|
||||
Pin *savedPin `toml:"pin,omitempty"`
|
||||
}
|
||||
|
||||
type savedPin struct {
|
||||
Host string `toml:"host"`
|
||||
Port int `toml:"port"`
|
||||
SHA256 string `toml:"sha256"`
|
||||
}
|
||||
|
||||
type savedKey struct {
|
||||
Version int `toml:"version"`
|
||||
Host string `toml:"host"`
|
||||
Port int `toml:"port"`
|
||||
Key string `toml:"key"`
|
||||
}
|
||||
|
||||
func (value settings) endpoint() (endpoint, error) {
|
||||
e := endpoint{host: value.Host, port: value.Port}
|
||||
if value.Version != 1 || (value.Role != "controller" && value.Role != "controlled") {
|
||||
return endpoint{}, errSettings
|
||||
}
|
||||
if value.Pin != nil {
|
||||
digest, err := hex.DecodeString(value.Pin.SHA256)
|
||||
if err != nil || len(digest) != 32 || hex.EncodeToString(digest) != value.Pin.SHA256 {
|
||||
return endpoint{}, errSettings
|
||||
}
|
||||
pin := certificatePin{host: value.Pin.Host, port: value.Pin.Port}
|
||||
copy(pin.sha256[:], digest)
|
||||
e.pin = &pin
|
||||
}
|
||||
if _, err := e.tlsConfig(); err != nil {
|
||||
return endpoint{}, errSettings
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// settingsStore owns a directory descriptor, not a pathname reopened per write.
|
||||
// Opening/loading it does no network I/O. The caller chooses when to read a saved
|
||||
// key; there is no automatic connection or restore of session permissions.
|
||||
type settingsStore struct {
|
||||
mu sync.Mutex
|
||||
directory *os.File
|
||||
}
|
||||
|
||||
// Parents must already exist. Reject symlinks in every path component and require
|
||||
// a private, current-user final directory. This deliberately refuses a symlinked
|
||||
// settings location instead of silently weakening credential handling.
|
||||
func openSettingsStore(path string) (*settingsStore, error) {
|
||||
if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == "/" {
|
||||
return nil, errSettings
|
||||
}
|
||||
fd, err := syscall.Open("/", syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil, errSettings
|
||||
}
|
||||
components := strings.Split(strings.TrimPrefix(path, "/"), "/")
|
||||
for index, component := range components {
|
||||
next, openErr := syscall.Openat(fd, component, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
|
||||
if openErr == syscall.ENOENT && index == len(components)-1 {
|
||||
mkdirErr := syscall.Mkdirat(fd, component, 0700)
|
||||
if mkdirErr != nil && mkdirErr != syscall.EEXIST {
|
||||
syscall.Close(fd)
|
||||
return nil, errSettings
|
||||
}
|
||||
next, openErr = syscall.Openat(fd, component, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
|
||||
}
|
||||
syscall.Close(fd)
|
||||
if openErr != nil {
|
||||
return nil, errSettings
|
||||
}
|
||||
fd = next
|
||||
}
|
||||
directory := os.NewFile(uintptr(fd), "remote-settings")
|
||||
if !privateFile(directory, true) {
|
||||
directory.Close()
|
||||
return nil, errSettings
|
||||
}
|
||||
return &settingsStore{directory: directory}, nil
|
||||
}
|
||||
|
||||
func privateFile(file *os.File, directory bool) bool {
|
||||
var stat syscall.Stat_t
|
||||
if syscall.Fstat(int(file.Fd()), &stat) != nil || stat.Uid != uint32(os.Getuid()) || stat.Mode&0077 != 0 {
|
||||
return false
|
||||
}
|
||||
if directory {
|
||||
return stat.Mode&syscall.S_IFMT == syscall.S_IFDIR
|
||||
}
|
||||
return stat.Mode&syscall.S_IFMT == syscall.S_IFREG && stat.Nlink == 1
|
||||
}
|
||||
|
||||
func (store *settingsStore) close() {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
if store.directory != nil {
|
||||
store.directory.Close()
|
||||
store.directory = nil
|
||||
}
|
||||
}
|
||||
|
||||
// Lock cooperating processes as well as callers. Existing unsafe lock files are
|
||||
// rejected; diagnostics never include a path, credential, or parser excerpt.
|
||||
func (store *settingsStore) lock() (*os.File, error) {
|
||||
if store.directory == nil || !privateFile(store.directory, true) {
|
||||
return nil, errSettings
|
||||
}
|
||||
fd, err := syscall.Openat(int(store.directory.Fd()), ".lock", syscall.O_RDWR|syscall.O_CREAT|syscall.O_NONBLOCK|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0600)
|
||||
if err != nil {
|
||||
return nil, errSettings
|
||||
}
|
||||
lock := os.NewFile(uintptr(fd), "remote-settings-lock")
|
||||
if !privateFile(lock, false) || syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB) != nil {
|
||||
lock.Close()
|
||||
return nil, errSettings
|
||||
}
|
||||
return lock, nil // Close releases flock.
|
||||
}
|
||||
|
||||
func (store *settingsStore) read(name string) ([]byte, error) {
|
||||
fd, err := syscall.Openat(int(store.directory.Fd()), name, syscall.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
|
||||
if err == syscall.ENOENT {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errSettings
|
||||
}
|
||||
file := os.NewFile(uintptr(fd), "remote-settings-data")
|
||||
defer file.Close()
|
||||
if !privateFile(file, false) {
|
||||
return nil, errSettings
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(file, maxSettingsBytes+1))
|
||||
if err != nil || len(data) > maxSettingsBytes {
|
||||
return nil, errSettings
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (store *settingsStore) replace(name string, value any) error {
|
||||
data, err := toml.Marshal(value)
|
||||
if err != nil || len(data) > maxSettingsBytes {
|
||||
return errSettings
|
||||
}
|
||||
// Refuse existing links/special files rather than replacing them silently.
|
||||
if _, err := store.read(name); err != nil {
|
||||
return err
|
||||
}
|
||||
var nonce [16]byte
|
||||
if _, err := rand.Read(nonce[:]); err != nil {
|
||||
return errSettings
|
||||
}
|
||||
temporary := ".pending-" + hex.EncodeToString(nonce[:])
|
||||
dirfd := int(store.directory.Fd())
|
||||
fd, err := syscall.Openat(dirfd, temporary, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_EXCL|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0600)
|
||||
if err != nil {
|
||||
return errSettings
|
||||
}
|
||||
file := os.NewFile(uintptr(fd), "remote-settings-pending")
|
||||
defer file.Close()
|
||||
defer syscall.Unlinkat(dirfd, temporary)
|
||||
if _, err := file.Write(data); err != nil {
|
||||
return errSettings
|
||||
}
|
||||
if file.Sync() != nil || file.Close() != nil {
|
||||
return errSettings
|
||||
}
|
||||
if syscall.Renameat(dirfd, temporary, dirfd, name) != nil || store.directory.Sync() != nil {
|
||||
return errSettings
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeSettings(data []byte, value any) error {
|
||||
if toml.NewDecoder(bytes.NewReader(data)).DisallowUnknownFields().Decode(value) != nil {
|
||||
return errSettings
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *settingsStore) save(value settings) error {
|
||||
if _, err := value.endpoint(); err != nil {
|
||||
return err
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
lock, err := store.lock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer lock.Close()
|
||||
return store.replace("settings.toml", value)
|
||||
}
|
||||
|
||||
func (store *settingsStore) load() (settings, bool, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
lock, err := store.lock()
|
||||
if err != nil {
|
||||
return settings{}, false, err
|
||||
}
|
||||
defer lock.Close()
|
||||
data, err := store.read("settings.toml")
|
||||
if err != nil || data == nil {
|
||||
return settings{}, false, err
|
||||
}
|
||||
var value settings
|
||||
if decodeSettings(data, &value) != nil {
|
||||
return settings{}, false, errSettings
|
||||
}
|
||||
if _, err := value.endpoint(); err != nil {
|
||||
return settings{}, false, err
|
||||
}
|
||||
return value, true, nil
|
||||
}
|
||||
|
||||
// rememberKey must be called only for an explicit local Remember key decision.
|
||||
// Pins are stored only in settings; secret state is independently replaceable.
|
||||
func (store *settingsStore) rememberKey(e endpoint, key string) error {
|
||||
if _, err := e.tlsConfig(); err != nil || !validChannelKey(key) {
|
||||
return errSettings
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
lock, err := store.lock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer lock.Close()
|
||||
return store.replace("channel-key.toml", savedKey{Version: 1, Host: e.host, Port: e.port, Key: key})
|
||||
}
|
||||
|
||||
func (store *settingsStore) loadKey(e endpoint) (string, error) {
|
||||
if _, err := e.tlsConfig(); err != nil {
|
||||
return "", errSettings
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
lock, err := store.lock()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer lock.Close()
|
||||
data, err := store.read("channel-key.toml")
|
||||
if err != nil || data == nil {
|
||||
return "", err
|
||||
}
|
||||
var value savedKey
|
||||
if decodeSettings(data, &value) != nil || value.Version != 1 || !validChannelKey(value.Key) {
|
||||
return "", errSettings
|
||||
}
|
||||
if _, err := (endpoint{host: value.Host, port: value.Port}).tlsConfig(); err != nil {
|
||||
return "", errSettings
|
||||
}
|
||||
if value.Host != e.host || value.Port != e.port {
|
||||
return "", nil
|
||||
}
|
||||
return value.Key, nil
|
||||
}
|
||||
|
||||
// forgetKey reports failure; callers must not claim forgetting succeeded if it
|
||||
// could not remove/sync the credential. Removal is not secure disk erasure.
|
||||
func (store *settingsStore) forgetKey() error {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
lock, err := store.lock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer lock.Close()
|
||||
data, err := store.read("channel-key.toml")
|
||||
if err != nil || data == nil {
|
||||
return err
|
||||
}
|
||||
if syscall.Unlinkat(int(store.directory.Fd()), "channel-key.toml") != nil || store.directory.Sync() != nil {
|
||||
return errSettings
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package remote
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func settingsFixture(t *testing.T) (*settingsStore, string, settings) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "remote")
|
||||
store, err := openSettingsStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(store.close)
|
||||
return store, path, settings{Version: 1, Role: "controller", Host: "relay.invalid", Port: 6837}
|
||||
}
|
||||
|
||||
func TestSettingsAndExplicitSavedKeyRoundTrip(t *testing.T) {
|
||||
store, path, value := settingsFixture(t)
|
||||
if _, exists, err := store.load(); err != nil || exists {
|
||||
t.Fatal("new store has settings", exists, err)
|
||||
}
|
||||
e, err := value.endpoint()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if key, err := store.loadKey(e); err != nil || key != "" {
|
||||
t.Fatal("key stored by default")
|
||||
}
|
||||
if err := store.save(value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := "private-fixture-猫-key"
|
||||
if err := store.rememberKey(e, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ordinary, err := os.ReadFile(filepath.Join(path, "settings.toml"))
|
||||
if err != nil || strings.Contains(string(ordinary), key) {
|
||||
t.Fatal("ordinary settings contain secret")
|
||||
}
|
||||
for _, name := range []string{"settings.toml", "channel-key.toml", ".lock"} {
|
||||
info, err := os.Stat(filepath.Join(path, name))
|
||||
if err != nil || info.Mode().Perm() != 0600 {
|
||||
t.Fatal("file permissions", name, err)
|
||||
}
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.Mode().Perm() != 0700 {
|
||||
t.Fatal("directory permissions", err)
|
||||
}
|
||||
store.close()
|
||||
reopened, err := openSettingsStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reopened.close()
|
||||
got, exists, err := reopened.load()
|
||||
if err != nil || !exists || got != value {
|
||||
t.Fatal("settings restart", got, exists, err)
|
||||
}
|
||||
saved, err := reopened.loadKey(e)
|
||||
if err != nil || saved != key {
|
||||
t.Fatal("credential restart failed")
|
||||
}
|
||||
for _, other := range []endpoint{{host: "other.invalid", port: e.port}, {host: e.host, port: e.port + 1}} {
|
||||
saved, err := reopened.loadKey(other)
|
||||
if err != nil || saved != "" {
|
||||
t.Fatal("credential crossed endpoint")
|
||||
}
|
||||
}
|
||||
before, err := os.Stat(filepath.Join(path, "channel-key.toml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reopened.rememberKey(e, "replacement-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := os.Stat(filepath.Join(path, "channel-key.toml"))
|
||||
if err != nil || os.SameFile(before, after) {
|
||||
t.Fatal("credential was not atomically replaced")
|
||||
}
|
||||
files, err := os.ReadDir(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, file := range files {
|
||||
if strings.HasPrefix(file.Name(), ".pending-") {
|
||||
t.Fatal("temporary credential retained")
|
||||
}
|
||||
}
|
||||
if err := reopened.forgetKey(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reopened.forgetKey(); err != nil {
|
||||
t.Fatal("forget not idempotent", err)
|
||||
}
|
||||
if key, err := reopened.loadKey(e); err != nil || key != "" {
|
||||
t.Fatal("forgotten credential returned")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsPinIsBoundToEndpoint(t *testing.T) {
|
||||
store, _, value := settingsFixture(t)
|
||||
value.Pin = &savedPin{Host: value.Host, Port: value.Port, SHA256: strings.Repeat("ab", 32)}
|
||||
if err := store.save(value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, exists, err := store.load()
|
||||
if err != nil || !exists {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e, err := got.endpoint()
|
||||
if err != nil || e.pin == nil || e.pin.host != value.Host || e.pin.port != value.Port {
|
||||
t.Fatal("pin lost", err)
|
||||
}
|
||||
for _, variant := range []string{"host", "port", "zero", "invalid", "uppercase"} {
|
||||
t.Run(variant, func(t *testing.T) {
|
||||
copyValue := value
|
||||
pin := *value.Pin
|
||||
copyValue.Pin = &pin
|
||||
switch variant {
|
||||
case "host":
|
||||
pin.Host = "other.invalid"
|
||||
case "port":
|
||||
pin.Port++
|
||||
case "zero":
|
||||
pin.SHA256 = strings.Repeat("0", 64)
|
||||
case "invalid":
|
||||
pin.SHA256 = "not-a-fingerprint"
|
||||
case "uppercase":
|
||||
pin.SHA256 = strings.ToUpper(pin.SHA256)
|
||||
}
|
||||
if err := store.save(copyValue); !errors.Is(err, errSettings) {
|
||||
t.Fatal("unsafe pin accepted", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsRejectUnsafeStorage(t *testing.T) {
|
||||
for _, variant := range []string{"directory mode", "directory symlink", "ancestor symlink", "file mode", "file symlink", "hardlink", "fifo", "lock symlink", "lock mode", "lock busy"} {
|
||||
t.Run(variant, func(t *testing.T) {
|
||||
store, path, value := settingsFixture(t)
|
||||
e, _ := value.endpoint()
|
||||
sentinel := filepath.Join(t.TempDir(), "sentinel")
|
||||
if err := os.WriteFile(sentinel, []byte("unrelated sentinel"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyPath := filepath.Join(path, "channel-key.toml")
|
||||
var failure error
|
||||
switch variant {
|
||||
case "directory mode":
|
||||
if err := os.Chmod(path, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, failure = store.loadKey(e)
|
||||
if other, err := openSettingsStore(path); err == nil {
|
||||
other.close()
|
||||
t.Fatal("unsafe directory opened")
|
||||
}
|
||||
case "directory symlink":
|
||||
link := filepath.Join(t.TempDir(), "link")
|
||||
if err := os.Symlink(path, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, failure = openSettingsStore(link)
|
||||
case "ancestor symlink":
|
||||
link := filepath.Join(t.TempDir(), "link")
|
||||
if err := os.Symlink(filepath.Dir(path), link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, failure = openSettingsStore(filepath.Join(link, "remote"))
|
||||
case "file mode":
|
||||
if err := os.WriteFile(keyPath, []byte("private-fixture"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failure = store.rememberKey(e, "new-fixture")
|
||||
case "file symlink":
|
||||
if err := os.Symlink(sentinel, keyPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failure = store.rememberKey(e, "new-fixture")
|
||||
case "hardlink":
|
||||
if err := os.Link(sentinel, keyPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failure = store.rememberKey(e, "new-fixture")
|
||||
case "fifo":
|
||||
if err := syscall.Mkfifo(keyPath, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, failure = store.loadKey(e)
|
||||
case "lock symlink":
|
||||
if err := os.Symlink(sentinel, filepath.Join(path, ".lock")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failure = store.save(value)
|
||||
case "lock mode":
|
||||
if err := os.WriteFile(filepath.Join(path, ".lock"), nil, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failure = store.save(value)
|
||||
case "lock busy":
|
||||
lock, err := store.lock()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lock.Close()
|
||||
failure = store.save(value)
|
||||
}
|
||||
if !errors.Is(failure, errSettings) {
|
||||
t.Fatal("unsafe storage accepted", failure)
|
||||
}
|
||||
data, err := os.ReadFile(sentinel)
|
||||
if err != nil || string(data) != "unrelated sentinel" {
|
||||
t.Fatal("unrelated file changed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsRejectUnknownMalformedAndOversizedValues(t *testing.T) {
|
||||
for _, data := range []string{
|
||||
"version=2\nrole='controller'\nhost='relay.invalid'\nport=6837\n",
|
||||
"version=1\nrole='controller'\nhost='relay.invalid'\nport=6837\nauto-connect=true\n",
|
||||
"version=1\nrole='controller'\nhost='relay.invalid'\nport=6837\nkey='private-fixture'\n",
|
||||
"version=1\nrole='other'\nhost='relay.invalid'\nport=6837\n",
|
||||
"version=1\nrole='controller'\nhost='relay.invalid'\nport=0\n",
|
||||
"version=1\nrole='controller'\nhost='relay.invalid/path'\nport=6837\n",
|
||||
"version=1\nrole='controller'\nhost='relay.invalid'\nport=6837\nport=6838\n",
|
||||
"private-fixture='unterminated",
|
||||
strings.Repeat("private-fixture", maxSettingsBytes),
|
||||
} {
|
||||
t.Run("invalid", func(t *testing.T) {
|
||||
store, path, _ := settingsFixture(t)
|
||||
if err := os.WriteFile(filepath.Join(path, "settings.toml"), []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, exists, err := store.load()
|
||||
if exists || !errors.Is(err, errSettings) || strings.Contains(err.Error(), "private-fixture") {
|
||||
t.Fatal("invalid settings accepted or leaked")
|
||||
}
|
||||
})
|
||||
}
|
||||
store, path, value := settingsFixture(t)
|
||||
e, _ := value.endpoint()
|
||||
for _, key := range []string{"", "line\nbreak", strings.Repeat("x", 513), string([]byte{0xff})} {
|
||||
if err := store.rememberKey(e, key); !errors.Is(err, errSettings) {
|
||||
t.Fatal("invalid credential saved")
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(path, "channel-key.toml"), []byte("key='private-fixture'"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if key, err := store.loadKey(e); key != "" || !errors.Is(err, errSettings) || strings.Contains(err.Error(), "private-fixture") {
|
||||
t.Fatal("invalid key file accepted or exposed")
|
||||
}
|
||||
store.close()
|
||||
if err := store.save(value); !errors.Is(err, errSettings) {
|
||||
t.Fatal("closed store accepted write")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
type speechPart struct {
|
||||
kind string // text, characters, language, end
|
||||
text string
|
||||
characters bool
|
||||
}
|
||||
|
||||
type speech struct {
|
||||
parts []speechPart
|
||||
priority int // NVDA NORMAL=0, NEXT=1, NOW=2; absent means NORMAL.
|
||||
unsupported int
|
||||
}
|
||||
|
||||
func decodeSpeech(f fields) (speech, error) {
|
||||
var s speech
|
||||
var err error
|
||||
s.priority, err = f.number("priority", 0, 2, true)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
var sequence []json.RawMessage
|
||||
if f.required("sequence", &sequence) != nil {
|
||||
return s, errProtocol
|
||||
}
|
||||
if len(sequence) > maxSequence {
|
||||
return s, errLimit
|
||||
}
|
||||
textBytes := 0
|
||||
for _, item := range sequence {
|
||||
var text string
|
||||
if len(item) > 0 && item[0] == '"' && json.Unmarshal(item, &text) == nil {
|
||||
textBytes += len(text)
|
||||
if textBytes > maxRelayFrame {
|
||||
return s, errLimit
|
||||
}
|
||||
s.parts = append(s.parts, speechPart{kind: "text", text: text})
|
||||
continue
|
||||
}
|
||||
var command []json.RawMessage
|
||||
if json.Unmarshal(item, &command) != nil || len(command) != 2 {
|
||||
return s, errProtocol
|
||||
}
|
||||
var name string
|
||||
if json.Unmarshal(command[0], &name) != nil || len(name) == 0 || len(name) > 128 {
|
||||
return s, errProtocol
|
||||
}
|
||||
values, err := object(command[1])
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
switch name {
|
||||
case "CharacterModeCommand":
|
||||
var state bool
|
||||
if values.required("state", &state) != nil {
|
||||
return s, errProtocol
|
||||
}
|
||||
s.parts = append(s.parts, speechPart{kind: "characters", characters: state})
|
||||
case "LangChangeCommand":
|
||||
raw, ok := values["lang"]
|
||||
if !ok {
|
||||
return s, errProtocol
|
||||
}
|
||||
var language string
|
||||
if !bytes.Equal(raw, []byte("null")) {
|
||||
if json.Unmarshal(raw, &language) != nil || len(language) > 64 {
|
||||
return s, errProtocol
|
||||
}
|
||||
for _, c := range language {
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_') {
|
||||
return s, errProtocol
|
||||
}
|
||||
}
|
||||
}
|
||||
s.parts = append(s.parts, speechPart{kind: "language", text: language})
|
||||
case "EndUtteranceCommand":
|
||||
s.parts = append(s.parts, speechPart{kind: "end"})
|
||||
default:
|
||||
s.unsupported++
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
{"type":"channel_joined","channel":"synthetic-fixture","user_ids":[]}
|
||||
{"type":"channel_joined","channel":"synthetic-fixture","user_ids":[7],"clients":[{"id":7,"connection_type":"slave"}]}
|
||||
{"type":"client_joined","origin":7,"user_id":7,"client":{"id":7,"connection_type":"slave"}}
|
||||
{"type":"client_left","origin":7,"user_id":7,"client":{"id":7,"connection_type":"slave"}}
|
||||
{"type":"speak","origin":7,"priority":0,"sequence":[" hello ",["CharacterModeCommand",{"state":true,"isDefault":false}],"a",["CharacterModeCommand",{"state":false,"isDefault":true}],["LangChangeCommand",{"lang":"fr_FR","isDefault":false}],"monde",["LangChangeCommand",{"lang":null,"isDefault":true}]]}
|
||||
{"type":"speak","origin":7,"priority":1,"sequence":["next"]}
|
||||
{"type":"speak","origin":7,"priority":2,"sequence":["now",["EndUtteranceCommand",{}]]}
|
||||
{"type":"cancel","origin":7}
|
||||
{"type":"pause_speech","origin":7,"switch":true}
|
||||
{"type":"key","origin":7,"vk_code":65,"extended":false,"pressed":true}
|
||||
{"type":"key","origin":7,"vk_code":163,"extended":true,"pressed":false,"scan_code":29}
|
||||
{"type":"set_braille_info","origin":7,"name":"synthetic-display","numCells":40}
|
||||
{"type":"set_braille_info","origin":7}
|
||||
{"type":"set_display_size","origin":7,"sizes":[40]}
|
||||
{"type":"display","origin":7,"cells":[0,1,127,128,255]}
|
||||
{"type":"braille_input","origin":7,"source":"synthetic","scriptPath":["globalCommands","GlobalCommands","braille_scrollBack"]}
|
||||
{"type":"braille_input","origin":7,"source":"synthetic","scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"routingIndex":3}
|
||||
{"type":"braille_input","origin":7,"source":"synthetic","scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"cellIndexes":[3],"routingIndex":3}
|
||||
{"type":"set_clipboard_text","origin":7,"text":"Harmless test text."}
|
||||
{"type":"ping"}
|
||||
{"type":"motd","motd":"Synthetic relay","force_display":false}
|
||||
{"type":"error","message":"incorrect_password"}
|
||||
{"type":"version_mismatch"}
|
||||
@@ -0,0 +1,316 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
dialTimeout = 15 * time.Second
|
||||
joinTimeout = 15 * time.Second
|
||||
writeTimeout = 5 * time.Second
|
||||
// NVDA's embedded relay sends ping every 300 seconds. A short application
|
||||
// read deadline would incorrectly disconnect idle but healthy sessions.
|
||||
idleTimeout = 6 * time.Minute
|
||||
maxPendingWrites = 32
|
||||
maxQueuedBytes = 256 << 10
|
||||
)
|
||||
|
||||
var (
|
||||
errEndpoint = errors.New("invalid remote relay endpoint")
|
||||
errTrust = errors.New("remote relay certificate verification failed")
|
||||
errNetwork = errors.New("remote relay connection failed")
|
||||
errTimeout = errors.New("remote relay operation timed out")
|
||||
errClosed = errors.New("remote relay connection closed")
|
||||
)
|
||||
|
||||
// A pin is an already-approved decision, not permission to ask a peer for trust.
|
||||
// There is deliberately no insecure flag, trust-on-first-use or auto-reconnect.
|
||||
type certificatePin struct {
|
||||
host string
|
||||
port int
|
||||
sha256 [32]byte
|
||||
}
|
||||
|
||||
type endpoint struct {
|
||||
host string
|
||||
port int
|
||||
roots *x509.CertPool // nil uses system roots; tests supply a private CA.
|
||||
pin *certificatePin
|
||||
}
|
||||
|
||||
func (e endpoint) tlsConfig() (*tls.Config, error) {
|
||||
if e.host == "" || len(e.host) > 253 || strings.TrimSpace(e.host) != e.host || strings.ContainsAny(e.host, "/\\@\x00\r\n\t []") || e.port < 1 || e.port > 65535 {
|
||||
return nil, errEndpoint
|
||||
}
|
||||
// Colons are accepted only in bare IPv6 literals; JoinHostPort adds brackets.
|
||||
if strings.Contains(e.host, ":") && net.ParseIP(e.host) == nil {
|
||||
return nil, errEndpoint
|
||||
}
|
||||
cfg := &tls.Config{MinVersion: tls.VersionTLS12, ServerName: e.host, RootCAs: e.roots}
|
||||
if e.pin != nil {
|
||||
pin := *e.pin // Freeze the trust decision for this connection.
|
||||
if pin.host != e.host || pin.port != e.port || pin.sha256 == [32]byte{} {
|
||||
return nil, errTrust
|
||||
}
|
||||
// Exact leaf-certificate identity replaces CA/hostname validation only
|
||||
// for this explicitly approved host and port. TLS still proves key ownership.
|
||||
cfg.InsecureSkipVerify = true
|
||||
cfg.VerifyConnection = func(state tls.ConnectionState) error {
|
||||
if len(state.PeerCertificates) == 0 {
|
||||
return errTrust
|
||||
}
|
||||
digest := sha256.Sum256(state.PeerCertificates[0].Raw)
|
||||
if subtle.ConstantTimeCompare(digest[:], pin.sha256[:]) != 1 {
|
||||
return errTrust
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func generateChannelKey() (string, error) {
|
||||
var entropy [32]byte
|
||||
if _, err := rand.Read(entropy[:]); err != nil {
|
||||
return "", errors.New("remote channel key generation failed")
|
||||
}
|
||||
return hex.EncodeToString(entropy[:]), nil
|
||||
}
|
||||
|
||||
type relayConn struct {
|
||||
conn net.Conn
|
||||
reader *bufio.Reader // One reader owner only.
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
stop func() bool
|
||||
once sync.Once
|
||||
writeGate chan struct{}
|
||||
mu sync.Mutex
|
||||
pending, bytes int
|
||||
}
|
||||
|
||||
func newRelayConn(ctx context.Context, conn net.Conn) *relayConn {
|
||||
lifetime, cancel := context.WithCancel(ctx)
|
||||
c := &relayConn{conn: conn, reader: bufio.NewReaderSize(conn, 4096), ctx: lifetime, cancel: cancel, writeGate: make(chan struct{}, 1)}
|
||||
c.stop = context.AfterFunc(lifetime, func() { _ = conn.Close() })
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *relayConn) close() {
|
||||
c.once.Do(func() {
|
||||
c.cancel()
|
||||
c.stop()
|
||||
_ = c.conn.Close()
|
||||
})
|
||||
}
|
||||
|
||||
// connect performs TLS authentication before writing any protocol bytes. It
|
||||
// returns only after a matching channel_joined; peer readiness is separate.
|
||||
// The supplied context owns the entire connection, including after return.
|
||||
func connect(ctx context.Context, e endpoint, r role, key string) (*relayConn, message, error) {
|
||||
cfg, err := e.tlsConfig()
|
||||
if err != nil {
|
||||
return nil, message{}, err
|
||||
}
|
||||
if !r.valid() || !validChannelKey(key) {
|
||||
return nil, message{}, errProtocol
|
||||
}
|
||||
dialCtx, cancel := context.WithTimeout(ctx, dialTimeout)
|
||||
defer cancel()
|
||||
dialer := &net.Dialer{KeepAliveConfig: net.KeepAliveConfig{Enable: true, Idle: 10 * time.Second, Interval: 3 * time.Second, Count: 3}}
|
||||
raw, err := dialer.DialContext(dialCtx, "tcp", net.JoinHostPort(e.host, strconv.Itoa(e.port)))
|
||||
if err != nil {
|
||||
return nil, message{}, networkError(ctx, err)
|
||||
}
|
||||
tlsConn := tls.Client(raw, cfg)
|
||||
if err := tlsConn.HandshakeContext(dialCtx); err != nil {
|
||||
_ = raw.Close()
|
||||
var verify *tls.CertificateVerificationError
|
||||
if errors.As(err, &verify) || errors.Is(err, errTrust) {
|
||||
return nil, message{}, errTrust
|
||||
}
|
||||
return nil, message{}, networkError(ctx, err)
|
||||
}
|
||||
c := newRelayConn(ctx, tlsConn)
|
||||
success := false
|
||||
defer func() {
|
||||
if !success {
|
||||
c.close()
|
||||
}
|
||||
}()
|
||||
joinCtx, cancelJoin := context.WithTimeout(ctx, joinTimeout)
|
||||
defer cancelJoin()
|
||||
// Cancellation closes the connection even while a read/write is blocked.
|
||||
stop := context.AfterFunc(joinCtx, c.close)
|
||||
defer stop()
|
||||
version := []byte("{\"type\":\"protocol_version\",\"version\":2}\n")
|
||||
join, _ := json.Marshal(struct {
|
||||
Type string `json:"type"`
|
||||
Channel string `json:"channel"`
|
||||
Role role `json:"connection_type"`
|
||||
}{"join", key, r})
|
||||
if err := c.write(joinCtx, version); err != nil {
|
||||
return nil, message{}, err
|
||||
}
|
||||
if err := c.write(joinCtx, append(join, '\n')); err != nil {
|
||||
return nil, message{}, err
|
||||
}
|
||||
deadline, _ := joinCtx.Deadline()
|
||||
// Bound pre-join notices as well as elapsed time.
|
||||
for count := 0; count < 32; count++ {
|
||||
m, err := c.readUntil(deadline)
|
||||
if err != nil {
|
||||
return nil, message{}, err
|
||||
}
|
||||
switch m.kind {
|
||||
case "ping", "motd":
|
||||
if m.origin != 0 {
|
||||
return nil, message{}, errPeer
|
||||
}
|
||||
continue
|
||||
case "channel_joined":
|
||||
v := m.payload.(membership)
|
||||
if v.channel != key {
|
||||
return nil, message{}, errProtocol
|
||||
}
|
||||
v.channel = "" // Do not retain the echoed credential in session state.
|
||||
m.payload = v
|
||||
if !stop() || joinCtx.Err() != nil {
|
||||
return nil, message{}, errTimeout
|
||||
}
|
||||
success = true
|
||||
return c, m, nil
|
||||
default:
|
||||
return nil, message{}, errProtocol
|
||||
}
|
||||
}
|
||||
return nil, message{}, errLimit
|
||||
}
|
||||
|
||||
func networkError(ctx context.Context, err error) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
var timeout net.Error
|
||||
if errors.As(err, &timeout) && timeout.Timeout() {
|
||||
return errTimeout
|
||||
}
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) {
|
||||
return errClosed
|
||||
}
|
||||
return errNetwork
|
||||
}
|
||||
|
||||
func (c *relayConn) read() (message, error) { return c.readUntil(time.Now().Add(idleTimeout)) }
|
||||
|
||||
func (c *relayConn) readUntil(deadline time.Time) (message, error) {
|
||||
if c.ctx.Err() != nil {
|
||||
c.close()
|
||||
return message{}, errClosed
|
||||
}
|
||||
if err := c.conn.SetReadDeadline(deadline); err != nil {
|
||||
c.close()
|
||||
return message{}, errClosed
|
||||
}
|
||||
frame, err := readFrame(c.reader)
|
||||
if err != nil {
|
||||
mapped := networkError(c.ctx, err)
|
||||
if errors.Is(err, errLimit) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
mapped = errProtocol
|
||||
}
|
||||
c.close()
|
||||
return message{}, mapped
|
||||
}
|
||||
m, err := decodeMessage(frame)
|
||||
// bufio may have another complete frame even after lifetime cancellation.
|
||||
if c.ctx.Err() != nil {
|
||||
c.close()
|
||||
return message{}, errClosed
|
||||
}
|
||||
if err != nil {
|
||||
c.close()
|
||||
}
|
||||
return m, err
|
||||
}
|
||||
|
||||
// write serializes complete frames and bounds waiting callers and retained
|
||||
// bytes. Overflow closes the transport rather than silently losing a key-up.
|
||||
// Callers must not invoke it from the reader's event/input thread.
|
||||
func (c *relayConn) write(ctx context.Context, frame []byte) error {
|
||||
c.mu.Lock()
|
||||
if len(frame) > maxQueuedBytes || c.pending >= maxPendingWrites || c.bytes+len(frame) > maxQueuedBytes {
|
||||
c.mu.Unlock()
|
||||
c.close()
|
||||
return errLimit
|
||||
}
|
||||
c.pending++
|
||||
c.bytes += len(frame)
|
||||
queuedBytes := len(frame)
|
||||
c.mu.Unlock()
|
||||
defer func() { c.mu.Lock(); c.pending--; c.bytes -= queuedBytes; c.mu.Unlock() }()
|
||||
op, cancel := context.WithTimeout(ctx, writeTimeout)
|
||||
defer cancel()
|
||||
select {
|
||||
case c.writeGate <- struct{}{}:
|
||||
defer func() { <-c.writeGate }()
|
||||
case <-op.Done():
|
||||
c.close()
|
||||
return op.Err()
|
||||
case <-c.ctx.Done():
|
||||
return errClosed
|
||||
}
|
||||
if op.Err() != nil || c.ctx.Err() != nil {
|
||||
c.close()
|
||||
return errClosed
|
||||
}
|
||||
stop := context.AfterFunc(op, c.close)
|
||||
defer stop()
|
||||
deadline, _ := op.Deadline()
|
||||
if c.conn.SetWriteDeadline(deadline) != nil {
|
||||
c.close()
|
||||
return errClosed
|
||||
}
|
||||
for len(frame) > 0 {
|
||||
n, err := c.conn.Write(frame)
|
||||
if err != nil || n == 0 {
|
||||
mapped := networkError(op, err)
|
||||
c.close()
|
||||
return mapped
|
||||
}
|
||||
frame = frame[n:]
|
||||
}
|
||||
if !stop() || op.Err() != nil {
|
||||
c.close()
|
||||
return errTimeout
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validChannelKey(key string) bool {
|
||||
if key == "" || !boundedText(key, 512) {
|
||||
return false
|
||||
}
|
||||
for _, ch := range key {
|
||||
if ch < 32 || ch == 127 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// All certificates and keys are generated in memory for a private loopback
|
||||
// relay. Nothing connects to the user's display, reader or a public relay.
|
||||
func testCertificate(t *testing.T, validHost bool) (tls.Certificate, *x509.CertPool) {
|
||||
t.Helper()
|
||||
pub, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Remote test relay"},
|
||||
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true, IsCA: true, DNSNames: []string{"localhost"},
|
||||
}
|
||||
if validHost {
|
||||
template.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")}
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, pub, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
roots.AddCert(leaf)
|
||||
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: leaf}, roots
|
||||
}
|
||||
|
||||
func testRelay(t *testing.T, cert tls.Certificate, serve func(net.Conn)) endpoint {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e := endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port}
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
var connections []net.Conn
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
connections = append(connections, conn)
|
||||
mu.Unlock()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
serve(tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12}))
|
||||
}()
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
_ = listener.Close()
|
||||
mu.Lock()
|
||||
for _, conn := range connections {
|
||||
_ = conn.Close()
|
||||
}
|
||||
mu.Unlock()
|
||||
wg.Wait()
|
||||
})
|
||||
return e
|
||||
}
|
||||
|
||||
func relayHandshake(t *testing.T, conn net.Conn, r role) *bufio.Reader {
|
||||
t.Helper()
|
||||
reader := bufio.NewReader(conn)
|
||||
version, err := readFrame(reader)
|
||||
if err != nil {
|
||||
t.Errorf("relay version read: %v", err)
|
||||
return nil
|
||||
}
|
||||
var v struct {
|
||||
Type string `json:"type"`
|
||||
Version int `json:"version"`
|
||||
}
|
||||
if json.Unmarshal(version, &v) != nil || v.Type != "protocol_version" || v.Version != 2 {
|
||||
t.Error("wrong protocol greeting")
|
||||
return nil
|
||||
}
|
||||
join, err := readFrame(reader)
|
||||
if err != nil {
|
||||
t.Errorf("relay join read: %v", err)
|
||||
return nil
|
||||
}
|
||||
var j struct {
|
||||
Type string `json:"type"`
|
||||
Channel string `json:"channel"`
|
||||
Role role `json:"connection_type"`
|
||||
}
|
||||
if json.Unmarshal(join, &j) != nil || j.Type != "join" || j.Channel != "synthetic-fixture" || j.Role != r {
|
||||
t.Error("wrong join fields")
|
||||
return nil
|
||||
}
|
||||
return reader
|
||||
}
|
||||
|
||||
func TestTLSJoinAndPeerSession(t *testing.T) {
|
||||
cert, roots := testCertificate(t, true)
|
||||
for _, r := range []role{controller, controlled} {
|
||||
t.Run(string(r), func(t *testing.T) {
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
reader := relayHandshake(t, conn, r)
|
||||
if reader == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"motd\",\"motd\":\"Synthetic relay\",\"force_display\":true}\n")
|
||||
if r == controller {
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"ping\"}\n{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[{\"id\":7,\"connection_type\":\"slave\"}]}\n{\"type\":\"speak\",\"origin\":7,\"sequence\":[\" hello \"],\"priority\":2}\n{\"type\":\"cancel\",\"origin\":7}\n")
|
||||
} else {
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[{\"id\":7,\"connection_type\":\"master\"}]}\n{\"type\":\"key\",\"origin\":7,\"vk_code\":65,\"extended\":false,\"pressed\":true}\n{\"type\":\"key\",\"origin\":7,\"vk_code\":65,\"extended\":false,\"pressed\":false}\n")
|
||||
}
|
||||
_, _ = reader.ReadByte() // Wait until client closes.
|
||||
})
|
||||
e.roots = roots
|
||||
conn, joined, err := connect(context.Background(), e, r, "synthetic-fixture")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.close()
|
||||
if joined.payload.(membership).channel != "" {
|
||||
t.Fatal("credential retained in returned membership")
|
||||
}
|
||||
s, _ := newSession(r, 1)
|
||||
if _, err := s.accept(1, joined); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 2 {
|
||||
m, err := conn.read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if accepted, err := s.accept(1, m); err != nil || !accepted {
|
||||
t.Fatalf("peer data: %v %v", accepted, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTLSRejectsBeforeChannelDisclosure(t *testing.T) {
|
||||
for _, mode := range []string{"unknown-ca", "wrong-host", "wrong-pin", "changed-certificate"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
cert, roots := testCertificate(t, mode != "wrong-host")
|
||||
read := make(chan int, 1)
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
buf := make([]byte, 4096)
|
||||
n, _ := conn.Read(buf)
|
||||
read <- n
|
||||
})
|
||||
switch mode {
|
||||
case "wrong-host":
|
||||
e.roots = roots
|
||||
case "wrong-pin", "changed-certificate":
|
||||
digest := sha256.Sum256(cert.Certificate[0])
|
||||
if mode == "changed-certificate" {
|
||||
old, _ := testCertificate(t, true)
|
||||
digest = sha256.Sum256(old.Certificate[0])
|
||||
} else {
|
||||
digest[0] ^= 1
|
||||
}
|
||||
e.roots = roots // A valid CA must not override a mismatched saved pin.
|
||||
e.pin = &certificatePin{host: e.host, port: e.port, sha256: digest}
|
||||
}
|
||||
conn, _, err := connect(context.Background(), e, controller, "synthetic-fixture")
|
||||
if conn != nil || !errors.Is(err, errTrust) {
|
||||
t.Fatalf("expected trust failure: %v", err)
|
||||
}
|
||||
select {
|
||||
case n := <-read:
|
||||
if n != 0 {
|
||||
t.Fatal("sent application data before verification")
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("server did not observe failure")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplicitPinAndEndpointBinding(t *testing.T) {
|
||||
cert, _ := testCertificate(t, false)
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
reader := relayHandshake(t, conn, controller)
|
||||
if reader == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"user_ids\":[]}\n")
|
||||
_, _ = reader.ReadByte()
|
||||
})
|
||||
e.pin = &certificatePin{host: e.host, port: e.port, sha256: sha256.Sum256(cert.Certificate[0])}
|
||||
conn, _, err := connect(context.Background(), e, controller, "synthetic-fixture")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn.close()
|
||||
wrong := *e.pin
|
||||
wrong.port++
|
||||
e.pin = &wrong
|
||||
if _, err := e.tlsConfig(); !errors.Is(err, errTrust) {
|
||||
t.Fatal("pin escaped port binding")
|
||||
}
|
||||
wrong.port = e.port
|
||||
wrong.host = "localhost"
|
||||
if _, err := e.tlsConfig(); !errors.Is(err, errTrust) {
|
||||
t.Fatal("pin escaped host binding")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinRejectsUnexpectedTraffic(t *testing.T) {
|
||||
cert, roots := testCertificate(t, true)
|
||||
for _, reply := range []string{
|
||||
`{"type":"channel_joined","channel":"wrong-fixture"}`,
|
||||
`{"type":"error","message":"do not expose this text"}`,
|
||||
`{"type":"speak","origin":7,"sequence":["before join"]}`,
|
||||
`{"type":"ping","origin":7}`,
|
||||
strings.Repeat("{\"type\":\"ping\"}\n", 32),
|
||||
} {
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, reply+"\n")
|
||||
})
|
||||
e.roots = roots
|
||||
conn, _, err := connect(context.Background(), e, controller, "synthetic-fixture")
|
||||
if conn != nil || err == nil || strings.Contains(err.Error(), "expose") {
|
||||
t.Fatalf("unsafe join: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelDuringJoin(t *testing.T) {
|
||||
cert, roots := testCertificate(t, true)
|
||||
joined := make(chan struct{})
|
||||
closed := make(chan struct{})
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
reader := relayHandshake(t, conn, controller)
|
||||
if reader == nil {
|
||||
return
|
||||
}
|
||||
close(joined)
|
||||
_, _ = reader.ReadByte()
|
||||
close(closed)
|
||||
})
|
||||
e.roots = roots
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
conn, _, err := connect(ctx, e, controller, "synthetic-fixture")
|
||||
if conn != nil {
|
||||
conn.close()
|
||||
}
|
||||
result <- err
|
||||
}()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("join did not start")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-result:
|
||||
if err == nil {
|
||||
t.Fatal("canceled join succeeded")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("join did not cancel")
|
||||
}
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("join left connection open")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelDuringTLSHandshake(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
accepted := make(chan net.Conn, 1)
|
||||
go func() {
|
||||
conn, err := listener.Accept()
|
||||
if err == nil {
|
||||
accepted <- conn
|
||||
}
|
||||
}()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
conn, _, err := connect(ctx, endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port}, controller, "synthetic-fixture")
|
||||
if conn != nil {
|
||||
conn.close()
|
||||
}
|
||||
result <- err
|
||||
}()
|
||||
select {
|
||||
case conn := <-accepted:
|
||||
defer conn.Close()
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("dial did not reach relay")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-result:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("handshake cancellation: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("TLS handshake did not cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadDeadlineClosesTransport(t *testing.T) {
|
||||
left, right := net.Pipe()
|
||||
defer right.Close()
|
||||
conn := newRelayConn(context.Background(), left)
|
||||
defer conn.close()
|
||||
if _, err := conn.readUntil(time.Now().Add(-time.Second)); !errors.Is(err, errTimeout) {
|
||||
t.Fatalf("read timeout: %v", err)
|
||||
}
|
||||
if conn.ctx.Err() == nil {
|
||||
t.Fatal("expired read left transport active")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanceledLifetimeRejectsBufferedFrames(t *testing.T) {
|
||||
left, right := net.Pipe()
|
||||
defer right.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
conn := newRelayConn(ctx, left)
|
||||
defer conn.close()
|
||||
go func() { _, _ = io.WriteString(right, "{\"type\":\"cancel\"}\n{\"type\":\"cancel\"}\n") }()
|
||||
if _, err := conn.read(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancel()
|
||||
if _, err := conn.read(); !errors.Is(err, errClosed) {
|
||||
t.Fatalf("buffered frame survived cancellation: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type shortWriteConn struct{ net.Conn }
|
||||
|
||||
func (c shortWriteConn) Write(p []byte) (int, error) {
|
||||
if len(p) > 3 {
|
||||
p = p[:3]
|
||||
}
|
||||
return c.Conn.Write(p)
|
||||
}
|
||||
|
||||
func TestShortWritesPreserveFrame(t *testing.T) {
|
||||
left, right := net.Pipe()
|
||||
defer right.Close()
|
||||
conn := newRelayConn(context.Background(), shortWriteConn{left})
|
||||
defer conn.close()
|
||||
result := make(chan error, 1)
|
||||
go func() { result <- conn.write(context.Background(), []byte("{\"type\":\"cancel\"}\n")) }()
|
||||
_ = right.SetReadDeadline(time.Now().Add(time.Second))
|
||||
frame, err := readFrame(bufio.NewReader(right))
|
||||
if err != nil || string(frame) != `{"type":"cancel"}` {
|
||||
t.Fatalf("short write: %q %v", frame, err)
|
||||
}
|
||||
if err := <-result; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportCancellationAndFraming(t *testing.T) {
|
||||
for _, fragment := range []string{"", `{"type":"cancel"`, strings.Repeat("x", maxRelayFrame+4096)} {
|
||||
left, right := net.Pipe()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
conn := newRelayConn(ctx, left)
|
||||
result := make(chan error, 1)
|
||||
go func() { _, err := conn.read(); result <- err }()
|
||||
if fragment != "" {
|
||||
go func() { _, _ = io.WriteString(right, fragment); _ = right.Close() }()
|
||||
} else {
|
||||
cancel()
|
||||
}
|
||||
select {
|
||||
case err := <-result:
|
||||
if err == nil {
|
||||
t.Fatal("accepted partial/oversized/canceled read")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("read remained blocked")
|
||||
}
|
||||
cancel()
|
||||
conn.close()
|
||||
_ = right.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportSerializesConcurrentWriters(t *testing.T) {
|
||||
left, right := net.Pipe()
|
||||
defer right.Close()
|
||||
conn := newRelayConn(context.Background(), left)
|
||||
defer conn.close()
|
||||
const count = 16
|
||||
result := make(chan error, count)
|
||||
for i := range count {
|
||||
go func() {
|
||||
frame, err := encodeMessage("key", keyTransition{VK: i + 1, Pressed: true})
|
||||
if err == nil {
|
||||
err = conn.write(context.Background(), frame)
|
||||
}
|
||||
result <- err
|
||||
}()
|
||||
}
|
||||
reader := bufio.NewReader(right)
|
||||
seen := map[int]bool{}
|
||||
_ = right.SetReadDeadline(time.Now().Add(3 * time.Second))
|
||||
for range count {
|
||||
frame, err := readFrame(reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m, err := decodeMessage(frame)
|
||||
if err != nil {
|
||||
t.Fatal("interleaved frames")
|
||||
}
|
||||
seen[m.payload.(keyTransition).VK] = true
|
||||
}
|
||||
for range count {
|
||||
if err := <-result; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if len(seen) != count {
|
||||
t.Fatal("lost writes")
|
||||
}
|
||||
conn.mu.Lock()
|
||||
defer conn.mu.Unlock()
|
||||
if conn.pending != 0 || conn.bytes != 0 {
|
||||
t.Fatalf("write accounting leak: %d %d", conn.pending, conn.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
type blockedWriteConn struct {
|
||||
net.Conn
|
||||
entered chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (c *blockedWriteConn) Write(p []byte) (int, error) {
|
||||
c.once.Do(func() { close(c.entered) })
|
||||
return c.Conn.Write(p)
|
||||
}
|
||||
|
||||
func TestBlockedWriterCancellationAndOverflow(t *testing.T) {
|
||||
for _, mode := range []string{"cancel", "bytes", "operations"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
left, right := net.Pipe()
|
||||
defer right.Close()
|
||||
entered := make(chan struct{})
|
||||
conn := newRelayConn(context.Background(), &blockedWriteConn{Conn: left, entered: entered})
|
||||
defer conn.close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
result := make(chan error, 1)
|
||||
go func() { result <- conn.write(ctx, []byte("blocked\n")) }()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("writer did not start")
|
||||
}
|
||||
switch mode {
|
||||
case "cancel":
|
||||
cancel()
|
||||
case "bytes":
|
||||
if err := conn.write(context.Background(), make([]byte, maxQueuedBytes)); !errors.Is(err, errLimit) {
|
||||
t.Fatal("byte ceiling did not fail closed")
|
||||
}
|
||||
case "operations":
|
||||
// Reserve the remaining queue slots without scheduling dependence.
|
||||
conn.mu.Lock()
|
||||
conn.pending = maxPendingWrites
|
||||
conn.mu.Unlock()
|
||||
if err := conn.write(context.Background(), []byte("next\n")); !errors.Is(err, errLimit) {
|
||||
t.Fatal("operation ceiling did not fail closed")
|
||||
}
|
||||
}
|
||||
select {
|
||||
case err := <-result:
|
||||
if err == nil {
|
||||
t.Fatal("blocked write succeeded")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cleanup blocked behind writer")
|
||||
}
|
||||
if conn.ctx.Err() == nil {
|
||||
t.Fatal("transport remained active")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelKeysAndEndpointValidation(t *testing.T) {
|
||||
a, err := generateChannelKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := generateChannelKey()
|
||||
if err != nil || len(a) != 64 || len(b) != 64 || a == b {
|
||||
t.Fatal("invalid random keys")
|
||||
}
|
||||
for _, host := range []string{"", "relay:6837", "https://relay", "user@relay", "relay/path", "relay\n", "[::1]"} {
|
||||
if _, err := (endpoint{host: host, port: 6837}).tlsConfig(); err == nil {
|
||||
t.Errorf("accepted endpoint %q", host)
|
||||
}
|
||||
}
|
||||
if _, err := (endpoint{host: "::1", port: 6837}).tlsConfig(); err != nil {
|
||||
t.Fatal("bare IPv6 rejected")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user