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