Validate that we're in rootful podman

As this is a footgun that multiple people have run into.

Signed-off-by: Colin Walters <walters@verbum.org>
This commit is contained in:
Colin Walters 2024-01-05 16:23:52 -05:00 committed by Simon de Vlieger
parent 402c3955b9
commit 214fcda30e
2 changed files with 59 additions and 1 deletions

View file

@ -0,0 +1,38 @@
package podmanutil
import (
"bufio"
"bytes"
"errors"
"fmt"
"io/fs"
"os"
)
// envPath is written by podman
const envPath = "/run/.containerenv"
// rootlessKey is set when we are rootless
const rootlessKey = "rootless=1"
// IsRootless detects if we are running rootless in podman;
// other situations (e.g. docker) will successfuly return false.
func IsRootless() (bool, error) {
buf, err := os.ReadFile(envPath)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
return false, err
}
scanner := bufio.NewScanner(bytes.NewReader(buf))
for scanner.Scan() {
if scanner.Text() == rootlessKey {
return true, nil
}
}
if err := scanner.Err(); err != nil {
return false, fmt.Errorf("parsing %s: %w", envPath, err)
}
return false, nil
}