navid/veinsforge / 27ae176db35e12f448d829962f98f424322fefbb76adef60a5d40608edc6e0b7 / internal/vn/access.go

access.go

← internal/vn · 2106 bytes · raw · download

package vn

import (
	"errors"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

type AccessEntry struct {
	PublicKey string
	Name      string
	Role      string
}

// WriteAccess writes a veins .veins/access policy. The service key always
// retains write access so the forge can refresh caches and merge pull requests.
func (r *Runner) WriteAccess(central string, anonymous bool, entries []AccessEntry) error {
	if !pathWithin(r.RepoRoot, central) {
		return errors.New("access file path is outside the repository root")
	}
	all := append([]AccessEntry{}, entries...)
	if r.KeyPublic != "" {
		all = append(all, AccessEntry{PublicKey: r.KeyPublic, Name: r.KeyName, Role: "write"})
	}
	best := make(map[string]AccessEntry)
	for _, e := range all {
		e.PublicKey = strings.TrimSpace(e.PublicKey)
		e.Name = strings.TrimSpace(e.Name)
		if !strings.HasPrefix(e.PublicKey, "ed25519:") {
			continue
		}
		if e.Role == "admin" {
			e.Role = "write"
		}
		if e.Role != "write" && e.Role != "read" {
			e.Role = "read"
		}
		if len(e.Name) > 64 || strings.ContainsAny(e.Name, " \t\r\n\x00") {
			e.Name = ""
		}
		if old, ok := best[e.PublicKey]; !ok || (e.Role == "write" && old.Role == "read") {
			best[e.PublicKey] = e
		}
	}
	list := make([]AccessEntry, 0, len(best))
	for _, e := range best {
		list = append(list, e)
	}
	sort.Slice(list, func(i, j int) bool {
		if list[i].Name == list[j].Name {
			return list[i].PublicKey < list[j].PublicKey
		}
		return list[i].Name < list[j].Name
	})
	var b strings.Builder
	b.WriteString("# veins access policy\n")
	if anonymous {
		b.WriteString("anonymous read\n")
	}
	for _, e := range list {
		b.WriteString("allow ")
		b.WriteString(e.Role)
		b.WriteByte(' ')
		b.WriteString(e.PublicKey)
		if e.Name != "" {
			b.WriteByte(' ')
			b.WriteString(e.Name)
		}
		b.WriteByte('\n')
	}
	dir := filepath.Join(central, ".veins")
	if err := os.MkdirAll(dir, 0o700); err != nil {
		return err
	}
	final := filepath.Join(dir, "access")
	tmp := final + ".tmp"
	if err := os.WriteFile(tmp, []byte(b.String()), 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, final)
}