pico

created pr with pico/pico-ssh-impersonate.1 on 2026-11-26T16:14:35Z · by c8ef7d19
cmds
checkout latest patchset:
ssh pr.pico.sh pull pico:pico-ssh-impersonate | git am -3
checkout specific patchset revision:
ssh pr.pico.sh pull pico:pico-ssh-impersonate [rev] | git am -3
add changes to patch request:
git format-patch main --stdout | ssh pr.pico.sh pico:pico-ssh-impersonate
add comment to patch request:
ssh pr.pico.sh comment pico:pico-ssh-impersonate "lgtm!"
+19 -5 pkg/apps/pico/cli.go #
......@@ -22,11 +22,25 @@ func getUser(s *pssh.SSHServerConnSession, dbpool db.DB) (*db.User, error) {
2222 return nil, fmt.Errorf("key not found")
2323 }
2424
25- key := shared.KeyForKeyText(s.PublicKey())
26-
27- user, err := dbpool.FindUserByKey(s.User(), key)
28- if err != nil {
29- return nil, err
25+ user := pssh.GetUser(s)
26+ if user == nil {
27+ if perms := s.Permissions(); perms != nil {
28+ if userID := perms.Extensions["user_id"]; userID != "" {
29+ var err error
30+ user, err = dbpool.FindUser(userID)
31+ if err != nil {
32+ return nil, err
33+ }
34+ }
35+ }
36+ }
37+ if user == nil {
38+ key := shared.KeyForKeyText(s.PublicKey())
39+ var err error
40+ user, err = dbpool.FindUserByKey(s.User(), key)
41+ if err != nil {
42+ return nil, err
43+ }
3044 }
3145
3246 if user.Name == "" {
+161 -0 pkg/apps/pico/cli_test.go #
......@@ -0,0 +1,161 @@
1+package pico
2+
3+import (
4+ "context"
5+ "errors"
6+ "log/slog"
7+ "path/filepath"
8+ "strings"
9+ "testing"
10+ "time"
11+
12+ "github.com/picosh/pico/pkg/db"
13+ "github.com/picosh/pico/pkg/db/stub"
14+ "github.com/picosh/pico/pkg/pssh"
15+ "github.com/picosh/pico/pkg/shared"
16+ "golang.org/x/crypto/ssh"
17+)
18+
19+type cliTestDB struct {
20+ *certsDB
21+ features map[string]*db.FeatureFlag
22+}
23+
24+func (d *cliTestDB) FindUserByName(name string) (*db.User, error) {
25+ for _, u := range d.users {
26+ if u.Name == name {
27+ user := *u
28+ return &user, nil
29+ }
30+ }
31+ return nil, errors.New("user not found")
32+}
33+
34+func (d *cliTestDB) FindFeature(userID, name string) (*db.FeatureFlag, error) {
35+ if ff, ok := d.features[userID+":"+name]; ok {
36+ return ff, nil
37+ }
38+ return nil, errors.New("feature not found")
39+}
40+
41+func TestUserCommandImpersonation(t *testing.T) {
42+ now := time.Now()
43+ expires := now.Add(time.Hour)
44+ logger := slog.New(slog.DiscardHandler)
45+ adminKey := newSigner(t)
46+ aliceKey := newSigner(t)
47+ bobKey := newSigner(t)
48+
49+ cdb := &certsDB{
50+ StubDB: stub.NewStubDB(logger),
51+ users: map[string]*db.User{
52+ "admin-id": {ID: "admin-id", Name: "root", CreatedAt: &now},
53+ "alice-id": {ID: "alice-id", Name: "alice", CreatedAt: &now},
54+ "bob-id": {ID: "bob-id", Name: "bob", CreatedAt: &now},
55+ },
56+ keys: []*db.PublicKey{
57+ {ID: "k-admin", UserID: "admin-id", Name: "root-key", Key: shared.KeyForKeyText(adminKey.PublicKey()), CreatedAt: &now},
58+ {ID: "k-alice", UserID: "alice-id", Name: "alice-key", Key: shared.KeyForKeyText(aliceKey.PublicKey()), CreatedAt: &now},
59+ {ID: "k-bob", UserID: "bob-id", Name: "bob-key", Key: shared.KeyForKeyText(bobKey.PublicKey()), CreatedAt: &now},
60+ },
61+ }
62+
63+ testDB := &cliTestDB{
64+ certsDB: cdb,
65+ features: map[string]*db.FeatureFlag{
66+ "admin-id:admin": {ID: "ff-admin", UserID: "admin-id", Name: "admin", ExpiresAt: &expires},
67+ },
68+ }
69+
70+ ctx, cancel := context.WithCancel(t.Context())
71+ t.Cleanup(cancel)
72+
73+ auth := shared.NewSshAuthHandler(testDB, logger, "pico")
74+ server, err := pssh.NewSSHServerWithConfig(ctx, logger, "pico", "127.0.0.1", "0", "", filepath.Join(t.TempDir(), "host_key"),
75+ auth.OpenPubkeyAuthHandler,
76+ []pssh.SSHServerMiddleware{
77+ Middleware(&CliHandler{DBPool: testDB, Logger: logger}),
78+ pssh.LogMiddleware(NewUploadHandler(testDB, &Config{}), testDB),
79+ }, nil, nil)
80+ if err != nil {
81+ t.Fatal(err)
82+ }
83+ go func() { _ = server.ListenAndServe() }()
84+
85+ addr := ""
86+ for deadline := time.Now().Add(5 * time.Second); addr == "" && time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
87+ server.Mu.Lock()
88+ if server.Listener != nil {
89+ addr = server.Listener.Addr().String()
90+ }
91+ server.Mu.Unlock()
92+ }
93+
94+ run := func(sshUser string, signer ssh.Signer, command string) string {
95+ t.Helper()
96+ client, err := ssh.Dial("tcp", addr, &ssh.ClientConfig{
97+ User: sshUser,
98+ Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
99+ HostKeyCallback: ssh.InsecureIgnoreHostKey(),
100+ })
101+ if err != nil {
102+ t.Fatalf("ssh dial %s: %v", sshUser, err)
103+ }
104+ defer func() { _ = client.Close() }()
105+ session, err := client.NewSession()
106+ if err != nil {
107+ t.Fatalf("new session: %v", err)
108+ }
109+ out, err := session.CombinedOutput(command)
110+ if missing := (*ssh.ExitMissingError)(nil); errors.As(err, &missing) {
111+ err = nil
112+ }
113+ if err != nil {
114+ t.Fatalf("command %q as %s failed: %v (%s)", command, sshUser, err, out)
115+ }
116+ return string(out)
117+ }
118+
119+ tests := []struct {
120+ name string
121+ sshUser string
122+ signer ssh.Signer
123+ wantName string
124+ wantID string
125+ }{
126+ {
127+ name: "admin impersonates alice",
128+ sshUser: "admin__alice",
129+ signer: adminKey,
130+ wantName: "alice",
131+ wantID: "alice-id",
132+ },
133+ {
134+ name: "non-admin cannot impersonate alice",
135+ sshUser: "admin__alice",
136+ signer: bobKey,
137+ wantName: "bob",
138+ wantID: "bob-id",
139+ },
140+ {
141+ name: "normal login",
142+ sshUser: "alice",
143+ signer: aliceKey,
144+ wantName: "alice",
145+ wantID: "alice-id",
146+ },
147+ }
148+
149+ for _, tt := range tests {
150+ t.Run(tt.name, func(t *testing.T) {
151+ out := run(tt.sshUser, tt.signer, "user")
152+ lines := strings.Split(strings.TrimSpace(strings.ReplaceAll(out, "\r\n", "\n")), "\n")
153+ if len(lines) < 2 {
154+ t.Fatalf("unexpected output: %q", out)
155+ }
156+ if lines[0] != tt.wantName || lines[1] != tt.wantID {
157+ t.Errorf("got user (%q, %q), want (%q, %q)", lines[0], lines[1], tt.wantName, tt.wantID)
158+ }
159+ })
160+ }
161+}
+10 -8 pkg/apps/pico/file_handler.go #
......@@ -130,15 +130,17 @@ func (h *UploadHandler) GetLogger(s *pssh.SSHServerConnSession) *slog.Logger {
130130 }
131131
132132 func (h *UploadHandler) Validate(s *pssh.SSHServerConnSession) error {
133- var err error
134- key, err := sendutils.KeyText(s)
135- if err != nil {
136- return fmt.Errorf("key not found")
137- }
133+ user := pssh.GetUser(s)
134+ if user == nil {
135+ key, err := sendutils.KeyText(s)
136+ if err != nil {
137+ return fmt.Errorf("key not found")
138+ }
138139
139- user, err := h.DBPool.FindUserByKey(s.User(), key)
140- if err != nil {
141- return err
140+ user, err = h.DBPool.FindUserByKey(s.User(), key)
141+ if err != nil {
142+ return err
143+ }
142144 }
143145
144146 if user.Name == "" {
Back to top