all repos

mugit @ 326692ce4ff8ef575ba26a643e2a1d17cc0a2b1f

🐮 git server that your cow will love

mugit/internal/ssh/ssh.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
ssh!: switch to sshd, 2 months ago
1
package ssh
2
3
import (
4
	"context"
5
	"fmt"
6
	"io"
7
	"log/slog"
8
	"strings"
9
10
	"olexsmir.xyz/mugit/internal/config"
11
	"olexsmir.xyz/mugit/internal/git"
12
13
	gossh "golang.org/x/crypto/ssh"
14
)
15
16
type Shell struct {
17
	cfg *config.Config
18
19
	keys []gossh.PublicKey
20
}
21
22
func NewShell(cfg *config.Config) (*Shell, error) {
23
	parsedKeys := make([]gossh.PublicKey, len(cfg.SSH.Keys))
24
	for i, key := range cfg.SSH.Keys {
25
		pkey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(key))
26
		if err != nil {
27
			return nil, err
28
		}
29
		parsedKeys[i] = pkey
30
	}
31
32
	return &Shell{
33
		cfg:  cfg,
34
		keys: parsedKeys,
35
	}, nil
36
}
37
38
func (s *Shell) HandleCommand(ctx context.Context, cmd string, stdin io.Reader, stdout, stderr io.Writer) error {
39
	gitCmd, repoName, err := s.parseCommand(cmd)
40
	if err != nil {
41
		slog.Error("ssh invalid command", "error", err, "raw_cmd", cmd)
42
		return err
43
	}
44
45
	repoPath, err := git.ResolvePath(s.cfg.Repo.Dir, git.ResolveName(repoName))
46
	if err != nil {
47
		slog.Error("ssh access denied", "cmd", gitCmd, "repo", repoName, "error", err)
48
		return err
49
	}
50
51
	repo, err := git.Open(repoPath, "")
52
	if err != nil {
53
		slog.Error("ssh access denied", "cmd", gitCmd, "repo", repoName, "error", err)
54
		return err
55
	}
56
57
	switch gitCmd {
58
	case "git-upload-pack":
59
		err = repo.UploadPack(ctx, false, "", stdin, stdout)
60
	case "git-upload-archive":
61
		err = repo.UploadArchive(ctx, stdin, stdout)
62
	case "git-receive-pack":
63
		err = repo.ReceivePack(ctx, stdin, stdout, stderr)
64
	default:
65
		err = fmt.Errorf("access denied: invalid git command %q", gitCmd)
66
	}
67
68
	if err != nil {
69
		slog.Error("ssh operation failed", "cmd", gitCmd, "repo", repoName, "error", err)
70
	}
71
72
	return err
73
}
74
75
func (s *Shell) AuthorizedKeys(executablePath string) string {
76
	var out strings.Builder
77
	for _, key := range s.cfg.SSH.Keys {
78
		fmt.Fprintf(&out, `command="%s shell",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s`+"\n",
79
			executablePath, key)
80
	}
81
	return out.String()
82
}
83
84
func (s *Shell) parseCommand(cmd string) (gitCmd, repoName string, err error) {
85
	cmdParts := strings.Fields(cmd)
86
	if len(cmdParts) < 2 {
87
		return "", "", fmt.Errorf("invalid command: expected 'git-cmd repo', got %q", cmd)
88
	}
89
90
	gitCmd = cmdParts[0]
91
	repoName = strings.Trim(cmdParts[1], "'\"")
92
	if repoName == "" {
93
		return "", "", fmt.Errorf("invalid command: empty repository name")
94
	}
95
96
	return gitCmd, repoName, nil
97
}