Continue work on Cthulhu Remote.

This commit is contained in:
Storm Dragon committed 2026-11-03 23:49:44 -05:00
1 parent 63e84e9ac7
commit 0c74038c49
16 files changed
+2896 -30

No files matched your search

+281
View File
@@ -0,0 +1,281 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"bytes"
"context"
"encoding/json"
"io"
"net"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"testing"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
// A test-only executable peer. The parent supplies synthetic approval over real
// SDK process pipes; no production command can instantiate this workflow yet.
func TestConnectionWorkflowSDKPeer(t *testing.T) {
if os.Args[len(os.Args)-1] != "remote-workflow-peer" {
return
}
host, portText, err := net.SplitHostPort(os.Getenv("CTHULHU_REMOTE_TEST_ADDRESS"))
port, portErr := strconv.Atoi(portText)
if err != nil || portErr != nil || host != "127.0.0.1" {
os.Exit(2)
}
store, err := openSettingsStore(os.Getenv("CTHULHU_REMOTE_TEST_STORE"))
if err != nil {
os.Exit(2)
}
client := sdk.NewSessionClient()
c := newCoordinator(context.Background(), client)
var workflow *connectionWorkflow
var mu sync.Mutex
commands := []sdk.Command{
{ID: "remote-test-open", Title: "Private Remote workflow", Presentation: true, Interaction: true,
Handle: func(ctx context.Context, _ json.RawMessage) (any, error) {
mu.Lock()
defer mu.Unlock()
select {
case action := <-c.actions:
var err error
workflow, err = new_connection_workflow(c.ctx, c, action, endpoint{host: host, port: port}, store)
if err != nil {
return nil, err
}
return workflow.form(), nil
case <-ctx.Done():
return nil, ctx.Err()
}
}},
{ID: "remote-connection", Title: "Private Remote continuation", Presentation: true, Interaction: true,
Handle: func(ctx context.Context, data json.RawMessage) (any, error) {
mu.Lock()
defer mu.Unlock()
var submission sdk.Submission
if workflow == nil || json.Unmarshal(data, &submission) != nil {
return nil, sdk.ErrProtocol
}
return workflow.submit(ctx, submission)
}},
}
err = sdk.ServeSession(os.Stdin, os.Stdout, commands, nil, client)
barrier := c.disconnect()
c.close()
<-barrier
<-c.done
mu.Lock()
if workflow != nil {
workflow.close()
<-workflow.done
}
mu.Unlock()
store.close()
if err != nil {
os.Exit(1)
}
os.Exit(0)
}
func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
certificate, _ := testCertificate(t, false)
probed := make(chan struct{})
joined := make(chan struct{})
var serverMu sync.Mutex
connections := 0
target := testRelay(t, certificate, func(connection net.Conn) {
serverMu.Lock()
connections++
count := connections
serverMu.Unlock()
if count == 1 {
data, _ := io.ReadAll(connection)
if len(data) != 0 {
t.Error("process certificate inspection sent application data")
}
close(probed)
return
}
if relayHandshake(t, connection, controller) == nil {
return
}
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
close(joined)
_, _ = io.Copy(io.Discard, connection)
})
testBinary, err := os.Executable()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
defer cancel()
process := exec.CommandContext(ctx, testBinary, "-test.run=^TestConnectionWorkflowSDKPeer$", "--", "remote-workflow-peer")
process.Env = append(os.Environ(),
"CTHULHU_REMOTE_TEST_ADDRESS="+net.JoinHostPort(target.host, strconv.Itoa(target.port)),
"CTHULHU_REMOTE_TEST_STORE="+t.TempDir()+"/remote")
var stderr bytes.Buffer
process.Stderr = &stderr
input, err := process.StdinPipe()
if err != nil {
t.Fatal(err)
}
output, err := process.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err := process.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
input.Close()
process.Process.Kill()
process.Wait()
})
var writerMu sync.Mutex
send := func(value any) error {
writerMu.Lock()
defer writerMu.Unlock()
return json.NewEncoder(input).Encode(value)
}
replies := make(chan json.RawMessage, 16)
leaseCalls := make(chan string, 16)
hostDone := make(chan struct{})
go func() {
defer close(hostDone)
defer close(replies)
decoder := json.NewDecoder(output)
for {
var frame struct {
ID string `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
Result json.RawMessage `json:"result"`
Error json.RawMessage `json:"error"`
}
if decoder.Decode(&frame) != nil {
return
}
if frame.Method == "" {
if len(frame.Error) != 0 {
t.Error("SDK command returned an error")
}
replies <- frame.Result
continue
}
leaseCalls <- frame.Method
result := any(struct{}{})
if frame.Method == "remote.open" {
var open sdk.RemoteOpen
if json.Unmarshal(frame.Params, &open) != nil || open.Epoch != 1 || open.Role != "controller" {
t.Error("invalid SDK lease request")
return
}
result = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: open.Epoch}
}
if send(map[string]any{"jsonrpc": "2.0", "id": frame.ID, "result": result}) != nil {
return
}
}
}()
nextReply := func() json.RawMessage {
t.Helper()
select {
case reply, ok := <-replies:
if !ok {
t.Fatal("SDK process stopped before its reply")
}
return reply
case <-ctx.Done():
t.Fatal("SDK workflow timed out")
return nil
}
}
if err := send(map[string]any{"jsonrpc": "2.0", "id": "1", "method": "initialize", "params": map[string]any{
"protocol": map[string]int{"major": 1, "minor": 1}, "session": "fixture",
"apis": []string{"commands", "presentation", "interaction", "session-events", "remote-access"},
"capabilities": []string{"presentation", "interaction", "remote-present"},
}}); err != nil {
t.Fatal(err)
}
var registration struct {
Commands []sdk.Command `json:"commands"`
}
if json.Unmarshal(nextReply(), &registration) != nil || len(registration.Commands) != 2 {
t.Fatal("missing SDK workflow registration")
}
if err := send(map[string]any{"jsonrpc": "2.0", "method": "initialized", "params": map[string]string{"session": "fixture"}}); err != nil {
t.Fatal(err)
}
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": sdk.SessionEvent{
Kind: "remote.action", Sequence: 1, Epoch: 1, Action: strings.Repeat("a", 32), Role: "controller", Grants: []string{"remote-present"},
}}); err != nil {
t.Fatal(err)
}
id := 1
invoke := func(command, activated, key string) sdk.Interaction {
t.Helper()
id++
if err := send(map[string]any{"jsonrpc": "2.0", "id": strconv.Itoa(id), "method": "command.invoke", "params": map[string]any{
"command": command, "arguments": sdk.Submission{Activated: activated, Values: map[string]sdk.Value{"channel-key": {Text: key}}},
}}); err != nil {
t.Fatal(err)
}
var result sdk.Interaction
if json.Unmarshal(nextReply(), &result) != nil {
t.Fatal("invalid SDK interaction result")
}
assertSecretAbsent(t, result, "synthetic-fixture")
return result
}
if result := invoke("remote-test-open", "", ""); result.Form == nil || result.Form.Title != "Connect Remote relay" {
t.Fatal("SDK did not open connection controls")
}
invoke("remote-connection", "saved-key-actions", "")
invoke("remote-connection", "remember-key", "synthetic-fixture")
invoke("remote-connection", "inspect-certificate", "")
awaitDone(t, probed)
for result := invoke("remote-connection", "refresh", ""); result.Form.Title != "Review Remote relay certificate"; result = invoke("remote-connection", "refresh", "") {
if ctx.Err() != nil {
t.Fatal("SDK did not present inspected certificate")
}
time.Sleep(time.Millisecond)
}
if result := invoke("remote-connection", "copy-fingerprint", ""); result.Clipboard == nil {
t.Fatal("SDK lost explicit fingerprint copy")
}
invoke("remote-connection", "trust-once", "")
invoke("remote-connection", "load-key", "")
select {
case method := <-leaseCalls:
t.Fatal("SDK opened a lease before explicit Connect", method)
default:
}
invoke("remote-connection", "connect", "")
awaitDone(t, joined)
invoke("remote-connection", "disconnect", "")
for _, expected := range []string{"remote.open", "remote.close"} {
select {
case method := <-leaseCalls:
if method != expected {
t.Fatal("unexpected lease operation", method)
}
case <-ctx.Done():
t.Fatal("missing lease operation", expected)
}
}
if result := invoke("remote-connection", "cancel", ""); !result.Done {
t.Fatal("SDK did not close the workflow")
}
input.Close()
awaitDone(t, hostDone)
if err := process.Wait(); err != nil {
t.Fatalf("SDK workflow process failed: %v\n%s", err, stderr.String())
}
}
+317
View File
@@ -0,0 +1,317 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"errors"
"net"
"strconv"
"sync"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
// connectionWorkflow joins the library forms and coordinator for one selected
// endpoint and reader action. It is NOT a local-origin authorizer. Production
// registration still requires reader-owned consent and trusted submissions.
// The owner must cancel ctx on form closure, lock/handoff or process retirement.
type connectionWorkflow struct {
mu sync.Mutex
ctx context.Context
cancel context.CancelFunc
done chan struct{}
setupCtx context.Context
owner *coordinator
action sdk.SessionEvent
target endpoint
store *settingsStore
mode string // credentials, inspecting, certificate, saved-key, status, finished
notice string
key string // Explicitly loaded only; never placed back into a form.
review *certificateReview
keys *keyActions
probeDone chan struct{}
}
func new_connection_workflow(ctx context.Context, owner *coordinator, action sdk.SessionEvent, target endpoint, store *settingsStore) (*connectionWorkflow, error) {
if _, err := target.tlsConfig(); err != nil {
return nil, err
}
if ctx.Err() != nil {
return nil, errLease
}
approval, setupCtx, err := owner.claim_approval(action)
if err != nil {
return nil, errLease
}
if target.pin != nil {
pin := *target.pin
target.pin = &pin
}
if target.roots != nil {
target.roots = target.roots.Clone()
}
lifetime, cancel := context.WithCancel(owner.ctx)
w := &connectionWorkflow{ctx: lifetime, cancel: cancel, done: make(chan struct{}), setupCtx: setupCtx,
owner: owner, action: approval, target: target, store: store, mode: "credentials"}
stopParent := context.AfterFunc(ctx, cancel)
go func() {
defer close(w.done)
defer stopParent()
select {
case <-setupCtx.Done():
w.mu.Lock()
// connect consumes setup approval while holding this same mutex;
// only its status controls may outlive that consumption.
if w.mode != "status" {
w.finish_locked()
}
w.mu.Unlock()
case <-lifetime.Done():
}
<-lifetime.Done()
w.mu.Lock()
w.finish_locked()
probeDone := w.probeDone
w.mu.Unlock()
if probeDone != nil {
<-probeDone
}
}()
return w, nil
}
func (w *connectionWorkflow) finish_locked() {
w.mode, w.key, w.review, w.keys = "finished", "", nil, nil
w.target.pin = nil
w.cancel()
w.owner.disconnect_epoch(w.action.Epoch)
}
func (w *connectionWorkflow) close() { w.cancel() }
func (w *connectionWorkflow) form() sdk.Interaction {
w.mu.Lock()
defer w.mu.Unlock()
return w.form_locked()
}
func (w *connectionWorkflow) form_locked() sdk.Interaction {
var result sdk.Interaction
address := net.JoinHostPort(w.target.host, strconv.Itoa(w.target.port))
details := sdk.Element{ID: "details", Label: "Connection details", Kind: sdk.List, Items: []sdk.ListItem{
{ID: "endpoint", Label: "Relay: " + address},
{ID: "role", Label: "Approved role: " + w.action.Role},
{ID: "privacy", Label: "The relay can read the channel key and session contents. A channel key does not verify the other person's identity."},
{ID: "scope", Label: "Relay testing only. Speech, keyboard, clipboard transfer and Braille services are unavailable."},
}}
switch w.mode {
case "credentials":
trust := "Normal certificate and hostname validation."
if w.target.pin != nil {
trust = "An explicitly approved certificate pin is required for this relay."
}
details.Items = append(details.Items, sdk.ListItem{ID: "trust", Label: trust})
if w.key != "" {
details.Items = append(details.Items, sdk.ListItem{ID: "loaded-key", Label: "A saved key was explicitly loaded. Leave Channel key empty to use it, or enter a replacement for this attempt."})
}
elements := []sdk.Element{details,
{ID: "channel-key", Label: "Channel key", Kind: sdk.Entry, Secret: true, MaxLength: 512},
{ID: "connect", Label: "Connect relay", Kind: sdk.Button},
{ID: "inspect-certificate", Label: "Inspect relay certificate", Kind: sdk.Button},
}
if w.store != nil {
elements = append(elements,
sdk.Element{ID: "load-key", Label: "Use saved key", Kind: sdk.Button},
sdk.Element{ID: "saved-key-actions", Label: "Remember or forget a key", Kind: sdk.Button})
}
elements = append(elements, sdk.Element{ID: "cancel", Label: "Cancel", Kind: sdk.Button})
result.Form = &sdk.Form{Title: "Connect Remote relay", Elements: elements}
case "inspecting":
details.Items = append(details.Items, sdk.ListItem{ID: "inspection", Label: "Inspecting the certificate without sending a channel key. No connection will start automatically."})
result.Form = &sdk.Form{Title: "Inspecting Remote certificate", Elements: []sdk.Element{details,
{ID: "refresh", Label: "Refresh inspection status", Kind: sdk.Button},
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
}}
case "certificate":
result = w.review.form()
case "saved-key":
result = w.keys.form()
case "status":
status := w.owner.snapshot()
text := "This connection attempt has ended. Fresh local approval is required to connect again."
if status.epoch == w.action.Epoch {
text = connection_status_text(status)
}
details.Items = append(details.Items, sdk.ListItem{ID: "status", Label: text})
result.Form = &sdk.Form{Title: "Remote relay status", Elements: []sdk.Element{details,
{ID: "refresh", Label: "Refresh connection status", Kind: sdk.Button},
{ID: "disconnect", Label: "Disconnect", Kind: sdk.Button},
{ID: "cancel", Label: "Disconnect and close", Kind: sdk.Button},
}}
default:
return security_message("Remote connection workflow closed.")
}
// Nested forms always return through this instance's owner, never through
// the standalone handlers or a newly selected endpoint.
result.Next = "remote-connection"
if w.notice != "" {
result.Presentation = security_message(w.notice).Presentation
}
return result
}
func connection_status_text(status connectionStatus) string {
switch status.state {
case "opening":
return "Requesting the reader lease."
case "connecting":
return "Connecting and authenticating the relay."
case "waiting":
return "Connected to the relay; waiting for one opposite-role peer. Desktop services are unavailable."
case "ready":
return "One opposite-role peer has joined. Desktop services are unavailable."
case "stopping":
return "Disconnecting and releasing the reader lease."
case "failed":
switch {
case errors.Is(status.err, errTrust):
return "Certificate verification failed. No channel key was sent. A fresh local connection action is required; certificate inspection is never automatic."
case errors.Is(status.err, errLease):
return "Reader approval is unavailable or was revoked. Fresh local approval is required."
default:
return "Relay connection failed or the peer changed. Fresh local approval is required."
}
default:
return "Disconnected. Fresh local approval is required to connect again."
}
}
// Inspection is explicit and runs outside the command deadline. Only Refresh
// presents its result; neither completion nor Trust once starts a connection.
func (w *connectionWorkflow) inspect_locked() {
w.key, w.notice, w.mode = "", "", "inspecting"
done := make(chan struct{})
w.probeDone = done
probeCtx, cancel := context.WithCancel(w.setupCtx)
stop := context.AfterFunc(w.ctx, cancel)
target := w.target
go func() {
defer close(done)
defer cancel()
defer stop()
review, err := probe_certificate(probeCtx, target)
w.mu.Lock()
defer w.mu.Unlock()
if w.mode != "inspecting" || w.ctx.Err() != nil || w.setupCtx.Err() != nil {
return
}
if err != nil {
w.mode, w.notice = "credentials", "Certificate inspection failed. No trust was changed and no channel key was sent."
return
}
// The probe's short-lived context ends here. The review belongs to the
// still-pending approval and workflow, not the worker/command lifetime.
review.lifetime = w.setupCtx
w.review, w.mode = review, "certificate"
}()
}
func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (sdk.Interaction, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.ctx.Err() != nil || ctx.Err() != nil || w.mode == "finished" || w.mode != "status" && w.setupCtx.Err() != nil {
w.finish_locked()
return security_message("Remote connection approval ended. Start a fresh local connection action."), nil
}
if value.Cancelled {
w.finish_locked()
return w.form_locked(), nil
}
w.notice = ""
if value.Activated == "cancel" && w.mode != "certificate" && w.mode != "saved-key" {
w.finish_locked()
return w.form_locked(), nil
}
switch w.mode {
case "credentials":
switch value.Activated {
case "connect":
key := value.Values["channel-key"].Text
if key == "" {
key = w.key
}
if !validChannelKey(key) {
w.notice = "Enter a valid channel key or explicitly load a saved key."
break
}
err := w.owner.connect(w.action, w.target, key)
w.key = ""
w.target.pin = nil
if err != nil {
w.finish_locked()
return security_message("The connection could not start. Fresh local approval is required."), nil
}
w.mode = "status"
case "load-key":
w.key = ""
if w.store == nil {
break
}
key, err := w.store.loadKey(w.target)
if err != nil {
w.notice = "The saved channel key could not be loaded."
} else if key == "" {
w.notice = "No saved key is available for this relay."
} else {
w.key, w.notice = key, "Saved key loaded for this relay. Choose Connect relay to use it."
}
case "inspect-certificate":
w.inspect_locked()
case "saved-key-actions":
w.key = ""
if w.store == nil {
break
}
keys, err := new_key_actions(w.setupCtx, w.target, w.store)
if err != nil {
w.notice = "Saved-key actions are unavailable."
} else {
w.keys, w.mode = keys, "saved-key"
}
}
case "certificate":
approved, result, err := w.review.submit(ctx, value)
if err != nil || result.Done {
w.review, w.mode = nil, "credentials"
w.notice = result.Speech
if err != nil {
w.notice = "Certificate review ended without approval."
} else if approved.host != "" {
w.target = approved
w.notice = "Certificate approved for this attempt only. Enter a channel key and choose Connect relay."
}
} else {
result.Next = "remote-connection"
return result, nil
}
case "saved-key":
result, err := w.keys.submit(ctx, value)
if err != nil || result.Done {
w.keys, w.mode = nil, "credentials"
w.notice = result.Speech
if err != nil {
w.notice = "Saved-key action ended."
}
} else {
result.Next = "remote-connection"
return result, nil
}
case "status":
if value.Activated == "disconnect" {
w.owner.disconnect_epoch(w.action.Epoch)
}
}
return w.form_locked(), nil
}
+361
View File
@@ -0,0 +1,361 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"crypto/sha256"
"encoding/json"
"io"
"net"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func workflowFixture(t *testing.T, c *coordinator, action sdk.SessionEvent, target endpoint, store *settingsStore) *connectionWorkflow {
t.Helper()
w, err := new_connection_workflow(t.Context(), c, action, target, store)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { w.close(); awaitDone(t, w.done) })
return w
}
func workflowSubmit(t *testing.T, w *connectionWorkflow, activated, key string) sdk.Interaction {
t.Helper()
result, err := w.submit(t.Context(), sdk.Submission{Activated: activated, Values: map[string]sdk.Value{"channel-key": {Text: key}}})
if err != nil {
t.Fatal(err)
}
return result
}
func assertSecretAbsent(t *testing.T, result sdk.Interaction, secret string) {
t.Helper()
encoded, err := json.Marshal(result)
if err != nil || strings.Contains(string(encoded), secret) {
t.Fatal("response contains a channel key or could not be encoded")
}
if result.Form != nil {
for _, element := range result.Form.Elements {
if element.ID == "channel-key" && (!element.Secret || element.Text != "") {
t.Fatal("channel-key entry is unmasked or prefilled")
}
}
}
}
func TestConnectionWorkflowBindsReaderActionAndFreezesTrust(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
target := endpoint{host: "relay.invalid", port: 6837}
if _, err := new_connection_workflow(t.Context(), c, sdk.SessionEvent{}, target, nil); err != errLease {
t.Fatal("setup without a reader action", err)
}
action := approve(t, c, f, 1, "controller")
pin := &certificatePin{host: target.host, port: target.port, sha256: [32]byte{1}}
target.pin = pin
action.Role, action.Grants[0] = "controlled", "keyboard-inject"
w := workflowFixture(t, c, action, target, nil)
pin.sha256 = [32]byte{2}
if w.action.Role != "controller" || w.action.Grants[0] != "remote-present" || w.target.pin.sha256 != [32]byte{1} {
t.Fatal("caller changed the selected role, grants or certificate")
}
if _, err := new_connection_workflow(t.Context(), c, action, target, nil); err != errLease {
t.Fatal("multiple workflows claimed one action", err)
}
result := w.form()
encoded, _ := json.Marshal(result)
if result.Form == nil || result.Next != "remote-connection" || !strings.Contains(string(encoded), "services are unavailable") {
t.Fatal("missing form, continuation or service limitation")
}
workflowSubmit(t, w, "connect", strings.Repeat("猫", 200))
select {
case call := <-f.calls:
t.Fatal("invalid key started a connection", call.method)
default:
}
}
func TestConnectionWorkflowSavedKeyIsLoadedOnlyExplicitly(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
store, path, value := settingsFixture(t)
target, _ := value.endpoint()
key := "synthetic-saved-private-key"
if err := store.rememberKey(target, key); err != nil {
t.Fatal(err)
}
w := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, store)
assertSecretAbsent(t, w.form(), key)
if w.key != "" {
t.Fatal("opening a form loaded credentials")
}
result := workflowSubmit(t, w, "load-key", "ignored-private-entry")
assertSecretAbsent(t, result, key)
assertSecretAbsent(t, result, "ignored-private-entry")
if w.key != key || result.Clipboard != nil {
t.Fatal("explicit load failed or requested clipboard access")
}
select {
case call := <-f.calls:
t.Fatal("loading a key connected", call.method)
default:
}
// Forget through the nested workflow clears the in-memory selection too.
workflowSubmit(t, w, "saved-key-actions", "")
result = workflowSubmit(t, w, "forget-key", "")
assertSecretAbsent(t, result, key)
if w.key != "" || w.mode != "credentials" {
t.Fatal("Forget retained the loaded key or failed to return to Connect")
}
if _, err := os.Stat(filepath.Join(path, "channel-key.toml")); !os.IsNotExist(err) {
t.Fatal("Forget did not remove the saved key")
}
workflowSubmit(t, w, "load-key", "")
if w.key != "" {
t.Fatal("missing key was reported as loaded")
}
}
func TestConnectionWorkflowConnectUsesLoadedKeyWithoutEcho(t *testing.T) {
for _, roleName := range []string{"controller", "controlled"} {
t.Run(roleName, func(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
certificate, roots := testCertificate(t, true)
r := controller
if roleName == "controlled" {
r = controlled
}
joined := make(chan struct{})
target := testRelay(t, certificate, func(connection net.Conn) {
if relayHandshake(t, connection, r) == nil {
return
}
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
close(joined)
_, _ = io.Copy(io.Discard, connection)
})
target.roots = roots
store, _, _ := settingsFixture(t)
if err := store.rememberKey(target, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
w := workflowFixture(t, c, approve(t, c, f, 1, roleName), target, store)
workflowSubmit(t, w, "load-key", "")
result := workflowSubmit(t, w, "connect", "")
assertSecretAbsent(t, result, "synthetic-fixture")
awaitDone(t, joined)
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" })
result = workflowSubmit(t, w, "refresh", "")
encoded, _ := json.Marshal(result)
if !strings.Contains(string(encoded), "waiting for one opposite-role peer") || !strings.Contains(string(encoded), "Desktop services are unavailable") {
t.Fatal("status advertised desktop control or omitted waiting state")
}
if w.key != "" {
t.Fatal("connect retained a saved key")
}
workflowSubmit(t, w, "connect", "synthetic-second-attempt") // Old duplicate submission.
workflowSubmit(t, w, "disconnect", "")
nextCall(t, f, "remote.close")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "closed" })
select {
case call := <-f.calls:
t.Fatal("duplicate Connect reused approval", call.method)
default:
}
})
}
}
func TestConnectionWorkflowLoadEndpointMismatchAndFailure(t *testing.T) {
for _, mode := range []string{"other endpoint", "unsafe credential", "closed store"} {
t.Run(mode, func(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
store, path, value := settingsFixture(t)
target, _ := value.endpoint()
if err := store.rememberKey(target, "synthetic-private-key"); err != nil {
t.Fatal(err)
}
switch mode {
case "other endpoint":
target.host = "other.invalid"
case "unsafe credential":
if err := os.Chmod(filepath.Join(path, "channel-key.toml"), 0644); err != nil {
t.Fatal(err)
}
case "closed store":
store.close()
}
w := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, store)
result := workflowSubmit(t, w, "load-key", "")
assertSecretAbsent(t, result, "synthetic-private-key")
if w.key != "" || result.Speech == "" {
t.Fatal("load failed silently or crossed endpoint/permission boundary")
}
})
}
}
func TestConnectionWorkflowInspectionRequiresExplicitConnect(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
certificate, _ := testCertificate(t, false)
var connections atomic.Int32
probeBytes := make(chan int, 1)
target := testRelay(t, certificate, func(connection net.Conn) {
if connections.Add(1) == 1 {
data, _ := io.ReadAll(connection)
probeBytes <- len(data)
return
}
if relayHandshake(t, connection, controller) == nil {
return
}
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
_, _ = io.Copy(io.Discard, connection)
})
w := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, nil)
result := workflowSubmit(t, w, "inspect-certificate", "must-not-survive-inspection")
assertSecretAbsent(t, result, "must-not-survive-inspection")
awaitDone(t, w.probeDone)
select {
case count := <-probeBytes:
if count != 0 {
t.Fatal("inspection sent a channel key")
}
case <-time.After(time.Second):
t.Fatal("inspection did not close")
}
result = workflowSubmit(t, w, "copy-fingerprint", "")
digest := sha256.Sum256(certificate.Certificate[0])
if result.Clipboard == nil || len(*result.Clipboard) != 64 || w.target.pin != nil || result.Next != "remote-connection" {
t.Fatal("copy approved trust or lost continuation")
}
result = workflowSubmit(t, w, "trust-once", "")
if w.target.pin == nil || w.target.pin.sha256 != digest || result.Form == nil || w.mode != "credentials" {
t.Fatal("review did not return to explicit Connect")
}
if connections.Load() != 1 {
t.Fatal("trust action automatically connected")
}
select {
case call := <-f.calls:
t.Fatal("trust action opened a lease", call.method)
default:
}
workflowSubmit(t, w, "connect", "synthetic-fixture")
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" })
if connections.Load() != 2 {
t.Fatal("Connect reused inspection socket")
}
}
func TestConnectionWorkflowStalledInspectionCancelledByLifecycle(t *testing.T) {
for _, mode := range []string{"form close", "parent cancel", "replacement", "SDK EOF"} {
t.Run(mode, func(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { listener.Close() })
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
w, err := new_connection_workflow(ctx, c, approve(t, c, f, 1, "controller"), endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port}, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { w.close(); awaitDone(t, w.done) })
workflowSubmit(t, w, "inspect-certificate", "")
connection, err := listener.Accept()
if err != nil {
t.Fatal(err)
}
defer connection.Close()
closed := make(chan struct{})
go func() { _, _ = io.Copy(io.Discard, connection); close(closed) }()
switch mode {
case "form close":
_, _ = w.submit(t.Context(), sdk.Submission{Cancelled: true})
case "parent cancel":
cancel()
case "replacement":
approve(t, c, f, 2, "controller")
case "SDK EOF":
close(f.events)
}
awaitDone(t, w.probeDone)
awaitDone(t, w.done)
awaitDone(t, closed)
if result := workflowSubmit(t, w, "trust-once", ""); !result.Done {
t.Fatal("retired inspection could be approved")
}
})
}
}
func TestConnectionWorkflowCancellationPreventsSavedKeyEffects(t *testing.T) {
for _, mode := range []string{"form", "handler", "replacement"} {
t.Run(mode, func(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
store, path, value := settingsFixture(t)
target, _ := value.endpoint()
w := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, store)
workflowSubmit(t, w, "saved-key-actions", "")
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
submission := sdk.Submission{Activated: "remember-key", Values: map[string]sdk.Value{"channel-key": {Text: "synthetic-private-key"}}}
switch mode {
case "form":
submission.Cancelled = true
case "handler":
cancel()
case "replacement":
approve(t, c, f, 2, "controller")
}
result, _ := w.submit(ctx, submission)
if !result.Done {
t.Fatal("cancelled action retained a form")
}
if _, err := os.Stat(filepath.Join(path, "channel-key.toml")); !os.IsNotExist(err) {
t.Fatal("cancelled workflow saved credentials")
}
})
}
}
func TestConnectionWorkflowOldStatusCannotDisconnectNewEpoch(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
certificate, roots := testCertificate(t, true)
target := testRelay(t, certificate, func(connection net.Conn) {
if relayHandshake(t, connection, controller) == nil {
return
}
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
_, _ = io.Copy(io.Discard, connection)
})
target.roots = roots
old := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, nil)
workflowSubmit(t, old, "connect", "synthetic-fixture")
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" })
fresh := approve(t, c, f, 2, "controller")
nextCall(t, f, "remote.close")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
w := workflowFixture(t, c, fresh, target, nil)
workflowSubmit(t, w, "connect", "synthetic-fixture")
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.epoch == 2 && s.state == "waiting" })
workflowSubmit(t, old, "disconnect", "")
workflowSubmit(t, old, "cancel", "")
if status := c.snapshot(); status.epoch != 2 || status.state != "waiting" {
t.Fatal("old status controls disconnected a new connection", status)
}
}
+372
View File
@@ -0,0 +1,372 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"errors"
"slices"
"sync"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
var errLease = errors.New("remote reader access unavailable or revoked")
// sessionClient is the public SDK boundary, also used by private fixtures. The
// coordinator must be the only Events consumer for the process session.
type sessionClient interface {
Call(context.Context, string, any, any) error
Events() <-chan sdk.SessionEvent
}
var _ sessionClient = (*sdk.SessionClient)(nil)
type connectionStatus struct {
state string // idle, opening, connecting, waiting, ready, stopping, closed, failed
epoch uint64
peer int
ignored uint64
err error // Local constant errors only; never RPC/server diagnostic text.
}
type connectionAttempt struct {
ctx context.Context
cancel context.CancelFunc
done chan struct{}
epoch uint64
err error // Protected by coordinator.mu.
}
// coordinator joins reader consent and relay lifetime; it performs no desktop
// effects. A fresh core action AND an explicit connect call are required for
// every attempt. It never loads credentials, saves trust, or retries a network.
type coordinator struct {
client sessionClient
ctx context.Context
cancel context.CancelFunc
done chan struct{}
actions chan sdk.SessionEvent
mu sync.Mutex
pending sdk.SessionEvent
pendingCtx context.Context
pendingStop context.CancelFunc
setupClaimed bool
active *connectionAttempt
status connectionStatus
unavailable bool // Failed close cannot be followed by another connection.
}
func newCoordinator(ctx context.Context, client sessionClient) *coordinator {
lifetime, cancel := context.WithCancel(ctx)
c := &coordinator{client: client, ctx: lifetime, cancel: cancel, done: make(chan struct{}), actions: make(chan sdk.SessionEvent, 1), status: connectionStatus{state: "idle"}}
go c.read_events()
return c
}
// actions carries approval metadata, not an instruction to connect. A newer
// action supersedes an unread one. Copy slices so callers cannot alter consent.
func (c *coordinator) read_events() {
defer close(c.done)
defer close(c.actions)
defer c.cancel()
defer func() {
c.mu.Lock()
c.unavailable = true
c.clear_pending_locked()
c.stop_locked(errLease)
c.mu.Unlock()
}()
for {
select {
case <-c.ctx.Done():
return
case event, ok := <-c.client.Events():
if !ok {
return
}
c.mu.Lock()
switch event.Kind {
case "remote.action":
c.stop_locked(errLease)
c.clear_pending_locked()
c.pending = event
c.pendingCtx, c.pendingStop = context.WithCancel(c.ctx)
c.pending.Grants = slices.Clone(event.Grants)
event.Grants = slices.Clone(event.Grants)
select {
case <-c.actions:
default:
}
c.actions <- event
case "remote.revoked":
if event.Epoch == c.pending.Epoch {
c.clear_pending_locked()
}
// Epoch matching also handles revoke racing remote.open's reply.
if c.active != nil && event.Epoch == c.active.epoch {
c.stop_locked(errLease)
}
}
c.mu.Unlock()
}
}
}
func (c *coordinator) snapshot() connectionStatus {
c.mu.Lock()
defer c.mu.Unlock()
return c.status
}
func (c *coordinator) clear_pending_locked() {
if c.pendingStop != nil {
c.pendingStop()
}
c.pending, c.pendingCtx, c.pendingStop = sdk.SessionEvent{}, nil, nil
c.setupClaimed = false
}
// claim_approval binds one setup workflow to an action received from the SDK.
// The lifetime ends on replacement, consumption, disconnect or session loss.
// Role/grants in the caller's copy are never authoritative.
func (c *coordinator) claim_approval(action sdk.SessionEvent) (sdk.SessionEvent, context.Context, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.ctx.Err() != nil || c.unavailable || c.active != nil || c.setupClaimed || c.pending.Action == "" || action.Action != c.pending.Action || action.Epoch != c.pending.Epoch {
return sdk.SessionEvent{}, nil, errLease
}
approval := c.pending
approval.Grants = slices.Clone(approval.Grants)
c.setupClaimed = true
return approval, c.pendingCtx, nil
}
// connect returns after scheduling bounded background work. Only a token from
// this SDK's event stream can consume pending approval; the stored role/grants
// are authoritative. endpoint already contains any explicit local trust choice.
func (c *coordinator) connect(action sdk.SessionEvent, e endpoint, key string) error {
if _, err := e.tlsConfig(); err != nil {
return err
}
if !validChannelKey(key) {
return errProtocol
}
// Freeze caller-owned TLS options before handing them to a worker.
if e.pin != nil {
pin := *e.pin
e.pin = &pin
}
if e.roots != nil {
e.roots = e.roots.Clone()
}
c.mu.Lock()
defer c.mu.Unlock()
if c.ctx.Err() != nil || c.unavailable || c.active != nil || c.pending.Action == "" || action.Action != c.pending.Action || action.Epoch != c.pending.Epoch {
return errLease
}
approval := c.pending
c.clear_pending_locked() // Single-use even if open or TLS fails.
ctx, cancel := context.WithCancel(c.ctx)
a := &connectionAttempt{ctx: ctx, cancel: cancel, done: make(chan struct{}), epoch: approval.Epoch}
c.active, c.status = a, connectionStatus{state: "opening", epoch: a.epoch}
go c.run(a, approval, e, key)
return nil
}
func (c *coordinator) stop_locked(err error) {
if c.active != nil {
if c.active.ctx.Err() == nil {
c.active.err = err
}
c.active.cancel() // Socket cancellation never waits for reader RPC cleanup.
c.status.state, c.status.peer = "stopping", 0
}
}
// disconnect starts immediate relay cancellation and returns a completion
// barrier. A new connection is refused until lease-close cleanup has finished.
func (c *coordinator) disconnect() <-chan struct{} {
c.mu.Lock()
defer c.mu.Unlock()
c.clear_pending_locked()
if c.active == nil {
done := make(chan struct{})
close(done)
return done
}
c.stop_locked(nil)
return c.active.done
}
// A stale form must never disconnect a newer approval or connection. Unlike
// disconnect, this operation retires only the workflow's original epoch.
func (c *coordinator) disconnect_epoch(epoch uint64) <-chan struct{} {
c.mu.Lock()
defer c.mu.Unlock()
if epoch != 0 && c.pending.Epoch == epoch {
c.clear_pending_locked()
}
if c.active != nil && c.active.epoch == epoch {
c.stop_locked(nil)
return c.active.done
}
done := make(chan struct{})
close(done)
return done
}
// close ends the event owner too. Callers may wait on done and disconnect's
// barrier before disposing the process session; neither path needs the relay.
func (c *coordinator) close() { c.cancel() }
func (c *coordinator) update(a *connectionAttempt, s *session) bool {
c.mu.Lock()
defer c.mu.Unlock()
if a.ctx.Err() != nil {
return false
}
c.status.state, c.status.peer, c.status.ignored = s.state, s.peer.ID, s.ignored
return true
}
// Never cancel a healthy SDK call just to disconnect the relay: SDK call
// cancellation deliberately retires the entire Tentacle process session. Calls
// finish within two seconds independently; all lease operations are serialized.
func (c *coordinator) call(method string, params, result any) error {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if c.client.Call(ctx, method, params, result) != nil {
return errLease
}
return nil
}
func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e endpoint, key string) {
var lease sdk.RemoteLease
var conn *relayConn
var sequence uint64
var heartbeatDone chan struct{}
var failure error
defer func() {
// Stop relay and heartbeat admission before serializing the final close.
c.mu.Lock()
c.stop_locked(failure)
c.mu.Unlock()
if conn != nil {
conn.close()
}
if heartbeatDone != nil {
<-heartbeatDone
}
closeFailed := false
if lease.Lease != "" {
sequence++
closeFailed = c.call("remote.close", sdk.RemoteOperation{Lease: lease.Lease, Epoch: a.epoch, Sequence: sequence}, nil) != nil
}
c.mu.Lock()
if a.err != nil {
failure = a.err
}
if closeFailed {
c.unavailable, failure = true, errLease
}
c.status.state, c.status.peer, c.status.err = "closed", 0, failure
if failure != nil {
c.status.state = "failed"
}
c.active = nil
close(a.done)
c.mu.Unlock()
}()
if a.ctx.Err() != nil {
return
}
if err := c.call("remote.open", sdk.RemoteOpen{Action: approval.Action, Epoch: approval.Epoch, Role: approval.Role, Grants: approval.Grants}, &lease); err != nil {
failure = err
return
}
if len(lease.Lease) != 32 || lease.Epoch != a.epoch {
failure = errLease
c.mu.Lock()
c.unavailable = true
c.mu.Unlock()
return
}
if a.ctx.Err() != nil {
return
}
r := controller
if approval.Role == "controlled" {
r = controlled
}
s, err := newSession(r, a.epoch)
if err != nil {
failure = err
return
}
c.mu.Lock()
if a.ctx.Err() == nil {
c.status.state = "connecting"
}
c.mu.Unlock()
heartbeatDone = make(chan struct{})
go func() {
defer close(heartbeatDone)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-a.ctx.Done():
return
case <-ticker.C:
if a.ctx.Err() != nil {
return
}
sequence++
if c.call("remote.heartbeat", sdk.RemoteOperation{Lease: lease.Lease, Epoch: a.epoch, Sequence: sequence}, nil) != nil {
c.mu.Lock()
c.stop_locked(errLease)
c.mu.Unlock()
return
}
}
}
}()
var joined message
conn, joined, failure = connect(a.ctx, e, r, key)
key = "" // Do not retain credentials for any reconnect path.
if failure != nil {
if a.ctx.Err() != nil {
failure = nil
}
return
}
if _, failure = s.accept(a.epoch, joined); failure != nil || !c.update(a, s) {
return
}
for a.ctx.Err() == nil {
m, err := conn.read()
if err != nil {
if a.ctx.Err() == nil {
failure = err
}
return
}
accepted, err := s.accept(a.epoch, m)
if err != nil {
failure = err
return
}
// Desktop services are not implemented. Retain no payload and expose no
// effect queue which could be mistaken for delivery-time authorization.
if accepted && s.ignored != ^uint64(0) {
s.ignored++
}
if !c.update(a, s) {
return
}
}
}
+500
View File
@@ -0,0 +1,500 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"bufio"
"context"
"crypto/tls"
"encoding/json"
"errors"
"io"
"net"
"strings"
"sync"
"testing"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
type readerCall struct {
method string
params any
}
type fixtureClient struct {
events chan sdk.SessionEvent
calls chan readerCall
hook func(context.Context, string, any, any) error
}
func (f *fixtureClient) Events() <-chan sdk.SessionEvent { return f.events }
func (f *fixtureClient) Call(ctx context.Context, method string, params, result any) error {
f.calls <- readerCall{method, params}
if f.hook != nil {
return f.hook(ctx, method, params, result)
}
if method == "remote.open" {
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: params.(sdk.RemoteOpen).Epoch}
}
return nil
}
func fixtureCoordinator(t *testing.T, hook func(context.Context, string, any, any) error) (*coordinator, *fixtureClient) {
t.Helper()
f := &fixtureClient{events: make(chan sdk.SessionEvent, 8), calls: make(chan readerCall, 32), hook: hook}
c := newCoordinator(t.Context(), f)
t.Cleanup(func() {
barrier := c.disconnect()
c.close()
awaitDone(t, barrier)
awaitDone(t, c.done)
})
return c, f
}
func awaitDone(t *testing.T, done <-chan struct{}) {
t.Helper()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("cleanup did not finish")
}
}
func nextCall(t *testing.T, f *fixtureClient, method string) readerCall {
t.Helper()
select {
case call := <-f.calls:
if call.method != method {
t.Fatalf("got %s, want %s", call.method, method)
}
return call
case <-time.After(4 * time.Second):
t.Fatalf("missing %s", method)
return readerCall{}
}
}
func approve(t *testing.T, c *coordinator, f *fixtureClient, epoch uint64, role string) sdk.SessionEvent {
t.Helper()
grant := "remote-present"
if role == "controlled" {
grant = "output-observe"
}
f.events <- sdk.SessionEvent{Sequence: epoch, Kind: "remote.action", Action: strings.Repeat("a", 32), Epoch: epoch, Role: role, Grants: []string{grant}}
select {
case event := <-c.actions:
return event
case <-time.After(time.Second):
t.Fatal("missing action")
return sdk.SessionEvent{}
}
}
func awaitStatus(t *testing.T, c *coordinator, predicate func(connectionStatus) bool) connectionStatus {
t.Helper()
deadline := time.NewTimer(4 * time.Second)
defer deadline.Stop()
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
for {
status := c.snapshot()
if predicate(status) {
return status
}
select {
case <-deadline.C:
t.Fatalf("unexpected status: %+v", status)
case <-ticker.C:
}
}
}
func TestCoordinatorRequiresFreshReaderAction(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
e := endpoint{host: "localhost", port: 6837}
if err := c.connect(sdk.SessionEvent{}, e, "synthetic-fixture"); err != errLease {
t.Fatal("connected without action", err)
}
action := approve(t, c, f, 1, "controller")
wrong := action
wrong.Epoch++
if err := c.connect(wrong, e, "synthetic-fixture"); err != errLease {
t.Fatal("accepted stale token", err)
}
awaitDone(t, c.disconnect())
if err := c.connect(action, e, "synthetic-fixture"); err != errLease {
t.Fatal("disconnect retained unused approval", err)
}
select {
case call := <-f.calls:
t.Fatal("unexpected reader request", call.method)
default:
}
}
func TestCoordinatorDenialMakesNoRelayConnection(t *testing.T) {
c, f := fixtureCoordinator(t, func(context.Context, string, any, any) error {
return errors.New("private RPC content must not escape")
})
action := approve(t, c, f, 1, "controller")
cert, _ := testCertificate(t, true)
connected := make(chan struct{}, 1)
e := testRelay(t, cert, func(net.Conn) { connected <- struct{}{} })
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
status := awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
if status.err != errLease {
t.Fatal("exposed upstream error", status.err)
}
if err := c.connect(action, e, "synthetic-fixture"); err != errLease {
t.Fatal("retried consumed consent", err)
}
select {
case <-connected:
t.Fatal("network before consent")
default:
}
}
func TestCoordinatorMembershipFailureAndExplicitReconnect(t *testing.T) {
cert, roots := testCertificate(t, true)
for _, roleName := range []string{"controller", "controlled"} {
t.Run(roleName, func(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
action := approve(t, c, f, 1, roleName)
depart := make(chan struct{})
var once sync.Once
t.Cleanup(func() { once.Do(func() { close(depart) }) })
r, peerRole, effect := controller, "slave", `{"type":"speak","origin":7,"sequence":["private fixture"]}`
if roleName == "controlled" {
r, peerRole, effect = controlled, "master", `{"type":"key","origin":7,"vk_code":65,"extended":false,"pressed":true}`
}
e := testRelay(t, cert, func(conn net.Conn) {
if relayHandshake(t, conn, r) == nil {
return
}
_, _ = io.WriteString(conn, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"`+peerRole+`"}]}`+"\n"+effect+"\n")
select {
case <-depart:
case <-time.After(5 * time.Second):
return
}
_, _ = io.WriteString(conn, "{\"type\":\"client_left\",\"user_id\":7}\n")
_, _ = io.Copy(io.Discard, conn)
})
e.roots = roots
// Caller mutation cannot change the role or approved grants.
action.Role, action.Grants[0] = "untrusted", "keyboard-inject"
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
open := nextCall(t, f, "remote.open").params.(sdk.RemoteOpen)
if open.Role != roleName || open.Grants[0] == "keyboard-inject" {
t.Fatal("caller changed approval")
}
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" && s.ignored == 1 })
if err := c.connect(action, e, "synthetic-fixture"); err != errLease {
t.Fatal("concurrent connect", err)
}
once.Do(func() { close(depart) })
closed := nextCall(t, f, "remote.close").params.(sdk.RemoteOperation)
if closed.Epoch != 1 || closed.Sequence != 1 {
t.Fatal("bad close ownership", closed)
}
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
if err := c.connect(action, e, "synthetic-fixture"); err != errLease {
t.Fatal("reconnected automatically", err)
}
fresh := approve(t, c, f, 2, roleName)
if err := c.connect(fresh, e, "synthetic-fixture"); err != nil {
t.Fatal("fresh local action refused", err)
}
nextCall(t, f, "remote.open")
nextCall(t, f, "remote.close")
})
}
}
func TestCoordinatorRevokedDuringOpen(t *testing.T) {
opened, release := make(chan struct{}), make(chan struct{})
c, f := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error {
if method == "remote.open" {
close(opened)
select {
case <-release:
case <-ctx.Done():
return ctx.Err()
}
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
}
return nil
})
action := approve(t, c, f, 1, "controller")
if err := c.connect(action, endpoint{host: "localhost", port: 6837}, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
awaitDone(t, opened)
f.events <- sdk.SessionEvent{Kind: "remote.revoked", Epoch: 1, Lease: strings.Repeat("b", 32)}
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "stopping" })
close(release)
nextCall(t, f, "remote.open")
nextCall(t, f, "remote.close")
status := awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
if status.err != errLease {
t.Fatal(status.err)
}
}
func TestCoordinatorHeartbeatWhileTLSStalls(t *testing.T) {
for _, finish := range []string{"disconnect", "heartbeat failure", "SDK EOF", "replacement", "parent cancel"} {
t.Run(finish, func(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
if finish == "heartbeat failure" {
f.hook = func(_ context.Context, method string, params, result any) error {
if method == "remote.open" {
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
}
if method == "remote.heartbeat" {
return errLease
}
return nil
}
}
action := approve(t, c, f, 1, "controller")
cert, _ := testCertificate(t, true)
connected, closed := make(chan struct{}), make(chan struct{})
e := testRelay(t, cert, func(conn net.Conn) {
close(connected)
// Do not start TLS: consume raw bytes and wait for socket EOF.
_, _ = io.Copy(io.Discard, conn.(*tls.Conn).NetConn())
close(closed)
})
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
awaitDone(t, connected)
heartbeat := nextCall(t, f, "remote.heartbeat").params.(sdk.RemoteOperation)
if heartbeat.Sequence != 1 || heartbeat.Epoch != 1 {
t.Fatal("bad heartbeat", heartbeat)
}
switch finish {
case "disconnect":
awaitDone(t, c.disconnect())
case "SDK EOF":
close(f.events)
case "replacement":
approve(t, c, f, 2, "controller")
case "parent cancel":
c.close()
}
awaitDone(t, closed)
closeCall := nextCall(t, f, "remote.close").params.(sdk.RemoteOperation)
if closeCall.Sequence != 2 {
t.Fatal("close raced heartbeat", closeCall)
}
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" || s.state == "closed" })
})
}
}
func TestCoordinatorFailedCloseBlocksNewConsent(t *testing.T) {
c, f := fixtureCoordinator(t, func(_ context.Context, method string, params, result any) error {
if method == "remote.open" {
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
}
if method == "remote.close" {
return errLease
}
return nil
})
action := approve(t, c, f, 1, "controller")
cert, _ := testCertificate(t, false)
e := testRelay(t, cert, func(conn net.Conn) { _, _ = io.Copy(io.Discard, conn) })
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
nextCall(t, f, "remote.close")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
fresh := approve(t, c, f, 2, "controller")
if err := c.connect(fresh, e, "synthetic-fixture"); err != errLease {
t.Fatal("failed close allowed reconnect", err)
}
}
func TestCoordinatorDisconnectWaitsForHeartbeatWithoutCancellingSDK(t *testing.T) {
heartbeatStarted, heartbeatRelease := make(chan struct{}), make(chan struct{})
var releaseOnce sync.Once
t.Cleanup(func() { releaseOnce.Do(func() { close(heartbeatRelease) }) })
c, f := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error {
if method == "remote.open" {
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
}
if method == "remote.heartbeat" {
close(heartbeatStarted)
select {
case <-heartbeatRelease:
case <-ctx.Done():
return ctx.Err()
}
if ctx.Err() != nil {
t.Error("disconnect cancelled an in-flight SDK call")
}
}
return nil
})
action := approve(t, c, f, 1, "controller")
cert, roots := testCertificate(t, true)
closed := make(chan struct{})
e := testRelay(t, cert, func(conn net.Conn) {
if relayHandshake(t, conn, controller) == nil {
return
}
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
_, _ = io.Copy(io.Discard, conn)
close(closed)
})
e.roots = roots
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" && s.peer == 0 })
awaitDone(t, heartbeatStarted)
barrier := c.disconnect()
awaitDone(t, closed) // Relay closes before the blocked heartbeat completes.
select {
case <-barrier:
t.Fatal("cleanup completed before heartbeat")
default:
}
if status := c.snapshot(); status.state != "stopping" || status.peer != 0 {
t.Fatal("stale readiness during cleanup", status)
}
fresh := approve(t, c, f, 2, "controller")
if err := c.connect(fresh, e, "synthetic-fixture"); err != errLease {
t.Fatal("new connection raced unfinished close", err)
}
releaseOnce.Do(func() { close(heartbeatRelease) })
nextCall(t, f, "remote.heartbeat")
nextCall(t, f, "remote.close")
awaitDone(t, barrier)
}
// Exercise the actual public SDK framing, replies and event stream over owned
// pipes. The host here is a synthetic lifecycle peer, not a production consent
// issuer; core authorizer conformance is tested separately in the reader.
func TestCoordinatorPublicSDKPipes(t *testing.T) {
hostInput, childOutput := io.Pipe()
childInput, hostOutput := io.Pipe()
client := sdk.NewSessionClient()
sdkDone, hostDone := make(chan struct{}), make(chan struct{})
go func() {
defer close(sdkDone)
commands := []sdk.Command{{ID: "status", Title: "Status", Handle: func(context.Context, json.RawMessage) (any, error) { return nil, nil }}}
_ = sdk.ServeSession(childInput, childOutput, commands, nil, client)
}()
var writerMu sync.Mutex
send := func(value any) error {
writerMu.Lock()
defer writerMu.Unlock()
return json.NewEncoder(hostOutput).Encode(value)
}
registered := make(chan struct{})
calls := make(chan string, 8)
go func() {
defer close(hostDone)
decoder := json.NewDecoder(bufio.NewReader(hostInput))
var registration map[string]any
if decoder.Decode(&registration) != nil {
return
}
close(registered)
for {
var request struct {
ID string `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
if decoder.Decode(&request) != nil {
return
}
calls <- request.Method
result := any(map[string]any{})
if request.Method == "remote.open" {
var open sdk.RemoteOpen
if json.Unmarshal(request.Params, &open) != nil || open.Role != "controller" {
return
}
result = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: open.Epoch}
}
if send(map[string]any{"jsonrpc": "2.0", "id": request.ID, "result": result}) != nil {
return
}
}
}()
t.Cleanup(func() {
hostInput.Close()
hostOutput.Close()
awaitDone(t, sdkDone)
awaitDone(t, hostDone)
})
initialize := `{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocol":{"major":1,"minor":1},"session":"fixture","apis":["commands","session-events","remote-access"],"capabilities":["remote-present"]}}`
if _, err := io.WriteString(hostOutput, initialize+"\n"); err != nil {
t.Fatal(err)
}
awaitDone(t, registered)
if err := send(map[string]any{"jsonrpc": "2.0", "method": "initialized", "params": map[string]string{"session": "fixture"}}); err != nil {
t.Fatal(err)
}
c := newCoordinator(t.Context(), client)
t.Cleanup(func() {
barrier := c.disconnect()
c.close()
awaitDone(t, barrier)
awaitDone(t, c.done)
})
action := sdk.SessionEvent{Kind: "remote.action", Sequence: 1, Epoch: 4, Action: strings.Repeat("a", 32), Role: "controller", Grants: []string{"remote-present"}}
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": action}); err != nil {
t.Fatal(err)
}
select {
case action = <-c.actions:
case <-time.After(time.Second):
t.Fatal("SDK did not deliver approval")
}
cert, roots := testCertificate(t, true)
e := testRelay(t, cert, func(conn net.Conn) {
if relayHandshake(t, conn, controller) == nil {
return
}
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n{\"type\":\"client_joined\",\"client\":{\"id\":7,\"connection_type\":\"slave\"}}\n")
_, _ = io.Copy(io.Discard, conn)
})
e.roots = roots
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" })
// Stale revocations cannot close the current connection.
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": sdk.SessionEvent{Kind: "remote.revoked", Sequence: 2, Epoch: 3, Lease: strings.Repeat("b", 32), Reason: "closed"}}); err != nil {
t.Fatal(err)
}
awaitDone(t, c.disconnect())
if status := c.snapshot(); status.state != "closed" || status.err != nil {
t.Fatal("normal disconnect", status)
}
if method := <-calls; method != "remote.open" {
t.Fatal(method)
}
if method := <-calls; method != "remote.close" {
t.Fatal(method)
}
}
+138
View File
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"net"
"strconv"
"sync"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func security_message(text string) sdk.Interaction {
return sdk.Interaction{Presentation: sdk.Presentation{Speech: text, Braille: text}, Done: true}
}
func (review *certificateReview) form() sdk.Interaction {
address := net.JoinHostPort(review.target.host, strconv.Itoa(review.target.port))
details := []sdk.ListItem{
{ID: "endpoint", Label: "Relay: " + address},
{ID: "fingerprint", Label: "Observed SHA-256 fingerprint: " + review.fingerprint},
{ID: "verify", Label: "Verify this fingerprint independently with the relay operator before trusting it."},
{ID: "checks", Label: "Trust once replaces CA, hostname and expiry checks for this exact certificate on this relay host and port."},
{ID: "privacy", Label: "The relay can read the channel key and session contents. The channel key does not verify a helper's identity."},
}
if review.previous != "" && review.previous != review.fingerprint {
details = append([]sdk.ListItem{{ID: "changed", Label: "The certificate has changed. This connection is stopped."},
{ID: "previous", Label: "Previously approved SHA-256 fingerprint: " + review.previous}}, details...)
}
return sdk.Interaction{Form: &sdk.Form{Title: "Review Remote relay certificate", Elements: []sdk.Element{
{ID: "details", Label: "Certificate and relay trust details", Kind: sdk.List, Items: details},
{ID: "copy-fingerprint", Label: "Copy fingerprint", Kind: sdk.Button},
{ID: "trust-once", Label: "Trust once", Kind: sdk.Button},
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
}}, Next: "remote-review-certificate"}
}
// submit returns an endpoint only on explicit Trust once. Copy fingerprint
// requests a host clipboard write, never a direct clipboard backend call. Trust
// is session-only: it neither saves a pin nor creates a reader action/lease.
func (review *certificateReview) submit(ctx context.Context, value sdk.Submission) (endpoint, sdk.Interaction, error) {
review.mu.Lock()
defer review.mu.Unlock()
if review.finished || review.lifetime.Err() != nil || ctx.Err() != nil {
review.finished = true
return endpoint{}, sdk.Interaction{}, errTrust
}
if value.Cancelled || value.Activated == "cancel" {
review.finished = true
return endpoint{}, security_message("Certificate review cancelled."), nil
}
switch value.Activated {
case "copy-fingerprint":
result := review.form()
fingerprint := review.fingerprint
result.Clipboard = &fingerprint
return endpoint{}, result, nil
case "trust-once":
review.finished = true
approved := review.target
pin := *approved.pin
approved.pin = &pin
return approved, security_message("Relay certificate approved for one connection attempt."), nil
default:
// Reading/activating a details row is not an approval.
return endpoint{}, review.form(), nil
}
}
// keyActions is a single form workflow for an already-selected endpoint. The
// caller owns the store and must keep it open until all handlers finish. Neither
// form creation nor submission loads an existing key or connects to the relay.
// As with certificateReview, production callers need verified local actions.
type keyActions struct {
mu sync.Mutex
lifetime context.Context
target endpoint
store *settingsStore
finished bool
}
func new_key_actions(ctx context.Context, target endpoint, store *settingsStore) (*keyActions, error) {
if _, err := target.tlsConfig(); err != nil || store == nil {
return nil, errSettings
}
return &keyActions{lifetime: ctx, target: endpoint{host: target.host, port: target.port}, store: store}, nil
}
func (actions *keyActions) form() sdk.Interaction {
address := net.JoinHostPort(actions.target.host, strconv.Itoa(actions.target.port))
return sdk.Interaction{Form: &sdk.Form{Title: "Remote saved channel key", Elements: []sdk.Element{
{ID: "details", Label: "Saved-key details", Kind: sdk.List, Items: []sdk.ListItem{
{ID: "endpoint", Label: "Remember a key only for relay " + address},
{ID: "storage", Label: "Remember stores the key in a private local file. Session-only keys need not be saved."},
{ID: "forget-details", Label: "Forget removes the saved key, including a key saved for another relay. It does not erase disk history or disconnect a session."},
}},
{ID: "channel-key", Label: "Channel key to remember", Kind: sdk.Entry, Secret: true, MaxLength: 512},
{ID: "remember-key", Label: "Remember key", Kind: sdk.Button},
{ID: "forget-key", Label: "Forget saved key", Kind: sdk.Button},
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
}}, Next: "remote-saved-key"}
}
func (actions *keyActions) submit(ctx context.Context, value sdk.Submission) (sdk.Interaction, error) {
actions.mu.Lock()
defer actions.mu.Unlock()
if actions.finished || actions.lifetime.Err() != nil || ctx.Err() != nil {
actions.finished = true
return sdk.Interaction{}, errSettings
}
if value.Cancelled || value.Activated == "cancel" {
actions.finished = true
return security_message("Saved-key action cancelled."), nil
}
switch value.Activated {
case "remember-key":
key := value.Values["channel-key"].Text
if !validChannelKey(key) {
result := actions.form()
result.Presentation = security_message("Enter a valid channel key before choosing Remember key.").Presentation
return result, nil
}
actions.finished = true
if err := actions.store.rememberKey(actions.target, key); err != nil {
return security_message("Channel key could not be remembered."), nil
}
return security_message("Channel key remembered for the selected relay."), nil
case "forget-key":
actions.finished = true
if err := actions.store.forgetKey(); err != nil {
return security_message("Saved channel key could not be forgotten."), nil
}
return security_message("Saved channel key forgotten."), nil
default:
return actions.form(), nil
}
}
+374
View File
@@ -0,0 +1,374 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func TestCertificateProbeDisclosesNoApplicationBytes(t *testing.T) {
certificate, _ := testCertificate(t, false) // Neither CA nor hostname trusted.
observed := make(chan int, 1)
target := testRelay(t, certificate, func(connection net.Conn) {
data, _ := io.ReadAll(connection)
observed <- len(data)
})
oldPin := &certificatePin{host: target.host, port: target.port, sha256: [32]byte{1}}
target.pin = oldPin
review, err := probe_certificate(t.Context(), target)
if err != nil {
t.Fatal(err)
}
select {
case count := <-observed:
if count != 0 {
t.Fatal("certificate probe sent application data")
}
case <-time.After(time.Second):
t.Fatal("certificate probe did not close its socket")
}
digest := sha256.Sum256(certificate.Certificate[0])
if review.fingerprint != hex.EncodeToString(digest[:]) {
t.Fatal("wrong certificate fingerprint")
}
form := review.form()
encoded, _ := json.Marshal(form)
if form.Clipboard != nil || !strings.Contains(string(encoded), "certificate has changed") || !strings.Contains(string(encoded), hex.EncodeToString(oldPin.sha256[:])) {
t.Fatal("changed pin not disclosed, or automatic clipboard request")
}
if strings.Contains(string(encoded), certificate.Leaf.Subject.CommonName) {
t.Fatal("untrusted certificate subject entered UI")
}
// Mutating the original pin cannot change the observed review or approval.
oldPin.sha256 = [32]byte{2}
approved, copied, err := review.submit(t.Context(), sdk.Submission{Activated: "copy-fingerprint"})
if err != nil || approved.host != "" || copied.Clipboard == nil || *copied.Clipboard != review.fingerprint || copied.Done {
t.Fatal("copy action changed trust or completed review", err)
}
approved, _, err = review.submit(t.Context(), sdk.Submission{Activated: "fingerprint"})
if err != nil || approved.host != "" {
t.Fatal("reading details approved a certificate")
}
approved, result, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"})
if err != nil || !result.Done || approved.pin.sha256 != digest || approved.host != target.host || approved.port != target.port || target.pin.sha256 == digest {
t.Fatal("approval changed endpoint identity or original trust", err)
}
if _, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"}); !errors.Is(err, errTrust) {
t.Fatal("certificate review was reusable")
}
}
func TestReviewedCertificateAuthenticatedAgainBeforeJoin(t *testing.T) {
certificate, _ := testCertificate(t, false)
var mutex sync.Mutex
attempt := 0
target := testRelay(t, certificate, func(connection net.Conn) {
mutex.Lock()
attempt++
current := attempt
mutex.Unlock()
if current == 1 {
data, _ := io.ReadAll(connection)
if len(data) != 0 {
t.Error("probe disclosed application data")
}
return
}
if relayHandshake(t, connection, controller) == nil {
return
}
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
_, _ = io.Copy(io.Discard, connection)
})
review, err := probe_certificate(t.Context(), target)
if err != nil {
t.Fatal(err)
}
approved, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"})
if err != nil {
t.Fatal(err)
}
connection, _, err := connect(t.Context(), approved, controller, "synthetic-fixture")
if err != nil {
t.Fatal("reviewed certificate failed fresh TLS authentication", err)
}
connection.close()
}
func TestCertificateReviewCancellationAndConcurrentApproval(t *testing.T) {
for _, mode := range []string{"cancel", "cancelled", "lifetime", "handler"} {
t.Run(mode, func(t *testing.T) {
lifetime, cancel := context.WithCancel(t.Context())
defer cancel()
review := &certificateReview{lifetime: lifetime, target: endpoint{host: "relay.invalid", port: 6837, pin: &certificatePin{sha256: [32]byte{1}}}}
value := sdk.Submission{Activated: "trust-once"}
ctx := t.Context()
switch mode {
case "cancel":
value.Activated = "cancel"
case "cancelled":
value.Cancelled = true
case "lifetime":
cancel()
case "handler":
var stop context.CancelFunc
ctx, stop = context.WithCancel(ctx)
stop()
}
approved, _, _ := review.submit(ctx, value)
if approved.host != "" {
t.Fatal("cancelled review returned trust")
}
if _, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"}); err == nil {
t.Fatal("cancelled review could be approved later")
}
})
}
review := &certificateReview{lifetime: t.Context(), target: endpoint{host: "relay.invalid", pin: &certificatePin{sha256: [32]byte{1}}}}
results := make(chan bool, 2)
for range 2 {
go func() {
_, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"})
results <- err == nil
}()
}
if first, second := <-results, <-results; first == second {
t.Fatal("concurrent submissions did not consume review exactly once")
}
}
func TestCertificateProbeCancellation(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
done := make(chan error, 1)
go func() {
_, err := probe_certificate(ctx, endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port})
done <- err
}()
connection, err := listener.Accept()
if err != nil {
t.Fatal(err)
}
defer connection.Close()
cancel()
select {
case err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatal("probe did not report cancellation", err)
}
case <-time.After(time.Second):
t.Fatal("stalled TLS probe ignored cancellation")
}
}
func TestCertificateChangeAfterReviewDoesNotDiscloseKey(t *testing.T) {
first, _ := testCertificate(t, true)
changed, _ := testCertificate(t, true)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { listener.Close() })
observed := make(chan int, 2)
done := make(chan struct{})
go func() {
defer close(done)
for _, certificate := range []tls.Certificate{first, changed} {
raw, err := listener.Accept()
if err != nil {
return
}
raw.SetDeadline(time.Now().Add(3 * time.Second))
connection := tls.Server(raw, &tls.Config{Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS12})
data, _ := io.ReadAll(connection)
observed <- len(data)
raw.Close()
}
}()
t.Cleanup(func() { listener.Close(); <-done })
target := endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port}
review, err := probe_certificate(t.Context(), target)
if err != nil {
t.Fatal(err)
}
approved, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"})
if err != nil {
t.Fatal(err)
}
connection, _, err := connect(t.Context(), approved, controller, "synthetic-private-key")
if connection != nil || !errors.Is(err, errTrust) {
t.Fatal("certificate changed between probe and join was accepted", err)
}
for range 2 {
select {
case count := <-observed:
if count != 0 {
t.Fatal("probe or failed authentication disclosed application data")
}
case <-time.After(time.Second):
t.Fatal("probe or failed authentication socket remained open")
}
}
}
func TestSavedKeyActionsAreExplicitAndSecret(t *testing.T) {
store, path, value := settingsFixture(t)
target, _ := value.endpoint()
if err := store.save(value); err != nil {
t.Fatal(err)
}
actions, err := new_key_actions(t.Context(), target, store)
if err != nil {
t.Fatal(err)
}
form := actions.form()
entry := form.Form.Elements[1]
if entry.Kind != sdk.Entry || !entry.Secret || entry.Text != "" || entry.Required || form.Clipboard != nil {
t.Fatal("key form exposes or unnecessarily requires a secret")
}
if _, err := os.Stat(filepath.Join(path, "channel-key.toml")); !os.IsNotExist(err) {
t.Fatal("creating a form saved a key")
}
key := "synthetic-private-猫-key"
submission := sdk.Submission{Activated: "remember-key", Values: map[string]sdk.Value{"channel-key": {Text: key}}}
result, err := actions.submit(t.Context(), submission)
encoded, _ := json.Marshal(result)
if err != nil || !result.Done || strings.Contains(string(encoded), key) {
t.Fatal("Remember failed or echoed the key", err)
}
stored, err := store.loadKey(target)
if err != nil || stored != key {
t.Fatal("explicit key was not stored")
}
ordinary, err := os.ReadFile(filepath.Join(path, "settings.toml"))
if err != nil || strings.Contains(string(ordinary), key) {
t.Fatal("key entered ordinary settings")
}
if _, err := actions.submit(t.Context(), submission); err == nil {
t.Fatal("Remember action was reusable")
}
// Another endpoint never receives the saved key in its form. Forget is
// explicitly global because the storage contract has one saved-key slot.
other := endpoint{host: "other.invalid", port: 6837}
forget, _ := new_key_actions(t.Context(), other, store)
encoded, _ = json.Marshal(forget.form())
if strings.Contains(string(encoded), key) {
t.Fatal("saved key entered a later form")
}
result, err = forget.submit(t.Context(), sdk.Submission{Activated: "forget-key"})
if err != nil || !result.Done {
t.Fatal("Forget failed", err)
}
if stored, err := store.loadKey(target); err != nil || stored != "" {
t.Fatal("forgotten key remains")
}
}
func TestSavedKeyCancellationValidationAndStorageFailure(t *testing.T) {
for _, mode := range []string{"cancel", "lifetime", "handler", "invalid", "failure", "details"} {
t.Run(mode, func(t *testing.T) {
store, path, value := settingsFixture(t)
target, _ := value.endpoint()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
actions, _ := new_key_actions(ctx, target, store)
key := "synthetic-private-key"
submission := sdk.Submission{Activated: "remember-key", Values: map[string]sdk.Value{"channel-key": {Text: key}}}
handlerContext := t.Context()
switch mode {
case "cancel":
submission.Cancelled = true
case "lifetime":
cancel()
case "handler":
var stop context.CancelFunc
handlerContext, stop = context.WithCancel(handlerContext)
stop()
case "invalid":
submission.Values["channel-key"] = sdk.Value{Text: strings.Repeat("猫", 200)} // Exceeds byte limit.
case "failure":
store.close()
case "details":
submission.Activated = "endpoint"
}
result, _ := actions.submit(handlerContext, submission)
encoded, _ := json.Marshal(result)
if strings.Contains(string(encoded), key) || result.Clipboard != nil {
t.Fatal("key leaked through response")
}
if mode == "failure" && result.Speech != "Channel key could not be remembered." {
t.Fatal("storage failure was not reported")
}
if _, err := os.Stat(filepath.Join(path, "channel-key.toml")); !os.IsNotExist(err) {
t.Fatal("key stored without a valid completed Remember action")
}
})
}
}
func TestForgetKeyCancellationAndFailurePreserveSavedKey(t *testing.T) {
for _, mode := range []string{"cancel", "lifetime", "failure"} {
t.Run(mode, func(t *testing.T) {
store, path, value := settingsFixture(t)
target, _ := value.endpoint()
if err := store.rememberKey(target, "synthetic-retained-key"); err != nil {
t.Fatal(err)
}
before, err := os.ReadFile(filepath.Join(path, "channel-key.toml"))
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
actions, _ := new_key_actions(ctx, target, store)
submission := sdk.Submission{Activated: "forget-key", Cancelled: mode == "cancel"}
if mode == "lifetime" {
cancel()
}
if mode == "failure" {
store.close()
}
result, _ := actions.submit(t.Context(), submission)
if mode == "failure" && result.Speech != "Saved channel key could not be forgotten." {
t.Fatal("Forget failure was not reported")
}
after, err := os.ReadFile(filepath.Join(path, "channel-key.toml"))
if err != nil || string(before) != string(after) {
t.Fatal("cancelled or failed Forget changed stored key")
}
})
}
}
func TestSecurityFormsRejectInvalidEndpoints(t *testing.T) {
store, _, _ := settingsFixture(t)
for _, host := range []string{"relay\x1b.invalid", "relay\x7f.invalid", "relay\x85.invalid", "relay\xff.invalid", "relay\n.invalid"} {
target := endpoint{host: host, port: 6837}
if _, err := new_key_actions(t.Context(), target, store); err == nil {
t.Fatal("invalid UI host accepted")
}
if _, err := probe_certificate(t.Context(), target); err == nil {
t.Fatal("invalid probe host accepted")
}
}
}
+3 -1
View File
@@ -19,6 +19,8 @@ import (
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
)
const (
@@ -56,7 +58,7 @@ type endpoint struct {
}
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 {
if e.host == "" || len(e.host) > 253 || !utf8.ValidString(e.host) || strings.IndexFunc(e.host, unicode.IsControl) >= 0 || strings.TrimSpace(e.host) != e.host || strings.ContainsAny(e.host, "/\\@ []") || e.port < 1 || e.port > 65535 {
return nil, errEndpoint
}
// Colons are accepted only in bare IPv6 literals; JoinHostPort adds brackets.
+69
View File
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"net"
"strconv"
"sync"
)
// certificateReview owns a single local review workflow. Its context must be
// the workflow lifetime, not a short command RPC. The future UI owner must cancel
// it on approval replacement, form closure, lock/handoff or process shutdown.
// A Submission is not proof of local input origin; these handlers must not be
// wired to production commands until the reader can establish that origin.
type certificateReview struct {
mu sync.Mutex
lifetime context.Context
target endpoint
fingerprint string
previous string
finished bool
}
// probe_certificate is an explicit, unauthenticated certificate inspection. It
// takes no channel key and writes no application bytes. Never call it as an
// automatic fallback from connect: CA or pin failure must stop that attempt.
// Normal CA/pin authentication is repeated on a NEW connection after review.
func probe_certificate(ctx context.Context, target endpoint) (*certificateReview, error) {
config, err := target.tlsConfig()
if err != nil {
return nil, err
}
// Only this inspection socket bypasses authentication. It closes immediately
// after TLS and cannot be returned as an authenticated relay connection.
config.InsecureSkipVerify = true
config.VerifyConnection = nil
probeContext, cancel := context.WithTimeout(ctx, dialTimeout)
defer cancel()
raw, err := (&net.Dialer{}).DialContext(probeContext, "tcp", net.JoinHostPort(target.host, strconv.Itoa(target.port)))
if err != nil {
return nil, networkError(ctx, err)
}
defer raw.Close()
connection := tls.Client(raw, config)
if err := connection.HandshakeContext(probeContext); err != nil {
return nil, networkError(ctx, err)
}
certificates := connection.ConnectionState().PeerCertificates
if len(certificates) == 0 {
return nil, errTrust
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
digest := sha256.Sum256(certificates[0].Raw)
review := &certificateReview{lifetime: ctx, fingerprint: hex.EncodeToString(digest[:])}
if target.pin != nil {
review.previous = hex.EncodeToString(target.pin.sha256[:])
}
// Retain endpoint identity and the observed digest only. No server-controlled
// subject/issuer text, certificates, keys or caller-owned TLS pointers survive.
review.target = endpoint{host: target.host, port: target.port, pin: &certificatePin{host: target.host, port: target.port, sha256: digest}}
return review, nil
}