How act handles untrusted .actrc files
You clone a repo, cd into it, and run act to try the workflows locally. Before a workflow executes, act reads ./.actrc from that directory and treats its lines as command-line flags. That file is part of the repository, so someone else may have written it.
That means a tool with Docker access accepts arguments from an untrusted source. The cmd package limits them with an allowlist map and three small validators. It also starts a version check in the background and uses dynamic fmt widths to align terminal output.
Trusted user config, untrusted project config
cmd/actrc.go assembles the final argument list in actrcArgs. Order matters: user config files first, then ./.actrc, then whatever was typed on the command line.
func actrcArgs(flags []*pflag.FlagSet, userFiles []string, projectFile string, cliArgs []string) []string {
args := make([]string, 0)
for _, f := range userFiles {
args = append(args, readArgsFile(f, true)...)
}
if !isUserConfigFile(projectFile, userFiles) {
if trustProjectActrc(append(append([]string{}, args...), cliArgs...)) {
args = append(args, readArgsFile(projectFile, true)...)
} else {
args = append(args, readProjectArgsFile(flags, projectFile)...)
}
}
return append(args, cliArgs...)
}
Two details are easy to skim past.
isUserConfigFile exists because you might run act from your home directory, where ./.actrc and ~/.actrc are the same file. String comparison misses that, so the code stats both and asks the filesystem:
fi, err := os.Stat(file)
if err != nil {
return false
}
for _, u := range userFiles {
if ui, err := os.Stat(u); err == nil && os.SameFile(fi, ui) {
return true
}
}
os.SameFile compares the underlying FileInfo values, so symlinks and hard links to the same file resolve correctly. Any time you deduplicate paths in Go, reach for it before string equality.
The second detail is the argument to trustProjectActrc: the user config args plus the CLI args, and nothing from the project file. The --trust-project-actrc opt-in can therefore live permanently in ~/.actrc or be passed once on the command line. The decision is made before the untrusted file’s contents are read, so the project config cannot grant itself trust.
With trust off, the project file goes through readProjectArgsFile, and the doc comment on actrcArgs states the two restrictions: no environment expansion, and only flags present in projectActrcFlags survive.
The allowlist is a map of validators
projectActrcFlags is a map[string]projectFlagCheck. A nil value means the flag is fine as-is. A non-nil value is a function that inspects the value:
type projectFlagCheck func(value string) string
It returns a reason string, empty meaning “allowed”. No error, no bool. That’s a narrow signature, and it works here only because the single thing any caller does with a rejection is print it next to the projectFlagDisallowed message. The day you need to wrap, classify, or test for a particular failure, you’ll be rewriting it. Use the shape deliberately, not by default.
Three checks, each closing a specific hole the allowlist would otherwise leave open:
// checkPlatform rejects self-hosted platforms, which run steps on the host.
func checkPlatform(value string) string {
_, image, _ := strings.Cut(value, "=")
if strings.TrimSpace(image) == "-self-hosted" {
return "self-hosted platforms run steps on the host"
}
return ""
}
// checkAssignment requires NAME=value. A bare NAME copies the value from the
// host environment.
func checkAssignment(value string) string {
if !strings.Contains(value, "=") {
return "a value without = is read from the host environment"
}
return ""
}
func checkLocalPath(value string) string {
if !filepath.IsLocal(filepath.FromSlash(value)) {
return "the path must stay inside the project directory"
}
return ""
}
checkAssignment is wired to env, var and input. Its comment says a bare name copies a value from the host environment, but the downstream code is more nuanced: bare --var NAME goes through newSecrets and can read NAME from the environment, while bare --env NAME and --input NAME are parsed as empty strings. Requiring an explicit = blocks the host lookup for variables and gives all three flags one unambiguous project-file form.
checkLocalPath guards eventpath, workflows, and the four *-file flags. filepath.IsLocal is a lexical check: it rejects absolute paths and paths that escape after cleaning, without accessing the filesystem. The filepath.FromSlash call first converts slash-separated config paths to the host platform’s separators.
That lexical guarantee has a boundary worth stating. IsLocal does not resolve symlinks, so an allowed path inside the repository can still point outside it. Code that needs a filesystem containment guarantee must resolve links and check the resulting path against the intended root.
Everything else is either nil or absent. The comment above the map states the inclusion rule plainly: flags that reach host resources, change container isolation, or point act at other services are left out, and you set those in the user config or on the command line. Writing the criterion down is the part most projects skip, and it’s why this map will still make sense after twenty more flags get added. A denylist of known-bad flags would have rotted by then.
One more thing about the signature. actrcArgs takes []*pflag.FlagSet and passes it to readProjectArgsFile. The line parser is custom, but it consults the real spf13/pflag definitions to resolve long names, shorthands and whether a flag takes a value. If you’re building something in this shape, Cobra and the standard flag package are two places to start.
A version check with a one-second exit wait
cmd/notices.go fetches release notices over HTTPS. act starts the request in Cobra’s persistent pre-run hook, overlaps it with the command, and waits for the result in the persistent post-run hook. The handoff uses a goroutine and an unbuffered channel:
var noticesLoaded = make(chan []Notice)
func loadVersionNotices(version string) {
go func() {
noticesLoaded <- getVersionNotices(version)
}()
}
The read side gives it one second:
select {
case notices := <-noticesLoaded:
// ... print them
case <-time.After(time.Second * 1):
log.Debugf("Timeout waiting for notices")
}
If the command finishes before the request, the post-run hook waits for at most one second. Because the channel is unbuffered, a timeout leaves the sender blocked until the process exits. The same pattern in a long-running process would leak a goroutine, so there you would want a buffered channel of size one or cancellation through context.Context.
displayNotices does two other sensible things. It returns immediately when input.listOptions is set, keeping the machine-readable --list-options output clean. And it builds a fresh logger with log.New() instead of reusing the global logrus instance, then explicitly selects JSON or padded text formatting for notices.
The request itself is a conditional GET. The ETag is read from disk and sent as If-None-Match, a 304 short-circuits before JSON decoding, and a newly created ETag file uses mode 0o600 (an existing file keeps its current mode). OS, architecture and version go out as query parameters. Setting ACT_DISABLE_VERSION_CHECK=1 skips all of it before the URL is parsed.
Where the ETag lands comes from cmd/dir.go, which reads XDG_CACHE_HOME:
if v := os.Getenv("XDG_CACHE_HOME"); v != "" {
CacheHomeDir = v
} else {
CacheHomeDir = filepath.Join(UserHomeDir, ".cache")
}
The code accepts any non-empty value verbatim, although the XDG specification requires an absolute path and says relative values should be ignored. It also runs in init() and calls log.Fatal when os.UserHomeDir fails. That makes the failure path awkward to test in-process; an ordinary setup function called from main would be easier to exercise.
Column alignment with %*s and negative widths
cmd/list.go prints the --list table. It walks every run in every stage, tracks the longest string per column, adds two characters of padding, and emits each row with a single Printf:
fmt.Printf("%*s%*s%*s%*s%*s%*s\n",
-stageMaxWidth, line.stage,
-jobIDMaxWidth, line.jobID,
-jobNameMaxWidth, line.jobName,
-wfNameMaxWidth, line.wfName,
-wfFileMaxWidth, line.wfFile,
-eventsMaxWidth, line.events,
)
The * in %*s pulls the width from the next argument instead of the format string, and a negative width left-justifies. Isolated, illustrative, not from act:
package main
import "fmt"
func main() {
width := 12
fmt.Printf("|%*s|\n", width, "right") // | right|
fmt.Printf("|%*s|\n", -width, "left") // |left |
}
That’s the whole thing. No strings.Repeat, no text/tabwriter, widths computed at runtime from the data. eventsMaxWidth is the one counter that never gets the += 2, which is what keeps rows from trailing off into whitespace. The same pass also tracks whether two runs shared a job ID, and prints a hint about -W at the bottom if so.
cmd/graph.go uses the same measure-then-render shape. drawGraph builds a slice of *common.Drawing for the stages and arrows, loops once to find the largest GetWidth(), then calls Draw(os.Stdout, maxWidth) on each. Collect, measure, render to a shared width. It’s a pattern worth recognizing because the alternative, deciding widths while you print, is how terminal output ends up ragged.
Paths are resolved at access time, not parse time
cmd/input.go is one big Input struct with unexported fields for every flag. Path flags are stored exactly as typed. Resolution lives in the accessor:
func (i *Input) resolve(path string) string {
basedir, err := filepath.Abs(i.workdir)
if err != nil {
log.Fatal(err)
}
if path == "" {
return path
}
if !filepath.IsAbs(path) {
path = filepath.Join(basedir, path)
}
return path
}
Envfile(), Secretfile(), Varfile(), WorkflowsPath(), EventPath() and Inputfile() are each a single line over resolve, and Workdir() is i.resolve("."). Relative paths resolve against --workdir, not the process working directory, which is the behaviour you want when act is aimed at a repository somewhere else on disk. Keeping the raw string and normalizing on read also means --workdir can show up anywhere in the flag order and nothing downstream has to care.
If you want the other half of the story, what act does with these flags once they’re parsed, there’s a walkthrough of running GitHub Actions locally.
The part I’d steal first isn’t the allowlist map itself. It’s the comment above it. Next time you add a project-level config file to a tool, write the inclusion rule in prose before you add the first key, then make every future entry argue against it.