all repos

mugit @ 57f9c82

🐮 git server that your cow will love

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

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
ssh: print modt on clone/push, 28 days ago
1
package ssh
2
3
import (
4
	"context"
5
	"errors"
6
	"fmt"
7
	"io"
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
		return s.replyWithGitError(stderr, "access denied: invalid command", err)
42
	}
43
44
	repoPath, err := git.ResolvePath(s.cfg.Repo.Dir, git.ResolveName(repoName))
45
	if err != nil {
46
		return s.replyWithGitError(stderr, "access denied", err)
47
	}
48
49
	repo, err := git.Open(repoPath, "")
50
	if err != nil {
51
		if !errors.Is(err, git.ErrRepoNotFound) || gitCmd != "git-receive-pack" {
52
			return s.replyWithGitError(stderr, "repository not found", err)
53
		}
54
55
		// SSH Git clients display informational messages from stderr; stdout must remain protocol-only for git-receive-pack.
56
		if ierr := s.replyWithGitInfo(stderr, "auto-initializing "+repoName); ierr != nil {
57
			return ierr
58
		}
59
60
		if ierr := git.Init(repoPath); ierr != nil {
61
			return s.replyWithGitError(stderr, "failed to init repo", ierr)
62
		}
63
64
		repo, err = git.Open(repoPath, "")
65
		if err != nil {
66
			return s.replyWithGitError(stderr, "failed to open initialized repo", err)
67
		}
68
	}
69
70
	if s.cfg.Meta.Modt != "" {
71
		fmt.Fprintln(stderr, s.cfg.Meta.Modt)
72
	}
73
74
	switch gitCmd {
75
	case "git-upload-pack":
76
		err = repo.UploadPack(ctx, false, "", stdin, stdout)
77
	case "git-upload-archive":
78
		err = repo.UploadArchive(ctx, stdin, stdout)
79
	case "git-receive-pack":
80
		err = repo.ReceivePack(ctx, stdin, stdout, stderr)
81
	default:
82
		msg := "access denied: invalid git command"
83
		return s.replyWithGitError(stderr, msg, errors.New(msg))
84
	}
85
86
	if err != nil {
87
		return err
88
	}
89
90
	return nil
91
}
92
93
func (s *Shell) AuthorizedKeys(executablePath string) string {
94
	var out strings.Builder
95
	for _, key := range s.cfg.SSH.Keys {
96
		fmt.Fprintf(&out, `command="%s shell",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s`+"\n",
97
			executablePath, key)
98
	}
99
	return out.String()
100
}
101
102
var validCommands = map[string]bool{
103
	"git-upload-pack":    true,
104
	"git-upload-archive": true,
105
	"git-receive-pack":   true,
106
}
107
108
func (s *Shell) parseCommand(cmd string) (gitCmd, repoName string, err error) {
109
	cmdParts := strings.Fields(cmd)
110
	if len(cmdParts) != 2 {
111
		return "", "", fmt.Errorf("invalid command: expected 'git-cmd repo', got %q", cmd)
112
	}
113
114
	gitCmd = cmdParts[0]
115
	if !validCommands[gitCmd] {
116
		return "", "", fmt.Errorf("invalid command: disallowed command")
117
	}
118
119
	repoName = strings.Trim(cmdParts[1], "'\"")
120
	if repoName == "" {
121
		return "", "", fmt.Errorf("invalid command: empty repository name")
122
	}
123
124
	return gitCmd, repoName, nil
125
}
126
127
func (s *Shell) replyWithGitError(stderr io.Writer, msg string, cause error) error {
128
	if _, err := fmt.Fprintf(stderr, "error: %s\n", msg); err != nil {
129
		return err
130
	}
131
132
	return cause
133
}
134
135
func (s *Shell) replyWithGitInfo(msgOut io.Writer, msg string) error {
136
	_, err := fmt.Fprintf(msgOut, "info: %s\n", msg)
137
	return err
138
}