mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 16:27:33 -10:00
fix(msg): one rule for which characters reach the terminal
msg.Safe is the one owner: a graphic character in any script is safe; controls, bidi controls, format characters, variation selectors, private use and the invisible fillers are not. Printable and OneLine drop what Safe refuses, agent save's diff escapes it, and forbidigo bans unicode.IsGraphic, IsPrint, IsControl and Bidi_Control outside internal/msg. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
13 files changed
+143
-40
No files matched your search
@@ -104,6 +104,8 @@ linters:
|
||||
msg: write a file whole through state.WriteFile, or state.WriteFileMode for another mode, which replace it atomically; internal/proxy uses its writeAtomic; a log or a download streamed into its file says why in a nolint.
|
||||
- pattern: ^(os|syscall)\.(Setenv|Unsetenv|Clearenv)$
|
||||
msg: devvm's environment never changes, as every command and process it starts inherits it; set a command's own (exec.Cmd's Env), as a VM's SSH agent is (backend.ExecOpts.Agent). Only daemon.Ready takes its status file out.
|
||||
- pattern: ^unicode\.(IsGraphic|IsPrint|IsControl|Bidi_Control)$
|
||||
msg: ask msg.Safe which characters reach the terminal (msg.Printable and msg.OneLine drop the rest); a check that isn't about the terminal says why in a nolint.
|
||||
nolintlint:
|
||||
require-explanation: true
|
||||
require-specific: true
|
||||
@@ -122,6 +124,10 @@ linters:
|
||||
presets:
|
||||
- std-error-handling
|
||||
rules:
|
||||
# msg.Safe is the one rule for which characters reach the terminal.
|
||||
- path: ^internal/msg/
|
||||
linters: [forbidigo]
|
||||
text: ask msg\.Safe
|
||||
- path: ^cmd/devvm/
|
||||
linters: [forbidigo]
|
||||
text: os\.Exit|context\.(Background|TODO)
|
||||
|
||||
@@ -123,6 +123,7 @@ An owner gets a check only when a second copy would be a bug or a security hole,
|
||||
| --- | --- | --- |
|
||||
| forbidigo, `testbuild.On` | `internal/cli`, whose `readOverrides` is the only code that asks whether this is a test build | nowhere: other packages take the overrides as fields |
|
||||
| forbidigo, `os.FindProcess`, `syscall.Kill`, `unix.Kill` and `os.Process`'s `Kill` and `Signal` | `internal/daemon`, which signals a background process only while its pid file and its arguments say it's still that process (`Proc`), or through the process it started (`Handle`) | `internal/platform`; tests, which signal the children they started; and a child that hasn't been waited for yet, whose pid is still its own, with a `nolint` saying so |
|
||||
| forbidigo, `unicode.IsGraphic`, `IsPrint`, `IsControl` and `Bidi_Control` | `msg.Safe` in `internal/msg/safe.go`, the one rule for which characters reach the terminal, which `msg.Printable`, `msg.OneLine`, the UI's renderers and devvm agent save's diff follow, so a second rule can't let through what this one refuses ([Colors](#colors) says what it refuses) | a check that isn't about the terminal, such as a path one line long, with a `//nolint:forbidigo` saying so |
|
||||
| forbidigo, HTTP clients | `internal/fetch`, whose `NewClient` sets each client's timeout and redirect policy (`HTTPSOnly` or `SameScheme`), and whose `Retry`, `Transient`, `ReadCapped`, `Get`, `Resolve` and `Download` try again after the failures that may pass, cap what a body or a download may hold, follow a HEAD's redirects to where they end and check a download's SHA-256 before anything uses it. `fetch.Client` is its own type, so a client that `NewClient` didn't make, such as `&fetch.Client{}`, fails every request, and a caller changes a client's transport through its `Transport` method | `internal/proxy`, which is the standard library only, and tests, which make their own servers' clients |
|
||||
| forbidigo, `os.WriteFile`, `os.Create` and `os.O_TRUNC` | `internal/state`, whose `WriteFile` and `WriteFileMode` write a file whole through a temporary file in its folder, renamed over it, so a reader never sees half of it | `internal/proxy`, which imports only the standard library and has its own writer, `writeAtomic`; `internal/msg/gen`, which imports no devvm package; `internal/stubtest`; tests; and, with a `nolint` saying why, a file written another way: a log that a process writes as it runs, a download that streams into its file, and `internal/daemon`'s pid and status files, each written in one write that a reader takes as missing until its line ends |
|
||||
| forbidigo, `os.Setenv`, `os.Unsetenv`, `os.Clearenv` and `syscall`'s | each command's own environment, its `exec.Cmd`'s `Env`, because every command and background process devvm starts inherits devvm's. A VM's SSH agent is one: the finder's `target` carries its socket, which goes to the backend in `backend.ExecOpts.Agent`, `backend.ShellOpts.Agent` and `Confinement.AgentSocket`, and Lima sets `SSH_AUTH_SOCK` on that VM's `limactl` commands alone, so a run that reaches several VMs never gives one another's | `daemon.Ready` in `internal/daemon/status.go`, which takes the status file's name out of a background process's own environment, and tests, which use `t.Setenv` |
|
||||
@@ -452,7 +453,7 @@ other = "{{.count}} current shared tool images no VM has ({{.size}}): {{.tools}}
|
||||
- **`description`** is an optional note for translators.
|
||||
- **Nothing else:** the generator refuses keys go-i18n doesn't know, nested tables, plural forms English doesn't use (`zero`, `two`, `few`, `many`) and `leftDelim`/`rightDelim`.
|
||||
- **Voice:** a message's text follows the docs-voice skill's [Messages](https://github.com/devvmhq/devvm/blob/main/.agents/skills/docs-voice/SKILL.md#messages) rules, which set its length (an error or a warning has at most two sentences, and a prompt at most two lines of context), and the mechanism goes in its doc link rather than its text.
|
||||
- **One line:** a value renders on one line without control or bidi characters, because `msg.OneLine` cleans every value as the message renders. Text from a VM that devvm shows as data goes through `msg.Printable` instead, which keeps its newlines and tabs. [Colors](#colors) says what the two drop.
|
||||
- **One line:** a value renders on one line without control, bidi or invisible characters, because `msg.OneLine` cleans every value as the message renders. Text from a VM that devvm shows as data goes through `msg.Printable` instead, which keeps its newlines and tabs. [Colors](#colors) says what the two drop.
|
||||
|
||||
### Doc links
|
||||
|
||||
@@ -516,7 +517,7 @@ The colors are SGR codes from the 16 base colors only, which the theme maps to i
|
||||
- The run log's end that `ErrorLogged` prints, with its `---` lines, the log text on the status line, and the log's lines that `-v` streams (`SetVerbose`: `LoggedCmd` and `LogWriter` copy the log to stderr through `msg.Printable`, with no status line) are dim (`2`).
|
||||
- The done mark that a slow step leaves is green (`32`).
|
||||
|
||||
The codes are added after `msg.Printable` and `msg.OneLine`, so they're the only ones devvm prints. Those two are devvm's one cleaner: they drop C0 control characters but newline and tab (which `OneLine` drops too), DEL and C1, whether in UTF-8 or as a lone byte, and the bidi controls such as U+202E, which reorder the text after them so a name could read as another. The status line, the run log's end, `Pick`, `devvm network log` and the port forwarder's log use them as well. The status line cuts and counts its plain text with `style.fit` before painting it, so it still fits the terminal's width and clears the right number of rows. The run log is never colored.
|
||||
The codes are added after `msg.Printable` and `msg.OneLine`, so they're the only ones devvm prints. Those two are devvm's one cleaner, and `msg.Safe` is its one rule for which characters reach the terminal. They drop every character that `msg.Safe` refuses but newline and tab (which `OneLine` drops too), and a lone C1 byte. `msg.Safe` takes a graphic character in any script, such as an accented letter, a CJK character or an emoji, so a VM's file names still read as they are. It refuses the control characters (C0, DEL and C1), the bidi controls such as U+202E, which reorder the text after them so a name could read as another, the format characters, such as the zero-width space and joiners, the word joiner, the soft hyphen and the tag characters, the variation selectors, and the fillers that show as nothing, such as U+3164 and the braille blank U+2800, which could hide or fake text in a prompt. The diff of devvm agent save writes each character that `msg.Safe` refuses as its code instead, and the names of the files it saves must hold none. The status line, the run log's end, `Pick`, `devvm network log` and the port forwarder's log use them as well. The status line cuts and counts its plain text with `style.fit` before painting it, so it still fits the terminal's width and clears the right number of rows. The run log is never colored.
|
||||
|
||||
Tables on `Stdout()` are colored as stdout is. A command gets a `ui.Table` from `u.Table()` and adds a header, rows of `ui.Cell`s and a totals row, and cli never reads the environment itself. Each cell has a `ui.Role`: `Good` is green (`32`), `Attention` yellow (`33`), `Bad` red (`31`), `Secondary` dim (`2`), and `Plain` stays in the default color, while the header and totals rows are bold. `Table` pads each cell on its plain text before painting it, because `text/tabwriter` counts the codes' bytes as width, and a plain table is byte for byte what `text/tabwriter` writes with a padding of 2 (`TestTableLikeTabwriter`). The roles for each table's values are next to the code that writes it:
|
||||
|
||||
|
||||
+7
-4
@@ -95,12 +95,15 @@ func (m M) Text() string {
|
||||
return m.textIn(loadBundle(), userLanguage(os.Getenv))
|
||||
}
|
||||
|
||||
func (m M) textIn(b *i18n.Bundle, lang string) string {
|
||||
// Values are made by anyone, a VM included, so each goes on one line
|
||||
// without control characters, here, wherever the message is shown.
|
||||
func (m M) textIn(b *i18n.Bundle, lang string) string { return m.renderIn(b, lang, OneLine) }
|
||||
|
||||
// renderIn is the message's text with each value as value makes it, which
|
||||
// goes through OneLine: values are made by anyone, a VM included, so each
|
||||
// goes on one line without what Safe refuses, wherever the message is shown.
|
||||
func (m M) renderIn(b *i18n.Bundle, lang string, value func(string) string) string {
|
||||
data := make(map[string]string, len(m.vals))
|
||||
for _, v := range m.vals {
|
||||
data[v.key] = OneLine(v.value)
|
||||
data[v.key] = value(v.value)
|
||||
}
|
||||
lc := &i18n.LocalizeConfig{MessageID: m.id, TemplateData: data}
|
||||
if m.plural {
|
||||
|
||||
@@ -2,17 +2,15 @@ package msg
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Printable returns s without the control characters that could move the
|
||||
// cursor or rewrite what a terminal shows: C0 but newline and tab, DEL,
|
||||
// and C1, whether in UTF-8 or as a lone byte, and the bidi controls
|
||||
// (U+202E and its kin) that reorder what follows them. It's for text a VM or a
|
||||
// build made (its output, a path, a host), and every message value goes
|
||||
// through OneLine, its one-line form, when the message renders. Other
|
||||
// bytes, invalid UTF-8 among them, stay as they are.
|
||||
// Printable returns s without the characters Safe refuses, but newline
|
||||
// and tab, and without a lone C1 byte: nothing in it moves the cursor,
|
||||
// rewrites, reorders or hides what a terminal shows. It's for text a VM
|
||||
// or a build made (its output, a path, a host), and every message value
|
||||
// goes through OneLine, its one-line form, when the message renders.
|
||||
// Other bytes, invalid UTF-8 among them, stay as they are.
|
||||
func Printable(s string) string { return clean(s, true) }
|
||||
|
||||
// OneLine is Printable without newlines and tabs too: text for one line,
|
||||
@@ -33,7 +31,7 @@ func clean(s string, lines bool) string {
|
||||
if lines {
|
||||
b.WriteRune(r)
|
||||
}
|
||||
case unicode.IsControl(r), unicode.Is(unicode.Bidi_Control, r):
|
||||
case !Safe(r):
|
||||
default:
|
||||
b.WriteString(s[i : i+n])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package msg
|
||||
|
||||
import "unicode"
|
||||
|
||||
// Safe reports whether a terminal shows r as it is, so that text from a VM
|
||||
// (or any other untrusted text) can't move the cursor, reorder, fake or
|
||||
// hide what the user reads: r is graphic (a letter, mark, number,
|
||||
// punctuation, symbol or space, in any script, emoji too), and not a
|
||||
// format character (Cf: zero-width spaces and joiners, the word joiner,
|
||||
// the soft hyphen, the tag characters), a bidi control, a variation
|
||||
// selector or one of the fillers that show as nothing (Hangul's, the
|
||||
// braille blank, the combining grapheme joiner). Controls, tab and
|
||||
// newline among them, aren't safe: a caller that keeps lines keeps
|
||||
// those itself. It's the one rule for which characters reach the
|
||||
// terminal: Printable and OneLine drop the rest, a diff escapes them.
|
||||
func Safe(r rune) bool {
|
||||
return unicode.IsGraphic(r) &&
|
||||
!unicode.Is(unicode.Cf, r) &&
|
||||
!unicode.Is(unicode.Bidi_Control, r) &&
|
||||
!unicode.Is(unicode.Variation_Selector, r) &&
|
||||
!invisible(r)
|
||||
}
|
||||
|
||||
// invisible is a graphic character most terminals show as blank space or
|
||||
// nothing at all, though Unicode doesn't call it a space.
|
||||
func invisible(r rune) bool {
|
||||
switch r {
|
||||
case 0x034f, // combining grapheme joiner
|
||||
0x115f, 0x1160, // Hangul choseong and jungseong fillers
|
||||
0x17b4, 0x17b5, // Khmer's inherent vowels
|
||||
0x2800, // braille pattern blank
|
||||
0x3164, // Hangul filler
|
||||
0xffa0: // halfwidth Hangul filler
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package msg
|
||||
|
||||
import "testing"
|
||||
|
||||
// Each class of character, by code point, so this file holds none of the
|
||||
// invisible ones.
|
||||
func TestSafe(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, tc := range []struct {
|
||||
what string
|
||||
r rune
|
||||
safe bool
|
||||
}{
|
||||
{"letter", 'a', true},
|
||||
{"space", ' ', true},
|
||||
{"accented", 'é', true},
|
||||
{"CJK", '漢', true},
|
||||
{"full-width letter", 0xff21, true},
|
||||
{"emoji", 0x1f600, true},
|
||||
{"combining accent", 0x0301, true},
|
||||
{"ideographic space", 0x3000, true},
|
||||
{"newline", '\n', false},
|
||||
{"tab", '\t', false},
|
||||
{"escape", 0x1b, false},
|
||||
{"DEL", 0x7f, false},
|
||||
{"C1 CSI", 0x9b, false},
|
||||
{"RLO", 0x202e, false},
|
||||
{"LRI", 0x2066, false},
|
||||
{"RLM", 0x200f, false},
|
||||
{"ALM", 0x061c, false},
|
||||
{"zero-width space", 0x200b, false},
|
||||
{"zero-width non-joiner", 0x200c, false},
|
||||
{"zero-width joiner", 0x200d, false},
|
||||
{"word joiner", 0x2060, false},
|
||||
{"invisible times", 0x2062, false},
|
||||
{"BOM", 0xfeff, false},
|
||||
{"soft hyphen", 0x00ad, false},
|
||||
{"tag A", 0xe0041, false},
|
||||
{"cancel tag", 0xe007f, false},
|
||||
{"variation selector 16", 0xfe0f, false},
|
||||
{"variation selector 17", 0xe0100, false},
|
||||
{"Mongolian vowel separator", 0x180e, false},
|
||||
{"combining grapheme joiner", 0x034f, false},
|
||||
{"Hangul filler", 0x3164, false},
|
||||
{"halfwidth Hangul filler", 0xffa0, false},
|
||||
{"Hangul choseong filler", 0x115f, false},
|
||||
{"Khmer inherent vowel", 0x17b4, false},
|
||||
{"braille blank", 0x2800, false},
|
||||
{"line separator", 0x2028, false},
|
||||
{"private use", 0xe000, false},
|
||||
{"unassigned", 0x0378, false},
|
||||
} {
|
||||
if got := Safe(tc.r); got != tc.safe {
|
||||
t.Errorf("Safe(%s, U+%04X) = %v, want %v", tc.what, tc.r, got, tc.safe)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// OneLine drops what Safe refuses, and keeps the rest.
|
||||
func TestOneLineDropsInvisible(t *testing.T) {
|
||||
t.Parallel()
|
||||
in := "a" + string(rune(0x200b)) + "b" + string(rune(0xe0041)) + "c" + string(rune(0x3164)) +
|
||||
"d" + string(rune(0x2800)) + "é漢" + string(rune(0x1f600))
|
||||
want := "abcdé漢" + string(rune(0x1f600))
|
||||
if got := OneLine(in); got != want {
|
||||
t.Errorf("OneLine(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
@@ -30,22 +30,10 @@ func (m M) Segments() (segs []Segment, link string) {
|
||||
}
|
||||
|
||||
func (m M) segmentsIn(b *i18n.Bundle, lang string) []Segment {
|
||||
marked := m
|
||||
marked.vals = make([]val, len(m.vals))
|
||||
for i, v := range m.vals {
|
||||
marked.vals[i] = val{v.key, string(valueStart) + unmarked(v.value) + string(valueEnd)}
|
||||
}
|
||||
return split(marked.textIn(b, lang))
|
||||
}
|
||||
|
||||
// unmarked is s without the marker runes.
|
||||
func unmarked(s string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
if r == valueStart || r == valueEnd {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
// OneLine drops private-use runes, the markers among them (Safe).
|
||||
return split(m.renderIn(b, lang, func(v string) string {
|
||||
return string(valueStart) + OneLine(v) + string(valueEnd)
|
||||
}))
|
||||
}
|
||||
|
||||
// split cuts marked text into segments, the marked parts values; empty
|
||||
|
||||
@@ -134,7 +134,7 @@ func New(dir string, nameMax int) (Folder, error) { return Nth(dir, nameMax, 0)
|
||||
// from dir keeps its name, and so its folder in devvm's data folder, so
|
||||
// a new VM for dir takes the next name.
|
||||
func Nth(dir string, nameMax, n int) (Folder, error) {
|
||||
if strings.Contains(dir, ",") || strings.IndexFunc(dir, unicode.IsControl) >= 0 {
|
||||
if strings.Contains(dir, ",") || strings.IndexFunc(dir, unicode.IsControl) >= 0 { //nolint:forbidigo // what a VM's mount takes, not the terminal
|
||||
return Folder{}, &BadPathError{Dir: dir}
|
||||
}
|
||||
room := slugMax
|
||||
|
||||
@@ -39,7 +39,7 @@ func checkUbuntuMirror(s string) error {
|
||||
u, err := url.Parse(s)
|
||||
bad := err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" ||
|
||||
u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Opaque != "" ||
|
||||
strings.ContainsFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) })
|
||||
strings.ContainsFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) //nolint:forbidigo // a line of apt's list, not the terminal
|
||||
if bad {
|
||||
return msg.UbuntuMirrorInvalid(KeyUbuntuMirror)
|
||||
}
|
||||
|
||||
@@ -316,7 +316,7 @@ func agentFiles(home, agent string) []string {
|
||||
// control character: the VM's setup takes paths one per line.
|
||||
func readDir(dir string) []os.DirEntry {
|
||||
es, _ := os.ReadDir(dir)
|
||||
return slices.DeleteFunc(es, func(e os.DirEntry) bool { return strings.IndexFunc(e.Name(), unicode.IsControl) >= 0 })
|
||||
return slices.DeleteFunc(es, func(e os.DirEntry) bool { return strings.IndexFunc(e.Name(), unicode.IsControl) >= 0 }) //nolint:forbidigo // the setup's one path per line, not the terminal
|
||||
}
|
||||
|
||||
// AgentMounts returns the host folders a VM with these shared tools
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/devvmhq/devvm/internal/agentlogin"
|
||||
@@ -144,13 +143,13 @@ func readSent(r io.Reader, vm string, agents []string) (*sent, error) {
|
||||
// entryName is a stream entry's path relative to the VM's home, a
|
||||
// folder's without its last /, when it's one devvm takes: relative,
|
||||
// clean (no . or .. part), valid UTF-8 and only of characters a terminal
|
||||
// shows (unicode.IsGraphic: no control, format or bidi characters), so
|
||||
// shows as they are (msg.Safe), so
|
||||
// the diff shows each name as it is.
|
||||
func entryName(raw string) (string, bool) {
|
||||
name := strings.TrimSuffix(raw, "/")
|
||||
ok := name != "" && name != "." && !path.IsAbs(name) && path.Clean(name) == name &&
|
||||
name != ".." && !strings.HasPrefix(name, "../") && utf8.ValidString(name) &&
|
||||
strings.IndexFunc(name, func(r rune) bool { return !unicode.IsGraphic(r) }) < 0
|
||||
strings.IndexFunc(name, func(r rune) bool { return !msg.Safe(r) }) < 0
|
||||
return name, ok
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,9 @@ package vm
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/devvmhq/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// diffContext is how many unchanged lines a diff shows around each change.
|
||||
@@ -187,7 +188,6 @@ func middleOps(a, b []string) []diffOp {
|
||||
// \u{HEX} (a byte that isn't UTF-8 as \x{HEX}), so nothing in it hides
|
||||
// or changes what the diff shows.
|
||||
func shownLine(s string) string {
|
||||
const softHyphen = 0xad // graphic to Unicode, but most terminals show nothing
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); {
|
||||
r, n := utf8.DecodeRuneInString(s[i:])
|
||||
@@ -196,7 +196,7 @@ func shownLine(s string) string {
|
||||
b.WriteString(`\x{` + strconv.FormatUint(uint64(s[i]), 16) + "}")
|
||||
case r == '\\':
|
||||
b.WriteString(`\\`)
|
||||
case r == '\t' || unicode.IsGraphic(r) && r != softHyphen:
|
||||
case r == '\t' || msg.Safe(r):
|
||||
b.WriteRune(r)
|
||||
default:
|
||||
b.WriteString(`\u{` + strconv.FormatInt(int64(r), 16) + "}")
|
||||
|
||||
Vendored
+3
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"unicode"
|
||||
|
||||
"github.com/devvmhq/devvm/internal/testbuild"
|
||||
)
|
||||
@@ -49,3 +50,5 @@ func truncates() (*os.File, error) { return os.OpenFile("f", os.O_WRONLY|os.O_TR
|
||||
func setsEnv() error { return os.Setenv("SSH_AUTH_SOCK", "/s") } // want forbidigo
|
||||
|
||||
func unsetsEnv() error { return os.Unsetenv("SSH_AUTH_SOCK") } // want forbidigo
|
||||
|
||||
func shows(r rune) bool { return unicode.IsGraphic(r) } // want forbidigo
|
||||
Reference in new issue
Block a user