package server import ( "fmt" "git.a-wan.net/alan/pipelines/internal/stage" "io" "net/url" "os" "path/filepath" "strings" "syscall" ) // notificationLinkLimit bounds a `link=` file: it holds one URL, not a document. const notificationLinkLimit = 4 << 10 // resolveNotificationLink reads the tap target a stage's `link=` pattern names // in the run's shared public/: the first non-empty line of the most recently // modified match, when it is an absolute http(s) URL ntfy accepts as a click. // Otherwise it returns no link and the reason for the notification receipt. func (r *runner) resolveNotificationLink(runID int64, pattern string) (string, string) { if pattern == "" { return "", "" } rel := r.publicNotificationFile(runID, pattern) if rel == "" { return "", fmt.Sprintf("notify link: no public file matches %s", pattern) } data, err := readNotificationLink(filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public"), rel) if err != nil { return "", fmt.Sprintf("notify link: public/%s %v", rel, err) } for _, line := range strings.Split(string(data), "\n") { if line = strings.TrimSpace(line); line == "" { continue } if !validNotificationLink(line) { return "", fmt.Sprintf("notify link: public/%s does not start with an absolute http(s) URL", rel) } return line, "" } return "", fmt.Sprintf("notify link: public/%s is empty", rel) } // readNotificationLink reads one small regular file below root without // following a symlink out of it. func readNotificationLink(root, rel string) ([]byte, error) { scoped, err := os.OpenRoot(root) if err != nil { return nil, fmt.Errorf("is unreadable") } defer scoped.Close() file, err := scoped.OpenFile(filepath.FromSlash(rel), os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0) if err != nil { return nil, fmt.Errorf("is unreadable") } defer file.Close() info, err := file.Stat() if err != nil || !info.Mode().IsRegular() || info.Size() > notificationLinkLimit { return nil, fmt.Errorf("must be a regular file of at most 4 KiB") } data, err := io.ReadAll(io.LimitReader(file, notificationLinkLimit+1)) if err != nil || len(data) > notificationLinkLimit { return nil, fmt.Errorf("must be a regular file of at most 4 KiB") } return data, nil } // validNotificationLink accepts only an absolute http(s) URL with a host that // also passes the ntfy click rules (no credentials, no fragment, bounded). func validNotificationLink(link string) bool { u, err := url.Parse(link) return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && stage.ValidNtfyClick(link) }