Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@
/tools/checkpublic/ @Runware/dev-admins
/.github/workflows/ @Runware/dev-admins
/.github/CODEOWNERS @Runware/dev-admins

# What a released CLI trusts for Shared Volumes key-pair statements: the
# shipped verification keys (verificationkeys.go), the build switch and the
# check that keep the development key override out of release builds, and the
# tests that guard them. A change here decides which keys every user trusts,
# so it needs a maintainer's review even if the default owner above changes.
/internal/volumes/keypair/ @Runware/dev-admins
3 changes: 2 additions & 1 deletion internal/cmd/serverless/volumes.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ func newVerifiedVolumeKeys(serverlessBaseURL, stateDir string) (put.Keys, error)
// newVolumesCmd returns the "serverless volumes" command group for Shared
// Volumes. It is hidden, and every command in it inherits that. Keep it
// hidden until the production verification keys ship (see
// newVerifiedVolumeKeys).
// newVerifiedVolumeKeys); TestVisibleVolumesNeedProductionKeys in
// internal/volumes/keypair fails if it is shown before then.
func newVolumesCmd(logger *log.Logger) *cobra.Command {
cmd := stubGroup("volumes", "Manage Shared Volumes (beta)")
cmd.Hidden = true
Expand Down
7 changes: 7 additions & 0 deletions internal/volumes/keypair/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package keypair

// ProductionKeyCount is the number of verification keys this release ships for the
// production host. It exists for the tests of package keypair_test.
func ProductionKeyCount() int {
return len(verificationKeys[productionHost])
}
8 changes: 0 additions & 8 deletions internal/volumes/keypair/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import (
"golang.org/x/net/idna"
)

const productionHost = "api.serverless.runware.ai"

// StatementKeyEnv names the environment variable that gives the trusted statement
// verification keys for a non-production API host. Its value is a comma-separated list of
// <version>:<key> entries, where version is the decimal signing key version and key is the
Expand All @@ -28,12 +26,6 @@ const productionHost = "api.serverless.runware.ai"
// Even a development build ignores it when the serverless base URL is the production host.
const StatementKeyEnv = "RUNWARE_VOLUMES_STATEMENT_KEY"

// verificationKeys maps a platform's serverless API host to the PEM public keys of its
// statement signing key, by key version (current and next).
var verificationKeys = map[string]map[uint32]string{
productionHost: {},
}

// platformHost is the host of baseURL as the HTTP client dials it, lower-cased and without
// trailing root dots. Like net/http, it maps a host that is not ASCII through IDNA, so a
// full-width or otherwise mapped spelling of a host is that host; an ASCII host (a name, an
Expand Down
26 changes: 26 additions & 0 deletions internal/volumes/keypair/release_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package keypair_test

import (
"io"
"testing"

"github.com/charmbracelet/log"

"github.com/runware/runware-cli/internal/cmd/serverless"
"github.com/runware/runware-cli/internal/volumes/keypair"
)

// TestVisibleVolumesNeedProductionKeys: a release without production verification keys
// refuses every statement from the production API, so the volumes commands may be visible
// only in a release that ships those keys. Unhiding them first fails here, in CI and in the
// release job, rather than in front of users.
func TestVisibleVolumesNeedProductionKeys(t *testing.T) {
root := serverless.NewCmd(log.New(io.Discard))
volumes, _, err := root.Find([]string{"volumes"})
if err != nil || volumes == root {
t.Fatalf("no volumes command under serverless: %v", err)
}
if !volumes.Hidden && keypair.ProductionKeyCount() == 0 {
t.Fatal("the volumes commands are visible, but this release ships no production verification keys: add them to verificationkeys.go first")
}
}
260 changes: 260 additions & 0 deletions internal/volumes/keypair/releasebuild_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
package keypair

import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"

"gopkg.in/yaml.v3"
)

// devKeysTag is the build tag that compiles devkeys.go, and with it the StatementKeyEnv
// override, into a binary.
const devKeysTag = "volumesdevkeys"

// repoRoot is the repository root, relative to this package's directory.
var repoRoot = filepath.Join("..", "..", "..")

type goreleaserConfig struct {
Env []string `yaml:"env"`
Builds []goreleaserBuild `yaml:"builds"`
}

type goreleaserBuild struct {
ID string `yaml:"id"`
Tags []string `yaml:"tags"`
Flags []string `yaml:"flags"`
Env []string `yaml:"env"`
Overrides []goreleaserBuild `yaml:"overrides"`
}

func readRepoFile(t *testing.T, name string) []byte {
t.Helper()
raw, err := os.ReadFile(filepath.Join(repoRoot, name))
if err != nil {
t.Fatal(err)
}
return raw
}

// isTagsFlag reports whether arg is the go command's tags flag, in any form go accepts:
// -tags, --tags, -tags=x or --tags=x.
func isTagsFlag(arg string) bool {
arg = strings.Trim(arg, `"'`)
return arg == "-tags" || arg == "--tags" || strings.HasPrefix(arg, "-tags=") || strings.HasPrefix(arg, "--tags=")
}

// exportsGOFLAGS matches a Makefile line that puts GOFLAGS, or every variable, into the
// environment of the commands make runs, where make -n does not show it: an export of
// GOFLAGS anywhere before a comment (also with override or for one target), a bare export,
// or .EXPORT_ALL_VARIABLES. unexport does not match, since \b sees no word start inside it.
var exportsGOFLAGS = regexp.MustCompile(`(?m)^[^#\n]*\bexport\b[^#\n]*\bGOFLAGS\b|^\s*export\s*(#.*)?$|^\s*\.EXPORT_ALL_VARIABLES`)
Comment thread
emmmile marked this conversation as resolved.
Resolved

// goreleaserProblems lists every way a GoReleaser config could build a release with build
// tags. It refuses GOFLAGS outright, since a templated value could carry a tags flag no
// check sees; GoReleaser takes build flags in flags.
func goreleaserProblems(raw []byte) ([]string, error) {
var problems []string
if strings.Contains(string(raw), devKeysTag) {
problems = append(problems, "mentions "+devKeysTag)
}
var cfg goreleaserConfig
if err := yaml.Unmarshal(raw, &cfg); err != nil {
return nil, err
}
if len(cfg.Builds) == 0 {
problems = append(problems, "has no builds")
}
checkEnv := func(where string, env []string) {
for _, entry := range env {
if strings.HasPrefix(strings.TrimSpace(entry), "GOFLAGS") {
Comment thread
emmmile marked this conversation as resolved.
Resolved
problems = append(problems, fmt.Sprintf("%s: env %q sets GOFLAGS", where, entry))
}
}
}
var checkBuild func(where string, build goreleaserBuild)
checkBuild = func(where string, build goreleaserBuild) {
if len(build.Tags) > 0 {
problems = append(problems, fmt.Sprintf("%s: sets tags %v", where, build.Tags))
}
for _, flag := range build.Flags {
if slices.ContainsFunc(strings.Fields(flag), isTagsFlag) {
Comment thread
emmmile marked this conversation as resolved.
Resolved
problems = append(problems, fmt.Sprintf("%s: flag %q sets build tags", where, flag))
}
}
checkEnv(where, build.Env)
for i, override := range build.Overrides {
checkBuild(fmt.Sprintf("%s override %d", where, i), override)
}
}
checkEnv("top level", cfg.Env)
for i, build := range cfg.Builds {
checkBuild(fmt.Sprintf("build %d (%s)", i, build.ID), build)
}
return problems, nil
}

// workflowProblems lists the ways a release workflow could hand GoReleaser build tags.
// GoReleaser takes tags from its config and from GOFLAGS in its environment, so the
// workflow must not mention the development tag or GOFLAGS; a value taken from a variable
// could carry a tags flag no check sees. A tags flag on the workflow's own go test ships
// nothing, so the check does not parse shell.
func workflowProblems(raw string) []string {
var problems []string
if strings.Contains(raw, devKeysTag) {
problems = append(problems, "mentions "+devKeysTag)
}
if strings.Contains(raw, "GOFLAGS") {
problems = append(problems, "sets GOFLAGS")
}
return problems
}

// TestGoReleaserNeverSetsTheDevelopmentTag: the release builds set no build tags, so a
// released binary is a release build and never reads StatementKeyEnv.
func TestGoReleaserNeverSetsTheDevelopmentTag(t *testing.T) {
problems, err := goreleaserProblems(readRepoFile(t, ".goreleaser.yaml"))
Comment thread
emmmile marked this conversation as resolved.
Resolved
if err != nil {
t.Fatal(err)
}
for _, problem := range problems {
t.Errorf(".goreleaser.yaml %s", problem)
}
}

// TestGoReleaserCheckCatchesEveryRoute: the check above sees tags set in a build, in an
// override, through a flag, and through GOFLAGS.
func TestGoReleaserCheckCatchesEveryRoute(t *testing.T) {
raw := []byte(`
env:
- GOFLAGS={{ .Env.A }}
builds:
- id: one
tags: [x]
flags: ["--tags={{ .Env.B }}", -tags, "--tags", "{{ .Env.C }}"]
env: [GOFLAGS=-trimpath]
overrides:
- goos: linux
tags: [y]
flags: [-tags=z]
env: [GOFLAGS=-tags=z]
`)
problems, err := goreleaserProblems(raw)
if err != nil {
t.Fatal(err)
}
if len(problems) != 9 {
t.Fatalf("got %d problems, want 9:\n%s", len(problems), strings.Join(problems, "\n"))
}
for name, config := range map[string]string{
"a config naming the tag": "builds:\n - ldflags: [-X main.note=" + devKeysTag + "]\n",
"a config with no builds": "project_name: x\n",
} {
if problems, err := goreleaserProblems([]byte(config)); err != nil || len(problems) != 1 {
t.Errorf("%s: problems %v, error %v, want one problem", name, problems, err)
}
}
clean := []byte("builds:\n - flags: [-trimpath]\n env: [CGO_ENABLED=0]\n")
if problems, err := goreleaserProblems(clean); err != nil || len(problems) != 0 {
t.Fatalf("a config without tags: problems %v, error %v", problems, err)
}
}

// TestReleaseWorkflowNeverSetsTheDevelopmentTag: the release workflow hands GoReleaser no
// build tags.
func TestReleaseWorkflowNeverSetsTheDevelopmentTag(t *testing.T) {
for _, problem := range workflowProblems(string(readRepoFile(t, filepath.Join(".github", "workflows", "release.yml")))) {
t.Errorf("release.yml %s", problem)
}
}

// TestWorkflowCheckCatchesGOFLAGSOnly: the workflow check refuses the development tag and
// GOFLAGS, and lets git's --tags and a fetch-tags key through.
func TestWorkflowCheckCatchesGOFLAGSOnly(t *testing.T) {
for _, text := range []string{
"run: go build -tags " + devKeysTag,
"env:\n GOFLAGS: -trimpath",
`run: echo "GOFLAGS=${{ vars.FLAGS }}" >> $GITHUB_ENV`,
} {
if len(workflowProblems(text)) == 0 {
t.Errorf("%q: nothing caught", text)
}
}
for _, text := range []string{
"run: go test ./...",
"run: git fetch --force --tags",
"fetch-tags: true",
`run: echo "VERSION=$(git describe --tags --always)" >> $GITHUB_ENV`,
} {
if problems := workflowProblems(text); len(problems) != 0 {
t.Errorf("%q was refused: %v", text, problems)
}
}
}

// TestExportsGOFLAGSSeesEveryForm: the Makefile check sees GOFLAGS put into the environment
// directly, for one target, through a bare export or through .EXPORT_ALL_VARIABLES, and not
// a plain make variable, an unexport or a comment.
func TestExportsGOFLAGSSeesEveryForm(t *testing.T) {
for _, makefile := range []string{
"GOFLAGS = -trimpath\nexport CGO_ENABLED",
"unexport GOFLAGS",
"# GOFLAGS is not exported, so make -n shows every flag; do not export GOFLAGS here",
} {
if exportsGOFLAGS.MatchString(makefile) {
t.Errorf("%q was taken for an export of GOFLAGS", makefile)
}
}
for _, makefile := range []string{
"export GOFLAGS = -tags foo",
"GOFLAGS = -trimpath\nexport GOFLAGS",
"export CGO_ENABLED GOFLAGS",
"override export GOFLAGS = -tags foo",
"install: export GOFLAGS = -tags=" + devKeysTag,
"install linux-amd64: export GOFLAGS += -tags=foo",
"GOFLAGS = -trimpath\nexport",
"export # every variable",
".EXPORT_ALL_VARIABLES:",
} {
if !exportsGOFLAGS.MatchString(makefile) {
t.Errorf("%q: the export was not seen", makefile)
}
}
}

// TestMakeReleaseTargetsNeverSetTheDevelopmentTag: the Makefile targets that build a binary
// to install or hand out (install and the cross-platform builds) never pass the development
// tag, while make build, which the check is compared against, does. make -n prints the
// commands with every make variable expanded, so a tag set through DEV_TAGS or any other
// variable shows by name; the check does not parse shell.
func TestMakeReleaseTargetsNeverSetTheDevelopmentTag(t *testing.T) {
if _, err := exec.LookPath("make"); err != nil {
t.Skip("make is not installed")
}
dryRun := func(targets ...string) string {
t.Helper()
out, err := exec.CommandContext(t.Context(), "make", append([]string{"-n", "--no-print-directory", "-C", repoRoot}, targets...)...).CombinedOutput() //nolint:gosec // make -n with fixed test targets, no shell
if err != nil {
t.Fatalf("make -n %v: %v\n%s", targets, err, out)
}
return string(out)
}
if makefile := readRepoFile(t, "Makefile"); exportsGOFLAGS.Match(makefile) {
t.Error("the Makefile exports GOFLAGS, which make -n does not show")
}
if out := dryRun("build"); !strings.Contains(out, devKeysTag) {
t.Fatalf("make -n build does not show the %s tag, so this check cannot see it:\n%s", devKeysTag, out)
}
out := dryRun("install", "build-all")
if !strings.Contains(out, "go install") || !strings.Contains(out, "GOOS=linux") {
t.Fatalf("make -n install build-all did not print the expected builds:\n%s", out)
}
if strings.Contains(out, devKeysTag) {
t.Errorf("make install or build-all sets the %s tag:\n%s", devKeysTag, out)
}
}
16 changes: 16 additions & 0 deletions internal/volumes/keypair/verificationkeys.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package keypair

// This file holds what a released CLI trusts for key-pair statements: the
// production API host and the verification keys it ships for each platform.
// .github/CODEOWNERS requires a maintainer's review of every change to it.

const productionHost = "api.serverless.runware.ai"

// verificationKeys maps a platform's serverless API host to the PEM public keys of its
// statement signing key, by key version (current and next). The production set stays empty
// until its key is published, and TestVisibleVolumesNeedProductionKeys keeps the volumes
// commands hidden until then. Before adding a production key, also check the upload host
// rule at platformDomain (uploadhost.go).
var verificationKeys = map[string]map[uint32]string{
productionHost: {},
}
Loading