Skip to content

An open-source, faster Devin alternative

TypeScript

computer: the model proxy names a session by its anchored unit and uid (work 103, step 6) (#1038)

opencomputer-app[bot]964cba74ce4d
diff --git a/computer/modelproxy/README.md b/computer/modelproxy/README.md
index 6bb86468..d81ae17f 100644
--- a/computer/modelproxy/README.md
+++ b/computer/modelproxy/README.md
@@ -148,7 +148,7 @@ Rules that hold:
## Who is calling
-`-identity=cgroup` (default): the caller is `<id>` of the `sp-runner-<id>.service` unit the connection's peer process runs in, read once from its cgroup when the connection is accepted. The outermost such unit in the path wins, so a process cannot rename itself by creating cgroups below its own. This is routing, not isolation: sessions that share a uid can move between each other's units, so do not put mutually untrusted tenants on one computer.
+`-identity=cgroup` (default): the caller is `<id>` of the `sp-runner-<id>.service` unit the connection's peer process runs in, read once from its cgroup when the connection is accepted. The path is matched from its root: only slices and `user@<uid>.service` may lead to `slack-presence-runners.slice`, and the element right below that slice must be the unit. Nothing further down is read, so a session cannot rename itself by creating cgroups below its own unit, which is all it can create: a session in a container owns that subtree and sees nothing else of the hierarchy. With `-caller-uid`, a peer of any other uid is no caller; in a session's container those are its subordinate ids (its root, for one). The root of a container the session nests as its own user maps to that user's uid again (1500), not to a subordinate id, so it is a caller, and its session's: the uid separates the sessions' user from everything else, the cgroup one session from another. Sessions that run as plain units of one user, without containers, can move between each other's units: there this is routing, not isolation.
`-identity=single`: every connection is the caller `single`. For a computer that runs one session outside systemd.
@@ -162,6 +162,7 @@ Rules that hold:
| `-check` | | load `-profiles`, print the first error, exit 0 or 1 |
| `-placeholder` | `ssh-placeholder` | the only credential a caller may send |
| `-identity` | `cgroup` | `cgroup` or `single` |
+| `-caller-uid` | `-1` (any) | with `-identity=cgroup`, the only uid a caller may have |
| `-bindings-file` | `/run/oc-modelproxy/profile-bindings.json` | persisted bindings, without variables (empty: off) |
| `-hold-timeout` | `10s` | how long a request waits for its caller's bind, and then for a free upstream connection |
| `-drain-timeout` | `630s` | on SIGTERM or after a handoff, how long streams in flight may finish |
diff --git a/computer/modelproxy/identity.go b/computer/modelproxy/identity.go
index f2893681..a24d1f3e 100644
--- a/computer/modelproxy/identity.go
+++ b/computer/modelproxy/identity.go
@@ -1,13 +1,26 @@
// Caller identity: which caller a connection on the API socket comes from.
-// SO_PEERCRED gives the peer's pid; /proc/<pid>/cgroup gives its cgroup
-// path, whose first `sp-runner-<id>.service` element names the caller <id>.
-// The first, not the last: a process can create cgroups below its own unit
-// and name them as it likes, but not above it.
+// SO_PEERCRED gives the peer's pid and uid; /proc/<pid>/cgroup gives its
+// cgroup path. The caller is <id> when the path is, from its root,
//
-// This is routing, not isolation: the computer is the trust boundary.
-// Sessions that share a uid share a systemd user manager, and a process can
-// move itself into a sibling unit's cgroup. Do not co-host mutually
-// untrusted tenants on one computer.
+// slices and user managers / slack-presence-runners.slice / sp-runner-<id>.service [/ anything]
+//
+// Anchored, not "contains": a session owns the cgroup subtree below its unit
+// (a container's is delegated to it) and can create cgroups of any name
+// there, but none above or beside its unit. So the element right below the
+// runners' slice is read, nothing after it, and nothing but slices and
+// `user@<uid>.service` may come before the slice.
+//
+// With -caller-uid, a peer of any other uid is no caller: in a session's
+// container every other uid is one of its subordinate ids (its root, for
+// one), and those are not the session. The root of a container the session
+// nests as itself is that uid again, the session's own (1500), and is the
+// session: the uid tells a session's user from the rest, never one session
+// from another, which is the cgroup's part.
+//
+// Where sessions run as plain units of one user (no containers), this is
+// routing, not isolation: they share a systemd user manager, and a process
+// can move itself into a sibling unit's cgroup. A container cannot: it sees
+// only its own subtree of the hierarchy.
//
// -identity=single is for a computer that runs one session outside systemd:
// every connection is the caller singleCaller, which the binder binds.
@@ -23,10 +36,19 @@ import (
"net"
"os"
"path/filepath"
+ "regexp"
"strconv"
"strings"
)
+// runnersSlice is the slice every session's unit is a direct child of
+// (computer/src/host/runner-limits.ts starts them with --slice=).
+const runnersSlice = "slack-presence-runners.slice"
+
+// userManager is a user's systemd instance, the one non-slice element above
+// the runners' slice when sessions are units of a user.
+var userManager = regexp.MustCompile(`^user@[0-9]+\.service$`)
+
// Resolver maps an accepted API connection to its caller ("" if none).
// Tests inject their own; a deployment uses peerResolver or singleResolver.
type Resolver func(c net.Conn) string
@@ -42,7 +64,7 @@ func callerFromCgroup(r io.Reader) string {
if len(parts) != 3 {
continue
}
- u := firstRunner(parts[2])
+ u := runnerOf(parts[2])
if u == "" {
continue
}
@@ -58,11 +80,19 @@ func callerFromCgroup(r io.Reader) string {
return other
}
-// firstRunner is the caller named by the first runner unit in a cgroup path.
-func firstRunner(path string) string {
- for elem := range strings.SplitSeq(path, "/") {
- if c := callerOfUnit(elem); c != "" {
- return c
+// runnerOf is the caller a cgroup path names: the unit right below the
+// runners' slice, when only slices and user managers lead to that slice.
+func runnerOf(path string) string {
+ elems := strings.Split(strings.TrimPrefix(path, "/"), "/")
+ for i, elem := range elems {
+ if elem == runnersSlice {
+ if i+1 < len(elems) {
+ return callerOfUnit(elems[i+1])
+ }
+ return ""
+ }
+ if !strings.HasSuffix(elem, ".slice") && !userManager.MatchString(elem) {
+ return ""
}
}
return ""
@@ -95,11 +125,15 @@ const singleCaller = "single"
func singleResolver(net.Conn) string { return singleCaller }
+// anyUID is -caller-uid's default: the peer's uid is not looked at.
+const anyUID = -1
+
// peerResolver is the cgroup Resolver: SO_PEERCRED pid → cgroup → caller.
-func peerResolver(procRoot string) Resolver {
+// uid: the only uid a caller may have, or anyUID.
+func peerResolver(procRoot string, uid int) Resolver {
return func(c net.Conn) string {
- pid, ok := peerPid(c)
- if !ok {
+ pid, peerUID, ok := peerCred(c)
+ if !ok || (uid != anyUID && peerUID != uid) {
return ""
}
return callerOfPid(procRoot, pid)
diff --git a/computer/modelproxy/identity_test.go b/computer/modelproxy/identity_test.go
index d625e24a..9bdc5d0a 100644
--- a/computer/modelproxy/identity_test.go
+++ b/computer/modelproxy/identity_test.go
@@ -11,21 +11,35 @@ import (
)
func TestCallerFromCgroup(t *testing.T) {
+ const user = "/user.slice/user-1500.slice/[email protected]/slack.slice/slack-presence.slice/slack-presence-runners.slice"
cases := map[string]string{
- "0::/user.slice/user-1500.slice/[email protected]/app.slice/sp-runner-abc123.service\n": "abc123",
- // a child cgroup below the unit
- "0::/user.slice/user-1500.slice/[email protected]/app.slice/sp-runner-abc123.service/tasks\n": "abc123",
- // the first matching element wins: a process can create a cgroup
- // below its own unit and name it like another, not one above it
- "0::/user.slice/[email protected]/app.slice/sp-runner-outer.service/sp-runner-inner.service\n": "outer",
+ "0::" + user + "/sp-runner-abc123.service\n": "abc123",
+ // a session's container: its payload, and what it creates below
+ "0::" + user + "/sp-runner-abc123.service/libpod-payload-0f3a\n": "abc123",
+ "0::" + user + "/sp-runner-abc123.service/libpod-payload-0f3a/tasks\n": "abc123",
+ // a system unit, should sessions ever be started as such
+ "0::/slack.slice/slack-presence-runners.slice/sp-runner-sys.service\n": "sys",
+ // only the element right below the slice is read: a session can
+ // create cgroups below its own unit and name them as it likes
+ "0::" + user + "/sp-runner-outer.service/sp-runner-inner.service\n": "outer",
+ "0::" + user + "/sp-runner-outer.service/libpod-payload-0f3a/slack-presence-runners.slice/sp-runner-x.service\n": "outer",
+ // a unit of that name anywhere else is not a runner
+ "0::/user.slice/user-1500.slice/[email protected]/app.slice/sp-runner-abc123.service\n": "",
+ "0::" + user + "/other.service/sp-runner-abc123.service\n": "",
+ "0::/user.slice/user-1500.slice/[email protected]/app.slice/x.service/slack-presence-runners.slice/sp-runner-abc123.service\n": "",
+ "0::/user.slice/user-1500.slice/session-3.scope/slack-presence-runners.slice/sp-runner-abc123.service\n": "",
+ "0::/user.slice/[email protected]/slack-presence-runners.slice/sp-runner-abc123.service\n": "",
// hybrid hierarchy: the v2 line wins over v1 lines
- "12:pids:/user.slice/sp-runner-v1.service\n0::/user.slice/[email protected]/app.slice/sp-runner-v2.service\n": "v2",
- "12:pids:/user.slice/sp-runner-v1.service\n0::/user.slice\n": "v1",
- "0::/user.slice/user-1500.slice/session-3.scope\n": "",
- "0::/user.slice/[email protected]/app.slice/sp-runner-.service\n": "",
- "0::/user.slice/[email protected]/app.slice/sp-runner-a b.service\n": "",
- "0::/user.slice/[email protected]/app.slice/sp-runner-x.scope\n": "",
- "0::/user.slice/[email protected]/app.slice/oc-sp-runner-x.service\n": "",
+ "12:pids:" + user + "/sp-runner-v1.service\n0::" + user + "/sp-runner-v2.service\n": "v2",
+ "12:pids:" + user + "/sp-runner-v1.service\n0::/user.slice\n": "v1",
+ "0::/user.slice/user-1500.slice/session-3.scope\n": "",
+ "0::" + user + "\n": "",
+ "0::" + user + "/\n": "",
+ "0::" + user + "/sp-runner-.service\n": "",
+ "0::" + user + "/sp-runner-a b.service\n": "",
+ "0::" + user + "/sp-runner-x.scope\n": "",
+ "0::" + user + "/oc-sp-runner-x.service\n": "",
+ "0::" + user + "x/sp-runner-abc.service\n": "",
"garbage": "",
"": "",
}
@@ -39,7 +53,7 @@ func TestCallerFromCgroup(t *testing.T) {
func TestCallerOfPidFromProcRoot(t *testing.T) {
root := t.TempDir()
os.MkdirAll(filepath.Join(root, "4242"), 0o755)
- os.WriteFile(filepath.Join(root, "4242", "cgroup"), []byte("0::/user.slice/user-1500.slice/[email protected]/app.slice/sp-runner-abc123.service\n"), 0o644)
+ os.WriteFile(filepath.Join(root, "4242", "cgroup"), []byte("0::/user.slice/user-1500.slice/[email protected]/slack-presence-runners.slice/sp-runner-abc123.service\n"), 0o644)
if u := callerOfPid(root, 4242); u != "abc123" {
t.Fatalf("got %q", u)
}
@@ -64,7 +78,7 @@ func TestPeerResolver(t *testing.T) {
root := t.TempDir()
pid := os.Getpid()
os.MkdirAll(filepath.Join(root, strconv.Itoa(pid)), 0o755)
- os.WriteFile(filepath.Join(root, strconv.Itoa(pid), "cgroup"), []byte("0::/app.slice/sp-runner-me.service\n"), 0o644)
+ os.WriteFile(filepath.Join(root, strconv.Itoa(pid), "cgroup"), []byte("0::/slack-presence-runners.slice/sp-runner-me.service\n"), 0o644)
go func() {
c, err := net.Dial("unix", filepath.Join(dir, "a.sock"))
if err == nil {
@@ -77,10 +91,18 @@ func TestPeerResolver(t *testing.T) {
t.Fatal(err)
}
defer c.Close()
- if u := peerResolver(root)(c); u != "me" {
+ if u := peerResolver(root, anyUID)(c); u != "me" {
t.Fatalf("got %q", u)
}
- if u := peerResolver(root)(&net.TCPConn{}); u != "" {
+ // -caller-uid: this process's own uid is a caller, any other is not,
+ // whatever its cgroup says (a container's root is a subordinate uid).
+ if u := peerResolver(root, os.Getuid())(c); u != "me" {
+ t.Fatalf("own uid: got %q", u)
+ }
+ if u := peerResolver(root, os.Getuid()+1)(c); u != "" {
+ t.Fatalf("another uid: got %q", u)
+ }
+ if u := peerResolver(root, anyUID)(&net.TCPConn{}); u != "" {
t.Fatalf("non-unix conn: %q", u)
}
}
diff --git a/computer/modelproxy/main.go b/computer/modelproxy/main.go
index c2065807..30528529 100644
--- a/computer/modelproxy/main.go
+++ b/computer/modelproxy/main.go
@@ -39,6 +39,7 @@ type config struct {
profilesDir string
placeholder string
identity string // cgroup | single
+ callerUID int // -identity=cgroup: the only uid a caller may have; anyUID: any
bindingsFile string
hold, drain time.Duration
maxInflightPerCaller int
@@ -122,6 +123,7 @@ func parseFlags(args []string) (config, runMode, error) {
fs.StringVar(&cfg.profilesDir, "profiles", "/etc/oc-modelproxy/profiles.d", "directory of profile files (*.json)")
fs.StringVar(&cfg.placeholder, "placeholder", "ssh-placeholder", "the only credential a caller may send: `Authorization: Bearer <it>` or `x-api-key: <it>`")
fs.StringVar(&cfg.identity, "identity", "cgroup", "how a caller is named: cgroup (<id> of its sp-runner-<id>.service unit) or single (every caller is "+singleCaller+")")
+ fs.IntVar(&cfg.callerUID, "caller-uid", anyUID, "with -identity=cgroup, the only uid a caller may have (the sessions' user); -1: any")
fs.StringVar(&cfg.bindingsFile, "bindings-file", "/run/oc-modelproxy/profile-bindings.json", "persisted bindings, without their variables (empty: do not persist)")
fs.DurationVar(&cfg.hold, "hold-timeout", 10*time.Second, "how long a request waits for its caller's credential, and then for a free upstream connection")
fs.DurationVar(&cfg.drain, "drain-timeout", 630*time.Second, "on SIGTERM or after a handoff, how long in-flight streams may finish")
@@ -153,7 +155,7 @@ func run(cfg config) error {
var resolve Resolver
switch cfg.identity {
case "cgroup":
- resolve = peerResolver(cmp.Or(cfg.procRoot, "/proc"))
+ resolve = peerResolver(cmp.Or(cfg.procRoot, "/proc"), cfg.callerUID)
case "single":
resolve = singleResolver
default:
diff --git a/computer/modelproxy/main_test.go b/computer/modelproxy/main_test.go
index e815fd1c..a9dbd9bc 100644
--- a/computer/modelproxy/main_test.go
+++ b/computer/modelproxy/main_test.go
@@ -8,7 +8,7 @@ import (
func TestParseFlags(t *testing.T) {
cfg, mode, err := parseFlags(nil)
- if err != nil || mode != modeServe || cfg.identity != "cgroup" || cfg.maxInflightPerCaller != 32 {
+ if err != nil || mode != modeServe || cfg.identity != "cgroup" || cfg.callerUID != anyUID || cfg.maxInflightPerCaller != 32 {
t.Fatalf("defaults: %+v %v %v", cfg, mode, err)
}
if _, mode, err := parseFlags([]string{"-version"}); err != nil || mode != modeVersion {
diff --git a/computer/modelproxy/peer_linux.go b/computer/modelproxy/peer_linux.go
index 750066ae..f674939e 100644
--- a/computer/modelproxy/peer_linux.go
+++ b/computer/modelproxy/peer_linux.go
@@ -7,23 +7,24 @@ import (
"syscall"
)
-// peerPid returns the pid of the process on the other end of a Unix socket
-// connection, from SO_PEERCRED (taken by the kernel at connect time).
-func peerPid(c net.Conn) (int, bool) {
+// peerCred returns the pid and uid of the process on the other end of a Unix
+// socket connection, from SO_PEERCRED (taken by the kernel at connect time).
+// The uid is as this process sees it: a container's root is a subordinate uid.
+func peerCred(c net.Conn) (pid, uid int, ok bool) {
uc, ok := c.(*net.UnixConn)
if !ok {
- return 0, false
+ return 0, 0, false
}
raw, err := uc.SyscallConn()
if err != nil {
- return 0, false
+ return 0, 0, false
}
var cred *syscall.Ucred
var serr error
if err := raw.Control(func(fd uintptr) {
cred, serr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
}); err != nil || serr != nil || cred == nil {
- return 0, false
+ return 0, 0, false
}
- return int(cred.Pid), true
+ return int(cred.Pid), int(cred.Uid), true
}
diff --git a/computer/modelproxy/peer_other.go b/computer/modelproxy/peer_other.go
index 52e8dd93..472ad7fa 100644
--- a/computer/modelproxy/peer_other.go
+++ b/computer/modelproxy/peer_other.go
@@ -4,5 +4,5 @@ package main
import "net"
-// peerPid is Linux-only (SO_PEERCRED); elsewhere no caller is a runner.
-func peerPid(net.Conn) (int, bool) { return 0, false }
+// peerCred is Linux-only (SO_PEERCRED); elsewhere no caller is a runner.
+func peerCred(net.Conn) (pid, uid int, ok bool) { return 0, 0, false }