git.sr.ht/gitsrht-shell/main.go -rw-r--r-- 11.0 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/exec"
	gopath "path"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"

	"github.com/google/shlex"
	_ "github.com/lib/pq"
	"github.com/vaughan0/go-ini"
)

const (
	ACCESS_NONE   = 0
	ACCESS_READ   = 1
	ACCESS_WRITE  = 2
	ACCESS_MANAGE = 4
)

func main() {
	// gitsrht-shell runs after we've authenticated the SSH session as an
	// authentic agent of a particular account, but before we've checked if
	// they have permission to perform the git operation they're trying to do.
	// Our job is to:
	//
	// 1. Find the repo they're trying to access, and handle redirects
	// 2. Check if they're allowed to do the thing they're trying to
	// 3. exec(2) into the git binary that does the rest of the work

	var (
		config ini.File
		err    error
		logger *log.Logger

		pusherId   int
		pusherName string

		origin         string
		repos          string
		siteOwnerName  string
		siteOwnerEmail string
		postUpdate     string

		cmdstr string
		cmd    []string
	)

	// Initialization and set up, collect our runtime needs
	log.SetFlags(0)
	logf, err := os.OpenFile("/var/log/gitsrht-shell",
		os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		log.Printf("Warning: unable to open log file: %v "+
			"(using stderr instead)", err)
		logger = log.New(os.Stderr, "", log.LstdFlags)
	} else {
		logger = log.New(logf, "", log.LstdFlags)
	}

	if len(os.Args) < 3 {
		logger.Fatalf("Expected two arguments from SSH")
	}
	logger.Printf("os.Args: %v", os.Args)

	if pusherId, err = strconv.Atoi(os.Args[1]); err != nil {
		logger.Fatalf("Couldn't interpret user ID: %v", err)
	}
	pusherName = os.Args[2]

	for _, path := range []string{"../config.ini", "/etc/sr.ht/config.ini"} {
		config, err = ini.LoadFile(path)
		if err == nil {
			break
		}
	}
	if err != nil {
		logger.Fatalf("Failed to load config file: %v", err)
	}

	origin, ok := config.Get("git.sr.ht", "origin")
	if !ok {
		logger.Fatalf("No origin configured for git.sr.ht")
	}

	repos, ok = config.Get("git.sr.ht", "repos")
	if !ok {
		logger.Fatalf("No repo path configured for git.sr.ht")
	}

	postUpdate, ok = config.Get("git.sr.ht", "post-update-script")
	if !ok {
		logger.Fatalf("No post-update script configured for git.sr.ht")
	}

	siteOwnerName, _ = config.Get("sr.ht", "owner-name")
	siteOwnerEmail, _ = config.Get("sr.ht", "owner-email")

	cmdstr, ok = os.LookupEnv("SSH_ORIGINAL_COMMAND")
	if !ok {
		cmdstr = ""
	}

	if pushUuid, ok := os.LookupEnv("SRHT_PUSH"); ok {
		logger.Printf("Running shell for push %s", pushUuid)
	}

	// Grab the command the user is trying to execute
	cmd, err = shlex.Split(cmdstr)
	if err != nil {
		logger.Fatalf("Unable to parse command: %v", err)
	}

	// Make sure it's a git command that we're expecting
	validCommands := []string{
		"git-receive-pack", "git-upload-pack", "git-upload-archive",
	}
	var valid bool
	for _, c := range validCommands {
		if len(cmd) > 0 && c == cmd[0] {
			valid = true
		}
	}

	if !valid {
		logger.Printf("Not permitting unacceptable command: %v", cmd)
		log.Printf("Hi %s! You've successfully authenticated, "+
			"but I do not provide an interactive shell. Bye!", pusherName)
		os.Exit(128)
	}

	os.Chdir(repos)

	// Validate the path that they're trying to access is in the repos directory
	path := cmd[len(cmd)-1]
	path, err = filepath.Abs(path)
	if err != nil {
		logger.Fatalf("filepath.Abs(%s): %v", path, err)
	}
	if !strings.HasPrefix(path, repos) {
		path = gopath.Join(repos, path)
	}
	cmd[len(cmd)-1] = path

	// Check what kind of access they're interested in
	needsAccess := ACCESS_READ
	if cmd[0] == "git-receive-pack" {
		needsAccess = ACCESS_WRITE
	}

	// Fetch the necessary info from SQL. This first query fetches:
	//
	// 1. Repository information, such as visibility (public|unlisted|private)
	// 2. Information about the repository owner's account
	// 3. Information about the pusher's account
	// 4. Any access control policies for that repo that apply to the pusher
	pgcs, ok := config.Get("git.sr.ht", "connection-string")
	if !ok {
		logger.Fatalf("No connection string configured for git.sr.ht: %v", err)
	}
	db, err := sql.Open("postgres", pgcs)
	if err != nil {
		logger.Fatalf("Failed to open a database connection: %v", err)
	}

	// Note: when updating push access logic, also update scm.sr.ht/access.py
	var (
		repoId              int
		repoName            string
		repoOwnerId         int
		repoOwnerName       string
		repoVisibility      string
		pusherType          string
		pusherSuspendNotice *string
		accessGrant         *string
	)
	logger.Printf("Looking up repo: pusher ID %d, repo path %s", pusherId, path)
	row := db.QueryRow(`
		SELECT
			repo.id,
			repo.name,
			repo.owner_id,
			owner.username,
			repo.visibility,
			pusher.user_type,
			pusher.suspension_notice,
			access.mode
		FROM repository repo
		JOIN "user" owner  ON owner.id  = repo.owner_id
		JOIN "user" pusher ON pusher.id = $1
		LEFT JOIN access
			ON (access.repo_id = repo.id AND access.user_id = $1)
		WHERE
			repo.path = $2;
	`, pusherId, path)
	if err := row.Scan(&repoId, &repoName, &repoOwnerId, &repoOwnerName,
		&repoVisibility, &pusherType, &pusherSuspendNotice, &accessGrant); err != nil {

		logger.Printf("Lookup failed: %v", err)
		logger.Println("Looking up redirect")

		// If looking up the repo failed, it might have been renamed. Look for a
		// corresponding redirect, and grab all of the same information that we
		// need for the new repo while we're at it.
		row = db.QueryRow(`
			SELECT
				repo.id,
				repo.name,
				repo.owner_id,
				owner.username,
				repo.visibility,
				pusher.user_type,
				pusher.suspension_notice,
				access.mode
			FROM repository repo
			JOIN "user" owner  ON owner.id  = repo.owner_id
			JOIN "user" pusher ON pusher.id = $1
			JOIN redirect      ON redirect.new_repo_id = repo.id
			LEFT JOIN access
				ON (access.repo_id = repo.id AND access.user_id = $1)
			WHERE
				redirect.path = $2;
		`, pusherId, path)

		if err := row.Scan(&repoId, &repoName, &repoOwnerId, &repoOwnerName,
			&repoVisibility, &pusherType, &pusherSuspendNotice,
			&accessGrant); err != nil {

			logger.Printf("Lookup failed: %v", err)

			// There wasn't a repo or a redirect by this name, so maybe the user
			// is pushing to a repo that doesn't exist. If so, autocreate it.
			//
			// If an error occurs at this step, we just log it internally and
			// tell the user we couldn't find the repo they're asking after.
			repoName = gopath.Base(path)
			repoOwnerName = gopath.Base(gopath.Dir(path))
			if repoOwnerName != "" {
				repoOwnerName = repoOwnerName[1:]
			}

			notFound := func(ctx string, err error) {
				if err != nil {
					logger.Printf("Error autocreating repo: %s: %v", ctx, err)
				}
				logger.Println("Repository not found.")
				log.Println("Repository not found.")
				log.Println()
				os.Exit(128)
			}

			if needsAccess == ACCESS_READ || repoOwnerName != pusherName {
				notFound("access", nil)
			}

			if needsAccess == ACCESS_WRITE {
				repoOwnerId = pusherId
				repoOwnerName = pusherName
				repoVisibility = "autocreated"

				createQuery, err := db.Prepare(`
					INSERT INTO repository (
						created,
						updated,
						name,
						owner_id,
						path,
						visibility
					) VALUES (
						NOW() at time zone 'utc',
						NOW() at time zone 'utc',
						$1, $2, $3, 'autocreated'
					) RETURNING id;
				`)
				if err != nil {
					notFound("create query prepare", err)
				}
				defer createQuery.Close()

				if err = createQuery.QueryRow(repoName, repoOwnerId, path).
					Scan(&repoId); err != nil {

					notFound("insert", err)
				}

				// Note: update gitsrht/repos.py when changing this
				if err = exec.Command("mkdir", "-p", path).Run(); err != nil {
					notFound("mkdir", err)
				}
				if err = exec.Command("git", "init",
					"--bare", path).Run(); err != nil {

					notFound("git init", err)
				}
				if err = exec.Command("ln", "-s", postUpdate,
					gopath.Join(path, "hooks", "update")).Run(); err != nil {

					notFound("ln update", err)
				}
				if err = exec.Command("ln", "-s", postUpdate,
					gopath.Join(path, "hooks", "post-update")).Run(); err != nil {

					notFound("ln post-update", err)
				}

				logger.Printf("Autocreated repo %s", path)
			}
		} else {
			log.Printf("\033[93mNOTICE\033[0m: This repository has moved.")
			log.Printf("Please update your remote to:")
			log.Println()
			log.Printf("\t%s/~%s/%s", origin, repoOwnerName, repoName)
			log.Println()
			os.Exit(128)
		}
	}

	agrant := ""
	snotice := ""
	if accessGrant != nil {
		agrant = *accessGrant
	}
	if pusherSuspendNotice != nil {
		snotice = *pusherSuspendNotice
	}
	logger.Printf("repo ID %d; name '%s'; owner ID %d; owner name '%s'; " +
		"visibility '%s'; pusher type '%s'; pusher suspension notice '%s'; " +
		"access grant '%s'", repoId, repoName, repoOwnerId, repoOwnerName,
		repoVisibility, pusherType, snotice, agrant)

	// We have everything we need, now we find out if the user is allowed to do
	// what they're trying to do.
	hasAccess := ACCESS_NONE
	if pusherId == repoOwnerId {
		hasAccess = ACCESS_READ | ACCESS_WRITE | ACCESS_MANAGE
	} else {
		if accessGrant == nil {
			switch repoVisibility {
			case "public":
				fallthrough
			case "unlisted":
				hasAccess = ACCESS_READ
			case "private":
				fallthrough
			default:
				hasAccess = ACCESS_NONE
			}
		} else {
			switch *accessGrant {
			case "r":
				hasAccess = ACCESS_READ
			case "rw":
				hasAccess = ACCESS_READ | ACCESS_WRITE
			default:
				hasAccess = ACCESS_NONE
			}
		}
	}

	if needsAccess&hasAccess != needsAccess {
		logger.Println("Access denied.")
		log.Println("Access denied.")
		log.Println()
		os.Exit(128)
	}

	if pusherType == "suspended" {
		log.Println("Your account has been suspended for the following reason:")
		log.Println()
		log.Println("\t" + *pusherSuspendNotice)
		log.Println()
		log.Printf("Please contact support: %s <%s>",
			siteOwnerName, siteOwnerEmail)
		log.Println()
		os.Exit(128)
	}

	// At this point, we know they're allowed to execute this operation. We
	// gather some of the information we've collected so far into a "push
	// context" so that steps later in the pipeline don't have to repeat our
	// lookups, then exec(2) into git.
	type RepoContext struct {
		Id         int    `json:"id"`
		Name       string `json:"name"`
		Path       string `json:"path"`
		Visibility string `json:"visibility"`
	}

	type UserContext struct {
		CanonicalName string `json:"canonical_name"`
		Name          string `json:"name"`
	}

	pushContext, _ := json.Marshal(struct {
		Repo RepoContext `json:"repo"`
		User UserContext `json:"user"`
	}{
		Repo: RepoContext{
			Id:         repoId,
			Name:       repoName,
			Path:       path,
			Visibility: repoVisibility,
		},
		User: UserContext{
			CanonicalName: "~" + pusherName,
			Name:          pusherName,
		},
	})

	logger.Printf("Executing command: %v", cmd)
	bin, err := exec.LookPath(cmd[0])
	if err != nil {
		logger.Fatalf("exec.LookPath: %v", err)
	}
	if err := syscall.Exec(bin, cmd, append(os.Environ(), fmt.Sprintf(
		"SRHT_PUSH_CTX=%s", string(pushContext)))); err != nil {

		logger.Fatalf("syscall.Exec: %v", err)
	}
}