Lindenii Project Forge
Login
Commit info
ID114dd59d703d00efe86ad02eb956aa5343daa08e
AuthorRunxi Yu<me@runxiyu.org>
Author dateWed, 19 Feb 2025 21:24:47 +0800
CommitterRunxi Yu<me@runxiyu.org>
Committer dateWed, 19 Feb 2025 21:24:47 +0800
Actions
Get patch
all: Use COALESCE to handle some nullable database fields
package main

import (
	"bytes"
	"context"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"net"
	"os"
	"path/filepath"
	"strings"
	"syscall"

	"github.com/jackc/pgx/v5"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
)

var (
	err_get_fd    = errors.New("unable to get file descriptor")
	err_get_ucred = errors.New("failed getsockopt")
)

// hooks_handle_connection handles a connection from git_hooks_client via the
// unix socket.
func hooks_handle_connection(conn net.Conn) {
	defer conn.Close()
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// There aren't reasonable cases where someone would run this as
	// another user.
	ucred, err := get_ucred(conn)
	if err != nil {
		if _, err := conn.Write([]byte{1}); err != nil {
			return
		}
		fmt.Fprintln(conn, "Unable to get peer credentials:", err.Error())
		return
	}
	if ucred.Uid != uint32(os.Getuid()) {
		if _, err := conn.Write([]byte{1}); err != nil {
			return
		}
		fmt.Fprintln(conn, "UID mismatch")
		return
	}

	cookie := make([]byte, 64)
	_, err = conn.Read(cookie)
	if err != nil {
		if _, err := conn.Write([]byte{1}); err != nil {
			return
		}
		fmt.Fprintln(conn, "Failed to read cookie:", err.Error())
		return
	}

	pack_to_hook, ok := pack_to_hook_by_cookie.Load(string(cookie))
	if !ok {
		if _, err := conn.Write([]byte{1}); err != nil {
			return
		}
		fmt.Fprintln(conn, "Invalid handler cookie")
		return
	}

	ssh_stderr := pack_to_hook.session.Stderr()

	hook_return_value := func() byte {
		var argc64 uint64
		err = binary.Read(conn, binary.NativeEndian, &argc64)
		if err != nil {
			fmt.Fprintln(ssh_stderr, "Failed to read argc:", err.Error())
			return 1
		}
		var args []string
		for i := uint64(0); i < argc64; i++ {
			var arg bytes.Buffer
			for {
				b := make([]byte, 1)
				n, err := conn.Read(b)
				if err != nil || n != 1 {
					fmt.Fprintln(ssh_stderr, "Failed to read arg:", err.Error())
					return 1
				}
				if b[0] == 0 {
					break
				}
				arg.WriteByte(b[0])
			}
			args = append(args, arg.String())
		}

		var stdin bytes.Buffer
		_, err = io.Copy(&stdin, conn)
		if err != nil {
			fmt.Fprintln(conn, "Failed to read to the stdin buffer:", err.Error())
		}

		switch filepath.Base(args[0]) {
		case "pre-receive":
			if pack_to_hook.direct_access {
				return 0
			} else {
				all_ok := true
				for {
					line, err := stdin.ReadString('\n')
					if errors.Is(err, io.EOF) {
						break
					}
					line = line[:len(line)-1]

					old_oid, rest, found := strings.Cut(line, " ")
					if !found {
						fmt.Fprintln(ssh_stderr, "Invalid pre-receive line:", line)
						return 1
					}

					new_oid, ref_name, found := strings.Cut(rest, " ")
					if !found {
						fmt.Fprintln(ssh_stderr, "Invalid pre-receive line:", line)
						return 1
					}

					if strings.HasPrefix(ref_name, "refs/heads/contrib/") {
						if all_zero_num_string(old_oid) { // New branch
							fmt.Fprintln(ssh_stderr, "Acceptable push to new contrib branch: "+ref_name)
							_, err = database.Exec(ctx,
								"INSERT INTO merge_requests (repo_id, creator, source_ref, status) VALUES ($1, $2, $3, 'open')",
								pack_to_hook.repo_id, pack_to_hook.user_id, strings.TrimPrefix(ref_name, "refs/heads/contrib/"),
							)
							if err != nil {
								fmt.Fprintln(ssh_stderr, "Error creating merge request:", err.Error())
								return 1
							}
						} else { // Existing contrib branch
							var existing_merge_request_user_id int
							err = database.QueryRow(ctx,
								"SELECT creator FROM merge_requests WHERE source_ref = $1 AND repo_id = $2",
								"SELECT COALESCE(creator, 0) FROM merge_requests WHERE source_ref = $1 AND repo_id = $2",
								strings.TrimPrefix(ref_name, "refs/heads/contrib/"), pack_to_hook.repo_id,
							).Scan(&existing_merge_request_user_id)
							if err != nil {
								if errors.Is(err, pgx.ErrNoRows) {
									fmt.Fprintln(ssh_stderr, "No existing merge request for existing contrib branch:", err.Error())
								} else {
									fmt.Fprintln(ssh_stderr, "Error querying for existing merge request:", err.Error())
								}
								return 1
							}
							if existing_merge_request_user_id == 0 {
								all_ok = false
								fmt.Fprintln(ssh_stderr, "Rejecting push to merge request with no owner", ref_name)
								continue
							}

							if existing_merge_request_user_id != pack_to_hook.user_id {
								all_ok = false
								fmt.Fprintln(ssh_stderr, "Rejecting push to existing contrib branch owned by another user:", ref_name)
								continue
							}

							repo, err := git.PlainOpen(pack_to_hook.repo_path)
							if err != nil {
								fmt.Fprintln(ssh_stderr, "Daemon failed to open repo:", err.Error())
								return 1
							}

							old_hash := plumbing.NewHash(old_oid)

							old_commit, err := repo.CommitObject(old_hash)
							if err != nil {
								fmt.Fprintln(ssh_stderr, "Daemon failed to get old commit:", err.Error())
								return 1
							}

							// Potential BUG: I'm not sure if new_commit is guaranteed to be
							// detectable as they haven't been merged into the main repo's
							// objects yet. But it seems to work, and I don't think there's
							// any reason for this to only work intermitently.
							new_hash := plumbing.NewHash(new_oid)
							new_commit, err := repo.CommitObject(new_hash)
							if err != nil {
								fmt.Fprintln(ssh_stderr, "Daemon failed to get new commit:", err.Error())
								return 1
							}

							is_ancestor, err := old_commit.IsAncestor(new_commit)
							if err != nil {
								fmt.Fprintln(ssh_stderr, "Daemon failed to check if old commit is ancestor:", err.Error())
								return 1
							}

							if !is_ancestor {
								// TODO: Create MR snapshot ref instead
								all_ok = false
								fmt.Fprintln(ssh_stderr, "Rejecting force push to contrib branch: "+ref_name)
								continue
							}

							fmt.Fprintln(ssh_stderr, "Acceptable push to existing contrib branch: "+ref_name)
						}
					} else { // Non-contrib branch
						all_ok = false
						fmt.Fprintln(ssh_stderr, "Rejecting push to non-contrib branch: "+ref_name)
					}
				}

				if all_ok {
					return 0
				} else {
					return 1
				}
			}
		default:
			fmt.Fprintln(ssh_stderr, "Invalid hook:", args[0])
			return 1
		}
	}()

	_, _ = conn.Write([]byte{hook_return_value})
}

func serve_git_hooks(listener net.Listener) error {
	for {
		conn, err := listener.Accept()
		if err != nil {
			return err
		}
		go hooks_handle_connection(conn)
	}
}

func get_ucred(conn net.Conn) (*syscall.Ucred, error) {
	unix_conn := conn.(*net.UnixConn)
	fd, err := unix_conn.File()
	if err != nil {
		return nil, err_get_fd
	}
	defer fd.Close()

	ucred, err := syscall.GetsockoptUcred(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
	if err != nil {
		return nil, err_get_ucred
	}
	return ucred, nil
}

func all_zero_num_string(s string) bool {
	for _, r := range s {
		if r != '0' {
			return false
		}
	}
	return true
}
package main

import (
	"net/http"
)

func get_user_info_from_request(r *http.Request) (id int, username string, err error) {
	session_cookie, err := r.Cookie("session")
	if err != nil {
		return
	}

	err = database.QueryRow(r.Context(), "SELECT user_id, username FROM users u JOIN sessions s ON u.id = s.user_id WHERE s.session_id = $1;", session_cookie.Value).Scan(&id, &username)
	err = database.QueryRow(r.Context(), "SELECT user_id, COALESCE(username, '') FROM users u JOIN sessions s ON u.id = s.user_id WHERE s.session_id = $1;", session_cookie.Value).Scan(&id, &username)

	return
}
package main

import (
	"crypto/rand"
	"encoding/base64"
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/alexedwards/argon2id"
	"github.com/jackc/pgx/v5"
)

func handle_login(w http.ResponseWriter, r *http.Request, params map[string]any) {
	if r.Method != "POST" {
		render_template(w, "login", params)
		return
	}

	var user_id int
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")

	var password_hash string
	err := database.QueryRow(r.Context(), "SELECT id, password FROM users WHERE username = $1", username).Scan(&user_id, &password_hash)
	err := database.QueryRow(r.Context(), "SELECT id, COALESCE(password, '') FROM users WHERE username = $1", username).Scan(&user_id, &password_hash)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			params["login_error"] = "Unknown username"
			render_template(w, "login", params)
			return
		}
		http.Error(w, "Error querying user information: "+err.Error(), http.StatusInternalServerError)
		return
	}
	if password_hash == "" {
		params["login_error"] = "User has no password"
		render_template(w, "login", params)
		return
	}

	match, err := argon2id.ComparePasswordAndHash(password, password_hash)
	if err != nil {
		http.Error(w, "Error comparing password and hash: "+err.Error(), http.StatusInternalServerError)
		return
	}

	if !match {
		params["login_error"] = "Invalid password"
		render_template(w, "login", params)
		return
	}

	cookie_value, err := random_urlsafe_string(16)
	if err != nil {
		http.Error(w, "Error getting random string: "+err.Error(), http.StatusInternalServerError)
		return
	}

	now := time.Now()
	expiry := now.Add(time.Duration(config.HTTP.CookieExpiry) * time.Second)

	cookie := http.Cookie{
		Name:     "session",
		Value:    cookie_value,
		SameSite: http.SameSiteLaxMode,
		HttpOnly: true,
		Secure:   false, // TODO
		Expires:  expiry,
		Path:     "/",
		// TODO: Expire
	}

	http.SetCookie(w, &cookie)

	_, err = database.Exec(r.Context(), "INSERT INTO sessions (user_id, session_id) VALUES ($1, $2)", user_id, cookie_value)
	if err != nil {
		http.Error(w, "Error inserting session: "+err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/", http.StatusSeeOther)
}

// random_urlsafe_string generates a random string of the given entropic size
// using the URL-safe base64 encoding. The actual size of the string returned
// will be 4*sz.
func random_urlsafe_string(sz int) (string, error) {
	r := make([]byte, 3*sz)
	_, err := rand.Read(r)
	if err != nil {
		return "", fmt.Errorf("error generating random string: %w", err)
	}
	return base64.RawURLEncoding.EncodeToString(r), nil
}
package main

import (
	"net/http"
)

type id_title_status_t struct {
	ID     int
	Title  string
	Status string
}

func handle_repo_contrib_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	rows, err := database.Query(r.Context(), "SELECT id, title, status FROM merge_requests WHERE repo_id = $1", params["repo_id"])
	rows, err := database.Query(r.Context(), "SELECT id, COALESCE(title, 'Untitled'), status FROM merge_requests WHERE repo_id = $1", params["repo_id"])
	if err != nil {
		http.Error(w, "Error querying merge requests: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	result := []id_title_status_t{}
	for rows.Next() {
		var id int
		var title, status string
		if err := rows.Scan(&id, &title, &status); err != nil {
			http.Error(w, "Error scanning merge request: "+err.Error(), http.StatusInternalServerError)
			return
		}
		result = append(result, id_title_status_t{id, title, status})
	}
	if err := rows.Err(); err != nil {
		http.Error(w, "Error ranging over merge requests: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["merge_requests"] = result

	render_template(w, "repo_contrib_index", params)
}
package main

import (
	"net/http"
	"strconv"

	"github.com/go-git/go-git/v5"
)

func handle_repo_contrib_one(w http.ResponseWriter, r *http.Request, params map[string]any) {
	mr_id_string := params["mr_id"].(string)
	mr_id, err := strconv.ParseInt(mr_id_string, 10, strconv.IntSize)
	if err != nil {
		http.Error(w, "Merge request ID not an integer: "+err.Error(), http.StatusBadRequest)
		return
	}

	var title, status, source_ref, destination_branch string
	err = database.QueryRow(r.Context(), "SELECT title, status, source_ref, destination_branch FROM merge_requests WHERE id = $1", mr_id).Scan(&title, &status, &source_ref, &destination_branch)
	err = database.QueryRow(r.Context(), "SELECT COALESCE(title, ''), status, source_ref, COALESCE(destination_branch, '') FROM merge_requests WHERE id = $1", mr_id).Scan(&title, &status, &source_ref, &destination_branch)
	if err != nil {
		http.Error(w, "Error querying merge request: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["mr_title"], params["mr_status"], params["mr_source_ref"], params["mr_destination_branch"] = title, status, source_ref, destination_branch

	repo := params["repo"].(*git.Repository)

	source_ref_hash, err := get_ref_hash_from_type_and_name(repo, "branch", source_ref)
	if err != nil {
		http.Error(w, "Error getting source ref hash: "+err.Error(), http.StatusInternalServerError)
		return
	}
	source_commit, err := repo.CommitObject(source_ref_hash)
	if err != nil {
		http.Error(w, "Error getting source commit: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["source_commit"] = source_commit

	destination_branch_hash, err := get_ref_hash_from_type_and_name(repo, "branch", destination_branch)
	if err != nil {
		http.Error(w, "Error getting destination branch hash: "+err.Error(), http.StatusInternalServerError)
		return
	}
	destination_commit, err := repo.CommitObject(destination_branch_hash)
	if err != nil {
		http.Error(w, "Error getting destination commit: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["destination_commit"] = destination_commit

	patch, err := destination_commit.Patch(source_commit)
	if err != nil {
		http.Error(w, "Error getting patch: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["file_patches"] = make_usable_file_patches(patch)

	render_template(w, "repo_contrib_one", params)
}