Skip to content
quarry Artifact [342a59145e]
Login

Artifact [342a59145e]

Artifact 342a59145e0084e8fbc1c7d585992ce48e99aa37549300c8c3c6ee3887d89d1d:


//go:build unix

package runner

import (
	"fmt"
	"io"
	"os"
	"strings"
	"syscall"
)

// readTokenFile reads a worker token from path. The file is opened
// without following a link and judged through the open descriptor, so
// nothing can be swapped in between: it must be a regular file owned by
// the user running the runner that no one else may read. The refusal
// names the path and never the value.
func readTokenFile(path string) (string, error) {
	f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
	if err != nil {
		return "", fmt.Errorf("--token-file: %v", err)
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		return "", fmt.Errorf("--token-file %s: %v", path, err)
	}
	if !fi.Mode().IsRegular() {
		return "", fmt.Errorf("--token-file %s is not a regular file", path)
	}
	if st, ok := fi.Sys().(*syscall.Stat_t); ok && int(st.Uid) != os.Geteuid() {
		return "", fmt.Errorf("--token-file %s is not owned by the user running the runner", path)
	}
	if fi.Mode().Perm()&0o077 != 0 {
		return "", fmt.Errorf("--token-file %s is readable by others (mode %04o); chmod 600 it", path, fi.Mode().Perm())
	}
	raw, err := io.ReadAll(io.LimitReader(f, 4096))
	if err != nil {
		return "", fmt.Errorf("--token-file %s: %v", path, err)
	}
	token := strings.TrimSpace(string(raw))
	if token == "" {
		return "", fmt.Errorf("--token-file %s holds no token", path)
	}
	return token, nil
}