internal/policy/names.go
66 lines · 2200 bytes
1// Package policy holds access-control and naming rules.
2package policy
3
4import (
5 "fmt"
6 "regexp"
7)
8
9// reservedNames are forbidden as usernames and org names because they are, or
10// will be, top-level web routes (the UI serves /<owner>/<name>). Any change to
11// the httpd mux's top-level routes must be reflected here; the httpd package
12// asserts this in its tests.
13var reservedNames = map[string]bool{
14 "admin": true,
15 "api": true,
16 "archive": true,
17 "explore": true,
18 "favicon.svg": true,
19 "gitbay": true, // vanity go-import path on gitbay.org
20 "login": true,
21 "logout": true,
22 "new": true,
23 "privacy": true,
24 "raw": true,
25 "register": true,
26 "settings": true,
27 "static": true,
28}
29
30// namePat matches valid user, org, and repo names: lowercase alphanumerics,
31// dot, dash, underscore; must start with an alphanumeric. Dots are further
32// restricted by ValidateName to avoid "." / ".." and ".git" suffixes.
33var namePat = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,62}$`)
34
35// ValidateOwnerName checks a username or org name.
36func ValidateOwnerName(name string) error {
37 if err := ValidateName(name); err != nil {
38 return err
39 }
40 if reservedNames[name] {
41 return fmt.Errorf("name %q is reserved", name)
42 }
43 return nil
44}
45
46// ValidateName checks a repo name (reserved words are allowed for repos;
47// routes are namespaced under the owner).
48func ValidateName(name string) error {
49 if !namePat.MatchString(name) {
50 return fmt.Errorf("invalid name %q: lowercase letters, digits, '.', '-', '_' only; must start with a letter or digit; max 63 chars", name)
51 }
52 if name == "." || name == ".." {
53 return fmt.Errorf("invalid name %q", name)
54 }
55 if len(name) > 4 && name[len(name)-4:] == ".git" {
56 return fmt.Errorf("invalid name %q: must not end in .git", name)
57 }
58 if len(name) > 5 && name[len(name)-5:] == ".wiki" {
59 return fmt.Errorf("invalid name %q: .wiki names are reserved for wiki companion repositories", name)
60 }
61 return nil
62}
63
64// Reserved reports whether name is a reserved route word. Exported so the
65// httpd tests can assert route/reserved-list agreement.
66func Reserved(name string) bool { return reservedNames[name] }