| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "net" |
| 8 | "os" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | // Only the runner's own user may talk to a step's tool socket. On a Mac |
| 15 | // the peer is read with LOCAL_PEERCRED (runner peer_darwin.go), on Linux |
| 16 | // with SO_PEERCRED; the decision is exercised through its seam, so a |
| 17 | // peer of another user, root, or one whose credential cannot be read is |
| 18 | // shut out on either. |
| 19 | func TestToolSocketPeerUID(t *testing.T) { |
| 20 | root := shortToolRoot(t) |
| 21 | ping := func(path string) (string, error) { |
| 22 | c, err := net.Dial("unix", path) |
| 23 | if err != nil { |
| 24 | return "", err |
| 25 | } |
| 26 | defer c.Close() |
| 27 | _ = c.SetDeadline(time.Now().Add(5 * time.Second)) |
| 28 | if _, err := c.Write([]byte(`{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n")); err != nil { |
| 29 | return "", err |
| 30 | } |
| 31 | return bufio.NewReader(c).ReadString('\n') |
| 32 | } |
| 33 | open := func() *toolSocket { |
| 34 | t.Helper() |
| 35 | s, err := openToolSet(context.Background(), root, converseSet(false), nil) |
| 36 | if err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | t.Cleanup(s.Close) |
| 40 | return s |
| 41 | } |
| 42 | // The real credential: this process is its own peer. |
| 43 | if reply, err := ping(open().Path); err != nil || !strings.Contains(reply, `"result"`) { |
| 44 | t.Fatalf("the runner's own user was refused: %q %v", reply, err) |
| 45 | } |
| 46 | defer func(f func(int) (uint32, error)) { toolPeerUID = f }(toolPeerUID) |
| 47 | own := uint32(os.Getuid()) |
| 48 | for name, seam := range map[string]func(int) (uint32, error){ |
| 49 | "another user": func(int) (uint32, error) { return own + 1, nil }, |
| 50 | "root": func(int) (uint32, error) { return 0, nil }, |
| 51 | "unknown": func(int) (uint32, error) { return own, errors.New("no credential") }, |
| 52 | } { |
| 53 | if own == 0 && name == "root" { |
| 54 | continue |
| 55 | } |
| 56 | toolPeerUID = seam |
| 57 | if reply, err := ping(open().Path); err == nil || reply != "" { |
| 58 | t.Fatalf("%s was answered: %q %v", name, reply, err) |
| 59 | } |
| 60 | } |
| 61 | toolPeerUID = func(int) (uint32, error) { return own, nil } |
| 62 | if reply, err := ping(open().Path); err != nil || !strings.Contains(reply, `"result"`) { |
| 63 | t.Fatalf("the seam's own user was refused: %q %v", reply, err) |
| 64 | } |
| 65 | } |
| 66 | |