diff --git a/README.md b/README.md index 5951bb6..84763af 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,7 @@ valar service logs [--follow] [--tail] [--skip n] [--all | --deployment n] [--ti #### Print a service's URLs -Linked custom domains come first, then the service's own `-` domains. +Linked custom domains come first, then the service's own `-` domains. The command reads the service's inspect route, so a token bound to the service works; against an older platform it reads the project's service listing instead. ```bash valar service url [--service service] @@ -422,7 +422,7 @@ A token created with `valar token create` acts as you. It is a child of the toke #### Create a token ```bash -valar token create [--project project] [--service service] [--scopes read,deploy] [--ttl 90d] name +valar token create [--project project] [--service service] [--scopes read,deploy] [--ttl 90d] [--agent] name ``` `--project` binds the token to one project and `--service` to one service of it. `--scopes` limits it to some of `read`, `deploy`, `invoke`, `kv` and `all` (the default). `--ttl` takes days (`30d`) or a duration (`12h`); the default is 90 days and the maximum 365. A token for CI that pushes and deploys one project: @@ -433,6 +433,37 @@ valar token create ci --project acme --scopes read,deploy The token goes to stdout and the rest to stderr, so `TOKEN=$(valar token create ci)` captures only the token; with `--json` it is the `value` field. Valar shows it once. +#### Create a token for an AI agent + +```bash +valar token create claude --agent --project acme [--service web] [--ttl 30d] +``` + +An agent token works only at the platform's MCP endpoint (`https://api.valar.dev/mcp`, or the API's origin followed by `/mcp` on another installation), not with this CLI or the API. It is bound to one project, can only read, and lasts 7 days by default and at most 30. The platform refuses it until the installation turns on its MCP endpoint. After creating it, the command prints how to configure MCP clients; with `--json`, `mcpUrl` holds the endpoint. + +Keep the token in a password manager or the client's secret store and give it to the client as an environment variable, here `VALAR_AGENT_TOKEN`, rather than writing it into a configuration file. For Claude Code: + +```bash +claude mcp add --transport http valar https://api.valar.dev/mcp \ + --header 'Authorization: Bearer ${VALAR_AGENT_TOKEN}' +``` + +Other MCP clients that speak Streamable HTTP and send a static header take the same URL and header, as in an `mcpServers` entry: + +```json +{ + "mcpServers": { + "valar": { + "type": "http", + "url": "https://api.valar.dev/mcp", + "headers": { "Authorization": "Bearer ${VALAR_AGENT_TOKEN}" } + } + } +} +``` + +Do not run the agent where it can read `~/.valar`, which holds your own token. + #### List tokens ```bash @@ -449,6 +480,52 @@ valar token revoke [--project project] id Revokes the token with the ID that `valar token list` shows, and the tokens it created. With `--project`, it revokes a token from the project's list. +### Deploys from CI + +Where the installation trusts a CI provider's identity tokens, a CI job can deploy without a stored token. A trust policy lets the job exchange its identity token for a token that acts as the policy's creator, bound to one service with `read` and `deploy`, for an hour. These commands need permission to manage the project, a token created in the console or with authctl, and a newer Valar platform. + +#### Add a trust policy + +```bash +valar trust add [--project project] --service web --github-repo acme/web --branch main --workflow deploy.yml [--event push] +valar trust add [--project project] --service web --github-repo acme/web --environment production --workflow deploy.yml +valar trust add [--project project] --service 'webpr*' --github-repo acme/web --pull-requests +valar trust add [--project project] --service web --subject sub [--claim name=value]... [--issuer url] [--force] +``` + +`--github-repo` builds the policy for GitHub Actions. It reads the repository's ID, its owner's ID and its OIDC subject format from GitHub, writes the subject as GitHub will issue it (with immutable IDs where the repository uses them), and pins `repository_id` and `repository_owner_id`. A branch or environment policy also pins `event_name` (`--event`, `push` by default) and `workflow_ref` (`--workflow`), so other workflows and triggers do not match. Where the repository's subject template leaves out the branch or environment, the policy pins it as a `ref` or `environment` claim. `--workflow deploy.yml@refs/heads/release` names the ref an environment's workflow runs from; it is the default branch otherwise. Protect an environment that a policy names with deployment branch rules, because GitHub issues its subject to every job that names it. + +A `--pull-requests` policy names a preview prefix followed by `*`: pull request 42 may deploy only `webpr42`. Public repositories give pull requests from forks no identity tokens; a private repository can, through its Actions settings, so there a fork's pull request may deploy its own preview. + +Unless `--force` is given, `trust add` refuses policies for `pull_request_target`, `workflow_run` and `issue_comment` jobs, which run with the repository's credentials on input that others control, and a hand-written `pull_request` subject for a service rather than a preview prefix. It warns when a hand-written GitHub policy pins no repository ID. + +For a private repository, set `GH_TOKEN` to a GitHub token that can read it, such as `GH_TOKEN=$(gh auth token)`. `--subject` and `--claim` set the policy by hand, for other CI providers or subject formats `--github-repo` does not know. `--issuer` defaults to `https://token.actions.githubusercontent.com`. `create` is an alias of `add`. + +#### List and remove trust policies + +```bash +valar trust list [--project project] +valar trust remove [--project project] id +``` + +Removing a policy revokes the tokens it issued. `delete` is an alias of `remove`. + +#### Exchange an identity token + +```bash +valar auth exchange [--service service] [--project project] [--id-token-file path] [--audience audience] [--export] +``` + +Prints a token for the service, which comes from `--service` or `.valar.yml`. In a GitHub Actions job with `permissions: id-token: write`, the command requests the identity token itself, for `--audience` (the endpoint's origin, such as `https://api.valar.dev`, by default); elsewhere it reads it from `--id-token-file` or stdin. In GitHub Actions it masks the token in the log, and `--export` sets `VALAR_TOKEN` for the job's later steps instead of printing it: + +```bash +VALAR_TOKEN=$(valar auth exchange --service web) +export VALAR_TOKEN +valar build push --wait +``` + +When no policy admits the identity token, the error shows the claims a policy matches, such as `sub` and `workflow_ref`, to compare with `valar trust list`. The [Valar GitHub Action](https://github.com/valar/action) does all of this when it gets no `token` input. + ### Audit log ```bash diff --git a/api/client.go b/api/client.go index 19f59ee..a25d28d 100644 --- a/api/client.go +++ b/api/client.go @@ -93,12 +93,20 @@ func parseErrorResponse(body []byte) error { return serverErr } +// authorize adds the bearer token; a client without one sends no header, as +// the token exchange requires. +func (client *Client) authorize(req *http.Request) { + if client.Token != "" { + req.Header.Add("Authorization", "Bearer "+client.Token) + } +} + func (client *Client) request(method, path string, obj interface{}, post io.Reader) error { req, err := http.NewRequest(method, client.Endpoint+path, post) if err != nil { return fmt.Errorf("client request: %w", err) } - req.Header.Add("Authorization", "Bearer "+client.Token) + client.authorize(req) resp, err := client.http.Do(req) if err != nil { return fmt.Errorf("submitting request: %w", err) diff --git a/api/logstream.go b/api/logstream.go index 4b8dd78..72e7f4c 100644 --- a/api/logstream.go +++ b/api/logstream.go @@ -122,7 +122,7 @@ func (client *Client) openStream(path string) (io.ReadCloser, bool, error) { if err != nil { return nil, false, fmt.Errorf("client request: %w", err) } - req.Header.Add("Authorization", "Bearer "+client.Token) + client.authorize(req) resp, err := client.stream.Do(req) if err != nil { diff --git a/api/token.go b/api/token.go index 1fd122e..79306c7 100644 --- a/api/token.go +++ b/api/token.go @@ -91,7 +91,9 @@ type MintedToken struct { // TokenRequest mints a token. TTL is a Go duration; empty means the server's default. type TokenRequest struct { - Name string `json:"name"` + Name string `json:"name"` + // Kind is user, the server's default when empty, or agent. + Kind string `json:"kind,omitempty"` Project string `json:"project,omitempty"` Service string `json:"service,omitempty"` Scopes []string `json:"scopes,omitempty"` diff --git a/api/trust.go b/api/trust.go new file mode 100644 index 0000000..0eececd --- /dev/null +++ b/api/trust.go @@ -0,0 +1,134 @@ +package api + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "net/http" + "time" +) + +// GitHubIssuer issues the identity tokens of GitHub Actions jobs. +const GitHubIssuer = "https://token.actions.githubusercontent.com" + +// ErrNoTrustAPI is returned when the server predates deploys from CI. +var ErrNoTrustAPI = errors.New("the server has no trust policies or token exchange; it needs a newer Valar platform") + +// TrustPolicy lets CI jobs whose identity tokens come from Issuer, name +// Subject and carry Claims exchange them for tokens for Service that act as +// CreatedBy. Service is a name, or a preview prefix followed by *. +type TrustPolicy struct { + ID string `json:"id"` + Service string `json:"service"` + Issuer string `json:"issuer"` + Subject string `json:"subject"` + Claims map[string]string `json:"claims"` + CreatedBy string `json:"createdBy"` + CreatedAt time.Time `json:"createdAt"` + // Warning is set when the policy was just created. + Warning string `json:"warning,omitempty"` +} + +// TrustPolicyRequest creates a trust policy. An empty Issuer is the +// installation's first. +type TrustPolicyRequest struct { + Service string `json:"service"` + Subject string `json:"subject"` + Issuer string `json:"issuer,omitempty"` + Claims map[string]string `json:"claims,omitempty"` +} + +// ExchangedToken is a token for one service, minted for a CI job's identity token. +type ExchangedToken struct { + Token string `json:"token"` + ExpiresAt time.Time `json:"expiresAt"` +} + +func trustError(err error) error { + if unknownRoute(err) { + return ErrNoTrustAPI + } + return err +} + +func trustPoliciesPath(project string) string { + return fmt.Sprintf("/projects/%s/trust-policies", project) +} + +// CreateTrustPolicy adds a trust policy to project. The calling token must +// have been created in the console or with authctl. +func (client *Client) CreateTrustPolicy(project string, req TrustPolicyRequest) (*TrustPolicy, error) { + payload, err := json.Marshal(req) + if err != nil { + return nil, err + } + var policy TrustPolicy + if err := client.request(http.MethodPost, trustPoliciesPath(project), &policy, bytes.NewReader(payload)); err != nil { + return nil, trustError(err) + } + return &policy, nil +} + +// ListTrustPolicies returns the project's trust policies, oldest first. +func (client *Client) ListTrustPolicies(project string) ([]TrustPolicy, error) { + var policies []TrustPolicy + if err := client.request(http.MethodGet, trustPoliciesPath(project), &policies, nil); err != nil { + return nil, trustError(err) + } + return policies, nil +} + +// DeleteTrustPolicy deletes a trust policy and returns how many of its tokens +// it revoked. +func (client *Client) DeleteTrustPolicy(project, id string) (int, error) { + var resp struct { + Revoked int `json:"revoked"` + } + if err := client.request(http.MethodDelete, trustPoliciesPath(project)+"/"+id, &resp, nil); err != nil { + return 0, trustError(err) + } + return resp.Revoked, nil +} + +// ExchangeToken trades a CI job's identity token for a token for one service. +// The request carries no bearer token, so the client needs none. +func (client *Client) ExchangeToken(project, service, idToken string) (*ExchangedToken, error) { + payload, err := json.Marshal(struct { + IDToken string `json:"idToken"` + }{idToken}) + if err != nil { + return nil, err + } + anonymous := *client + anonymous.Token = "" + var token ExchangedToken + path := fmt.Sprintf("/projects/%s/services/%s/token-exchange", project, service) + if err := anonymous.request(http.MethodPost, path, &token, bytes.NewReader(payload)); err != nil { + return nil, trustError(err) + } + return &token, nil +} + +// InspectedService is a service's listing entry with its URLs: those of the +// linked custom domains, then those of the canonical domains. +type InspectedService struct { + Service + URLs []string `json:"urls"` +} + +// ErrNoInspectAPI is returned when the server predates the inspect route. +var ErrNoInspectAPI = errors.New("the server has no service inspect route") + +// InspectService returns one service with its URLs. Unlike the listing, a +// token bound to the service may read it. +func (client *Client) InspectService(project, service string) (*InspectedService, error) { + var svc InspectedService + if err := client.request(http.MethodGet, fmt.Sprintf("/projects/%s/services/%s/inspect", project, service), &svc, nil); err != nil { + if unknownRoute(err) { + return nil, ErrNoInspectAPI + } + return nil, err + } + return &svc, nil +} diff --git a/api/trust_test.go b/api/trust_test.go new file mode 100644 index 0000000..091199b --- /dev/null +++ b/api/trust_test.go @@ -0,0 +1,67 @@ +package api + +import ( + "errors" + "net/http" + "testing" +) + +func TestAuthorization(t *testing.T) { + for _, tc := range []struct { + Name string + Token string + Call func(*Client) error + Want string + }{ + {"Token", "valar_ut_x", func(c *Client) error { _, err := c.UserInfo(); return err }, "Bearer valar_ut_x"}, + {"NoToken", "", func(c *Client) error { _, err := c.UserInfo(); return err }, ""}, + {"Exchange", "valar_ut_x", func(c *Client) error { _, err := c.ExchangeToken("acme", "web", "jwt"); return err }, ""}, + } { + t.Run(tc.Name, func(t *testing.T) { + var got []string + client := newHeaderTestClient(t, func(w http.ResponseWriter, r *http.Request) { + got = r.Header.Values("Authorization") + w.Write([]byte(`{}`)) + }) + client.Token = tc.Token + if err := tc.Call(client); err != nil { + t.Fatal(err) + } + if tc.Want == "" && len(got) != 0 || tc.Want != "" && (len(got) != 1 || got[0] != tc.Want) { + t.Errorf("Authorization %q, want %q", got, tc.Want) + } + }) + } +} + +func TestTrustRoutes_OlderServer(t *testing.T) { + client := newHeaderTestClient(t, http.NotFound) + for name, call := range map[string]func() error{ + "create": func() error { _, err := client.CreateTrustPolicy("acme", TrustPolicyRequest{}); return err }, + "list": func() error { _, err := client.ListTrustPolicies("acme"); return err }, + "delete": func() error { _, err := client.DeleteTrustPolicy("acme", "x"); return err }, + "exchange": func() error { _, err := client.ExchangeToken("acme", "web", "jwt"); return err }, + } { + if err := call(); !errors.Is(err, ErrNoTrustAPI) { + t.Errorf("%s: error = %v, want ErrNoTrustAPI", name, err) + } + } + if _, err := client.InspectService("acme", "web"); !errors.Is(err, ErrNoInspectAPI) { + t.Errorf("inspect: error = %v, want ErrNoInspectAPI", err) + } +} + +func TestInspectService(t *testing.T) { + var path string + client := newHeaderTestClient(t, func(w http.ResponseWriter, r *http.Request) { + path = r.URL.Path + w.Write([]byte(`{"name":"web","kind":"function","domains":["acme-web.valar.app"],"urls":["https://acme-web.valar.app"]}`)) + }) + svc, err := client.InspectService("acme", "web") + if err != nil { + t.Fatal(err) + } + if path != "/projects/acme/services/web/inspect" || svc.Name != "web" || len(svc.URLs) != 1 || svc.URLs[0] != "https://acme-web.valar.app" { + t.Errorf("GET %s gave %+v", path, svc) + } +} diff --git a/api/utils.go b/api/utils.go index 9fb9054..1248319 100644 --- a/api/utils.go +++ b/api/utils.go @@ -15,6 +15,11 @@ func VerifyNames(project, service string) error { if err := VerifyProjectName(project); err != nil { return err } + return VerifyServiceName(service) +} + +// VerifyServiceName checks that service is a valid service name. +func VerifyServiceName(service string) error { if !serviceExp.Match([]byte(service)) { return fmt.Errorf("invalid service name: may only contain alphanumerics") } diff --git a/cmd/audit.go b/cmd/audit.go index 6b8f0fe..544a424 100644 --- a/cmd/audit.go +++ b/cmd/audit.go @@ -95,7 +95,7 @@ func printAudit(w io.Writer, events []api.AuditEvent) error { kind = fmt.Sprintf("count (%d)", e.Count) } token := e.TokenID - if tokenIDPattern.MatchString(token) { + if idPattern.MatchString(token) { token = token[:8] } status := "-" diff --git a/cmd/exchange.go b/cmd/exchange.go new file mode 100644 index 0000000..b5cf110 --- /dev/null +++ b/cmd/exchange.go @@ -0,0 +1,261 @@ +package cmd + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "regexp" + "strings" + "time" + + "github.com/spf13/cobra" + "github.com/valar/cli/api" + "github.com/valar/cli/config" + "golang.org/x/term" +) + +// maxIDToken is the largest identity token the platform accepts. +const maxIDToken = 16 << 10 + +// policyTokenPattern is the only value an exchange returns; anything else is +// never printed or exported. +var policyTokenPattern = regexp.MustCompile(`^valar_ut_[0-9a-f]{64}$`) + +// GitHub Actions sets these in jobs with permissions: id-token: write. +const ( + envIDTokenRequestURL = "ACTIONS_ID_TOKEN_REQUEST_URL" + envIDTokenRequestToken = "ACTIONS_ID_TOKEN_REQUEST_TOKEN" +) + +var ( + exchangeService string + exchangeProject string + exchangeIDTokenFile string + exchangeAudience string + exchangeExport bool +) + +var authExchangeCmd = &cobra.Command{ + Use: "exchange [--service s] [--project p] [--id-token-file path] [--audience aud] [--export]", + Short: "Exchange a CI job's identity token for a token for one service.", + Long: `Exchange a CI job's identity token for a token for one service. + +A trust policy of the project ('valar trust add') must admit the identity +token. The token Valar returns acts as the policy's creator, bound to the +service with read and deploy, and lasts an hour. The service and project come +from the flags, VALAR_PROJECT or .valar.yml, as for other commands. + +The identity token comes from --id-token-file (- for stdin), or, in a GitHub +Actions job with permissions: id-token: write, from GitHub for --audience, +which defaults to the endpoint's origin (https://api.valar.dev). Otherwise it +is read from stdin. + +The token goes to stdout and everything else to stderr: + + VALAR_TOKEN=$(valar auth exchange --service web) + export VALAR_TOKEN + +In GitHub Actions the token is masked in the log, and --export sets +VALAR_TOKEN for the job's later steps instead of printing it.`, + Args: cobra.NoArgs, + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + project, service := exchangeProject, exchangeService + if project == "" || service == "" { + cfg, err := config.NewServiceConfigWithFallback(functionConfiguration, &service, globalConfiguration) + if err != nil { + return err + } + if project == "" { + project = cfg.Project() + } + service = cfg.Service() + } + if err := api.VerifyNames(project, service); err != nil { + return withKind(kindInvalid, err) + } + endpoint := globalConfiguration.EndpointOrDefault() + idToken, err := readIDToken(exchangeIDTokenFile, exchangeAudience, endpoint, os.Stdin) + if err != nil { + return err + } + client, err := api.NewClient(endpoint, "") + if err != nil { + return err + } + return exchangeToken(client, project, service, idToken, exchangeExport, stdout, os.Stderr) + }), +} + +// readIDToken returns the identity token from the file, GitHub Actions or +// stdin, in that order. +func readIDToken(file, audience, endpoint string, stdin *os.File) (string, error) { + switch { + case file == "-": + return readIDTokenFrom(stdin, "stdin") + case file != "": + f, err := os.Open(file) + if err != nil { + return "", withKind(kindInvalid, err) + } + defer f.Close() + return readIDTokenFrom(f, file) + } + if requestURL := os.Getenv(envIDTokenRequestURL); requestURL != "" { + if audience == "" { + u, err := url.Parse(endpoint) + if err != nil || u.Host == "" { + return "", newError(kindInvalid, "endpoint %q has no origin to use as the audience; pass --audience", endpoint) + } + audience = u.Scheme + "://" + u.Host + } + return githubIDToken(requestURL, os.Getenv(envIDTokenRequestToken), audience) + } + if term.IsTerminal(int(stdin.Fd())) { + return "", newError(kindInvalid, "no identity token: pass --id-token-file, pipe it to stdin, or run in a GitHub Actions job with permissions: id-token: write") + } + return readIDTokenFrom(stdin, "stdin") +} + +func readIDTokenFrom(r io.Reader, name string) (string, error) { + data, err := io.ReadAll(io.LimitReader(r, maxIDToken+1)) + if err != nil { + return "", fmt.Errorf("reading the identity token from %s: %w", name, err) + } + token := strings.TrimSpace(string(data)) + switch { + case token == "": + return "", newError(kindInvalid, "no identity token in %s", name) + case len(data) > maxIDToken: + return "", newError(kindInvalid, "the identity token in %s is larger than 16 KiB", name) + } + return token, nil +} + +// githubIDToken requests a GitHub Actions identity token for audience. +func githubIDToken(requestURL, requestToken, audience string) (string, error) { + sep := "?" + if strings.Contains(requestURL, "?") { + sep = "&" + } + req, err := http.NewRequest(http.MethodGet, requestURL+sep+"audience="+url.QueryEscape(audience), nil) + if err != nil { + return "", fmt.Errorf("requesting an identity token from GitHub: %w", err) + } + req.Header.Set("Authorization", "bearer "+requestToken) + req.Header.Set("Accept", "application/json") + resp, err := (&http.Client{Timeout: time.Minute}).Do(req) + if err != nil { + return "", withKind(kindUnavailable, fmt.Errorf("requesting an identity token from GitHub: %w", err)) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return "", withKind(kindUnavailable, fmt.Errorf("requesting an identity token from GitHub: %w", err)) + } + if resp.StatusCode != http.StatusOK { + return "", withKind(kindUnavailable, fmt.Errorf("requesting an identity token from GitHub: %s", resp.Status)) + } + var doc struct { + Value string `json:"value"` + } + if err := json.Unmarshal(body, &doc); err != nil || doc.Value == "" { + return "", withKind(kindUnavailable, errors.New("GitHub returned no identity token")) + } + return doc.Value, nil +} + +// exchangeToken trades idToken for a token and writes it to w, or with export +// to the file GITHUB_ENV names. +func exchangeToken(client *api.Client, project, service, idToken string, export bool, w, progress io.Writer) error { + githubEnv := os.Getenv("GITHUB_ENV") + if export && githubEnv == "" { + return newError(kindInvalid, "--export works in GitHub Actions, which sets GITHUB_ENV; elsewhere capture the printed token, as in VALAR_TOKEN=$(valar auth exchange)") + } + token, err := client.ExchangeToken(project, service, idToken) + if apiErr := (api.Error{}); errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusForbidden { + if hint := identityHint(idToken); hint != "" { + err = fmt.Errorf("%w\n%s", err, hint) + } + } + if err != nil { + return err + } + if !policyTokenPattern.MatchString(token.Token) { + return newError(kindUnavailable, "the server's exchange answer holds no valid token") + } + if os.Getenv("GITHUB_ACTIONS") == "true" { + fmt.Fprintf(progress, "::add-mask::%s\n", token.Token) + } + expiry := token.ExpiresAt.UTC().Format("2006-01-02 15:04 MST") + if export { + if err := appendGitHubEnv(githubEnv, "VALAR_TOKEN", token.Token); err != nil { + return err + } + return emit(w, struct { + ExpiresAt time.Time `json:"expiresAt"` + }{token.ExpiresAt}, func(io.Writer) error { + _, err := fmt.Fprintf(progress, "Set VALAR_TOKEN for the job's later steps: a token for %s/%s until %s.\n", project, service, expiry) + return err + }) + } + return emit(w, token, func(w io.Writer) error { + fmt.Fprintf(progress, "Exchanged the identity token for a token for %s/%s until %s.\n", project, service, expiry) + _, err := fmt.Fprintln(w, token.Token) + return err + }) +} + +func appendGitHubEnv(path, name, value string) error { + f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + return fmt.Errorf("export %s: %w", name, err) + } + if _, err := fmt.Fprintf(f, "%s=%s\n", name, value); err != nil { + f.Close() + return fmt.Errorf("export %s: %w", name, err) + } + return f.Close() +} + +// identityHint shows the claims a trust policy matches, read without +// verification from the identity token, so a refusal can be compared with +// 'valar trust list'. +func identityHint(idToken string) string { + parts := strings.Split(idToken, ".") + if len(parts) != 3 { + return "" + } + payload, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return "" + } + var claims map[string]any + if json.Unmarshal(payload, &claims) != nil { + return "" + } + var lines []string + for _, k := range []string{"iss", "sub", "ref", "repository_id", "repository_owner_id", "event_name", "workflow_ref"} { + if v, ok := claims[k].(string); ok { + lines = append(lines, fmt.Sprintf(" %s: %s", k, v)) + } + } + if len(lines) == 0 { + return "" + } + return "The identity token carries:\n" + strings.Join(lines, "\n") +} + +func initExchangeCmd() { + f := authExchangeCmd.Flags() + f.StringVarP(&exchangeService, "service", "s", "", "Service to get a token for, instead of the one in .valar.yml") + f.StringVarP(&exchangeProject, "project", "p", "", "Project of the service, instead of the active one") + f.StringVar(&exchangeIDTokenFile, "id-token-file", "", "Read the identity token from this file, or - for stdin") + f.StringVar(&exchangeAudience, "audience", "", "Audience of the identity token requested from GitHub Actions (default the endpoint's origin)") + f.BoolVar(&exchangeExport, "export", false, "In GitHub Actions, set VALAR_TOKEN for the job's later steps instead of printing it") + authCmd.AddCommand(authExchangeCmd) +} diff --git a/cmd/exchange_test.go b/cmd/exchange_test.go new file mode 100644 index 0000000..5bc65fe --- /dev/null +++ b/cmd/exchange_test.go @@ -0,0 +1,355 @@ +package cmd + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/valar/cli/api" +) + +const ( + exchangePath = "/projects/acme/services/web/token-exchange" + policyToken = "valar_ut_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + exchanged = `{"token":"` + policyToken + `","expiresAt":"2026-11-21T13:00:00Z"}` +) + +// fakeJWT builds an unsigned token with claims, enough for identityHint. +func fakeJWT(t *testing.T, claims map[string]any) string { + t.Helper() + payload, err := json.Marshal(claims) + if err != nil { + t.Fatal(err) + } + enc := base64.RawURLEncoding.EncodeToString + return enc([]byte(`{"alg":"RS256"}`)) + "." + enc(payload) + ".c2ln" +} + +// fileWith returns an open file holding content, standing in for stdin. +func fileWith(t *testing.T, content string) *os.File { + t.Helper() + path := filepath.Join(t.TempDir(), "stdin") + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { f.Close() }) + return f +} + +func TestReadIDToken(t *testing.T) { + file := filepath.Join(t.TempDir(), "id-token") + if err := os.WriteFile(file, []byte("from-file\n"), 0o600); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + Name string + File string + Stdin string + Want string + WantKind errorKind + }{ + {Name: "File", File: file, Want: "from-file"}, + {Name: "Dash", File: "-", Stdin: "from-stdin\n", Want: "from-stdin"}, + {Name: "Stdin", Stdin: "from-stdin", Want: "from-stdin"}, + {Name: "MissingFile", File: file + ".missing", WantKind: kindInvalid}, + {Name: "EmptyStdin", Stdin: "\n", WantKind: kindInvalid}, + {Name: "TooLarge", Stdin: strings.Repeat("a", maxIDToken+1), WantKind: kindInvalid}, + } { + t.Run(tc.Name, func(t *testing.T) { + t.Setenv(envIDTokenRequestURL, "") + got, err := readIDToken(tc.File, "", valarAPI, fileWith(t, tc.Stdin)) + if tc.WantKind != 0 { + if err == nil || classify(err, kindFailed) != tc.WantKind { + t.Errorf("error %v of kind %v, want kind %v", err, classify(err, kindFailed), tc.WantKind) + } + return + } + if err != nil || got != tc.Want { + t.Errorf("readIDToken = %q, %v; want %q", got, err, tc.Want) + } + }) + } +} + +func TestReadIDToken_GitHubActions(t *testing.T) { + for _, tc := range []struct { + Name string + Audience string + Endpoint string + Status int + WantAudience string + WantKind errorKind + }{ + {Name: "EndpointOrigin", Endpoint: valarAPI, Status: http.StatusOK, WantAudience: "https://api.valar.dev"}, + {Name: "OriginWithPort", Endpoint: "https://valar.example.com:8443/api/v2", Status: http.StatusOK, WantAudience: "https://valar.example.com:8443"}, + {Name: "Audience", Audience: "https://valar.example.com", Endpoint: valarAPI, Status: http.StatusOK, WantAudience: "https://valar.example.com"}, + {Name: "Refused", Endpoint: valarAPI, Status: http.StatusForbidden, WantAudience: "https://api.valar.dev", WantKind: kindUnavailable}, + } { + t.Run(tc.Name, func(t *testing.T) { + var gotAudience, gotAuth, gotVersion string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAudience, gotAuth, gotVersion = r.URL.Query().Get("audience"), r.Header.Get("Authorization"), r.URL.Query().Get("api-version") + w.WriteHeader(tc.Status) + w.Write([]byte(`{"value":"from-github"}`)) + })) + t.Cleanup(srv.Close) + t.Setenv(envIDTokenRequestURL, srv.URL+"/idtoken?api-version=2.0") + t.Setenv(envIDTokenRequestToken, "request-secret") + got, err := readIDToken("", tc.Audience, tc.Endpoint, fileWith(t, "not read")) + if gotAudience != tc.WantAudience || gotAuth != "bearer request-secret" || gotVersion != "2.0" { + t.Errorf("GitHub got audience %q, Authorization %q, api-version %q", gotAudience, gotAuth, gotVersion) + } + if tc.WantKind != 0 { + if err == nil || classify(err, kindFailed) != tc.WantKind { + t.Errorf("error %v of kind %v, want kind %v", err, classify(err, kindFailed), tc.WantKind) + } + return + } + if err != nil || got != "from-github" { + t.Errorf("readIDToken = %q, %v; want from-github", got, err) + } + }) + } +} + +// newExchangeAPI serves the token exchange, refusing requests that carry a +// bearer token, and records the request bodies. +func newExchangeAPI(t *testing.T, status int, body string) (*api.Client, *[]string) { + t.Helper() + var bodies []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" { + t.Errorf("%s %s carries Authorization", r.Method, r.URL.Path) + } + if r.URL.Path == "/" { + w.Write([]byte(`{"version":"v2"}`)) + return + } + if r.Method+" "+r.URL.Path != "POST "+exchangePath { + http.NotFound(w, r) + return + } + b, _ := io.ReadAll(r.Body) + bodies = append(bodies, string(b)) + w.WriteHeader(status) + w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + client, err := api.NewClient(srv.URL, "") + if err != nil { + t.Fatalf("new client: %v", err) + } + return client, &bodies +} + +func TestExchangeToken(t *testing.T) { + for _, tc := range []struct { + Name string + JSON bool + Actions bool + WantOut string + WantProgress string + }{ + {Name: "Human", WantOut: policyToken + "\n", WantProgress: "Exchanged the identity token for a token for acme/web until 2026-11-21 13:00 UTC.\n"}, + { + Name: "GitHubActions", Actions: true, WantOut: policyToken + "\n", + WantProgress: "::add-mask::" + policyToken + "\nExchanged the identity token for a token for acme/web until 2026-11-21 13:00 UTC.\n", + }, + {Name: "JSON", JSON: true}, + } { + t.Run(tc.Name, func(t *testing.T) { + setJSON(t, tc.JSON) + t.Setenv("GITHUB_ENV", "") + t.Setenv("GITHUB_ACTIONS", "") + if tc.Actions { + t.Setenv("GITHUB_ACTIONS", "true") + } + client, bodies := newExchangeAPI(t, http.StatusOK, exchanged) + var out, progress bytes.Buffer + if err := exchangeToken(client, "acme", "web", "id.token.jwt", false, &out, &progress); err != nil { + t.Fatalf("exchangeToken: %v", err) + } + if len(*bodies) != 1 || (*bodies)[0] != `{"idToken":"id.token.jwt"}` { + t.Errorf("bodies %q, want the identity token", *bodies) + } + if tc.JSON { + var doc api.ExchangedToken + if err := json.Unmarshal(out.Bytes(), &doc); err != nil || doc.Token != policyToken || doc.ExpiresAt.IsZero() { + t.Errorf("stdout %s decodes to %+v, %v", out.String(), doc, err) + } + return + } + if out.String() != tc.WantOut || progress.String() != tc.WantProgress { + t.Errorf("stdout %q and progress %q, want %q and %q", out.String(), progress.String(), tc.WantOut, tc.WantProgress) + } + }) + } +} + +func TestExchangeToken_Export(t *testing.T) { + setJSON(t, false) + env := filepath.Join(t.TempDir(), "github_env") + if err := os.WriteFile(env, []byte("EARLIER=1\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("GITHUB_ENV", env) + t.Setenv("GITHUB_ACTIONS", "true") + client, _ := newExchangeAPI(t, http.StatusOK, exchanged) + var out, progress bytes.Buffer + if err := exchangeToken(client, "acme", "web", "jwt", true, &out, &progress); err != nil { + t.Fatalf("exchangeToken: %v", err) + } + data, _ := os.ReadFile(env) + if string(data) != "EARLIER=1\nVALAR_TOKEN="+policyToken+"\n" { + t.Errorf("GITHUB_ENV holds %q", data) + } + if out.Len() != 0 { + t.Errorf("stdout %q, want nothing when exporting", out.String()) + } + if !strings.HasPrefix(progress.String(), "::add-mask::"+policyToken+"\n") || !strings.Contains(progress.String(), "Set VALAR_TOKEN") { + t.Errorf("progress %q, want the mask and a note", progress.String()) + } +} + +func TestExchangeToken_InvalidToken(t *testing.T) { + for name, token := range map[string]string{ + "Injection": policyToken + "\nBASH_ENV=/tmp/evil", + "Short": "valar_ut_0123", + "AgentKind": strings.Replace(policyToken, "valar_ut_", "valar_at_", 1), + "Empty": "", + } { + t.Run(name, func(t *testing.T) { + for _, export := range []bool{false, true} { + setJSON(t, false) + env := filepath.Join(t.TempDir(), "github_env") + if err := os.WriteFile(env, nil, 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("GITHUB_ENV", env) + t.Setenv("GITHUB_ACTIONS", "true") + body, _ := json.Marshal(map[string]string{"token": token, "expiresAt": "2026-11-21T13:00:00Z"}) + client, _ := newExchangeAPI(t, http.StatusOK, string(body)) + var out, progress bytes.Buffer + err := exchangeToken(client, "acme", "web", "jwt", export, &out, &progress) + if err == nil || classify(err, kindFailed) != kindUnavailable { + t.Errorf("export %v: error %v, want unavailable", export, err) + } + data, _ := os.ReadFile(env) + if out.Len() != 0 || progress.Len() != 0 || len(data) != 0 { + t.Errorf("export %v: printed %q and %q and exported %q", export, out.String(), progress.String(), data) + } + } + }) + } +} + +func TestExchangeToken_ExportOutsideActions(t *testing.T) { + t.Setenv("GITHUB_ENV", "") + client, bodies := newExchangeAPI(t, http.StatusOK, exchanged) + err := exchangeToken(client, "acme", "web", "jwt", true, io.Discard, io.Discard) + if err == nil || classify(err, kindFailed) != kindInvalid || len(*bodies) != 0 { + t.Errorf("error %v after %d exchanges, want an invalid flag and none", err, len(*bodies)) + } +} + +func TestExchangeToken_Refused(t *testing.T) { + jwt := fakeJWT(t, map[string]any{ + "iss": api.GitHubIssuer, "sub": "repo:acme/web:ref:refs/heads/dev", "ref": "refs/heads/dev", + "repository_id": "123", "event_name": "push", "run_id": "99", "aud": "https://api.valar.dev", + }) + for _, tc := range []struct { + Name string + Status int + Body string + IDToken string + WantKind errorKind + Want []string + NotWant []string + }{ + { + Name: "NoPolicy", Status: http.StatusForbidden, Body: `{"error":"no trust policy admits this identity for acme/web"}`, IDToken: jwt, + WantKind: kindNotAllowed, + Want: []string{ + "no trust policy admits this identity for acme/web", "The identity token carries:", + "sub: repo:acme/web:ref:refs/heads/dev", "ref: refs/heads/dev", "repository_id: 123", "event_name: push", + }, + NotWant: []string{"run_id", jwt}, + }, + {Name: "OpaqueToken", Status: http.StatusForbidden, Body: `{"error":"no trust policy admits this identity for acme/web"}`, IDToken: "opaque", WantKind: kindNotAllowed, NotWant: []string{"carries"}}, + {Name: "Expired", Status: http.StatusUnauthorized, Body: `{"error":"token expired"}`, IDToken: jwt, WantKind: kindNotAllowed, Want: []string{"token expired"}, NotWant: []string{"carries", "Create a new token"}}, + {Name: "Replayed", Status: http.StatusConflict, Body: `{"error":"identity token already exchanged"}`, IDToken: jwt, WantKind: kindConflict, Want: []string{"already exchanged"}}, + {Name: "Disabled", Status: http.StatusNotFound, Body: `{"error":"deploys from CI are not enabled on this installation"}`, IDToken: jwt, WantKind: kindNotFound, Want: []string{"not enabled"}}, + } { + t.Run(tc.Name, func(t *testing.T) { + setJSON(t, false) + t.Setenv("GITHUB_ENV", "") + client, _ := newExchangeAPI(t, tc.Status, tc.Body) + var out, progress bytes.Buffer + err := exchangeToken(client, "acme", "web", tc.IDToken, false, &out, &progress) + if err == nil || classify(err, kindFailed) != tc.WantKind { + t.Fatalf("error %v of kind %v, want kind %v", err, classify(err, kindFailed), tc.WantKind) + } + var report bytes.Buffer + reportError(&report, err, kindFailed, false) + containsAll(t, "error", report.String(), tc.Want...) + for _, unwanted := range tc.NotWant { + if strings.Contains(report.String(), unwanted) { + t.Errorf("error %q contains %q", report.String(), unwanted) + } + } + if out.Len() != 0 || progress.Len() != 0 { + t.Errorf("printed %q and %q on a refusal", out.String(), progress.String()) + } + }) + } +} + +func TestExchangeToken_OlderServer(t *testing.T) { + client, _ := newFakeAPI(t, nil) + if err := exchangeToken(client, "acme", "web", "jwt", false, io.Discard, io.Discard); !errors.Is(err, api.ErrNoTrustAPI) { + t.Errorf("error = %v, want ErrNoTrustAPI", err) + } +} + +func TestAuthExchangeCommand(t *testing.T) { + writeServiceConfig(t, deployConfig) + var gotPath string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" { + t.Errorf("%s carries Authorization", r.URL.Path) + } + if r.URL.Path == "/" { + w.Write([]byte(`{"version":"v2"}`)) + return + } + gotPath = r.URL.Path + w.Write([]byte(exchanged)) + })) + t.Cleanup(srv.Close) + t.Setenv("GITHUB_ACTIONS", "") + t.Setenv(envIDTokenRequestURL, "") + t.Cleanup(func() { exchangeService, exchangeProject, exchangeIDTokenFile = "", "", "" }) + idToken := filepath.Join(t.TempDir(), "id-token") + if err := os.WriteFile(idToken, []byte("jwt"), 0o600); err != nil { + t.Fatal(err) + } + out := runCLI(t, srv.URL, "auth", "exchange", "--service", "api", "--id-token-file", idToken) + if gotPath != "/projects/p/services/api/token-exchange" { + t.Errorf("exchanged at %q, want the project of .valar.yml and --service", gotPath) + } + if !strings.Contains(out, `"token": "`+policyToken+`"`) { + t.Errorf("output %q lacks the token", out) + } +} diff --git a/cmd/github.go b/cmd/github.go new file mode 100644 index 0000000..cdd4b1e --- /dev/null +++ b/cmd/github.go @@ -0,0 +1,212 @@ +package cmd + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "slices" + "strconv" + "strings" + "time" +) + +// githubAPI is GitHub's REST API; tests replace it. +var githubAPI = "https://api.github.com" + +// immutableSubjectsSince is when new, renamed and transferred repositories +// started to get immutable subjects. +var immutableSubjectsSince = time.Date(2026, 7, 15, 0, 0, 0, 0, time.UTC) + +// githubRepo is what a trust policy needs to know about a repository. +type githubRepo struct { + ID int64 `json:"id"` + FullName string `json:"full_name"` + DefaultBranch string `json:"default_branch"` + CreatedAt time.Time `json:"created_at"` + Owner struct { + ID int64 `json:"id"` + } `json:"owner"` +} + +// githubSubjectTemplate is a repository's OIDC subject customization. +type githubSubjectTemplate struct { + UseDefault bool `json:"use_default"` + IncludeClaimKeys []string `json:"include_claim_keys"` + UseImmutableSubject bool `json:"use_immutable_subject"` + // SubClaimPrefix is the subject's repo part, such as repo:acme@45/web@123. + SubClaimPrefix string `json:"sub_claim_prefix"` +} + +// githubError is a GitHub answer other than 200. +type githubError struct { + Status int + Text string +} + +func (e githubError) Error() string { return "GitHub answered " + e.Text } + +// githubStatus returns the status of a GitHub answer other than 200, or 0. +func githubStatus(err error) int { + var gerr githubError + if errors.As(err, &gerr) { + return gerr.Status + } + return 0 +} + +// githubGet reads a GitHub API path with GH_TOKEN or GITHUB_TOKEN, if set. +func githubGet(path string, v any) error { + req, err := http.NewRequest(http.MethodGet, githubAPI+path, nil) + if err != nil { + return err + } + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("User-Agent", "valar-cli") + for _, name := range []string{"GH_TOKEN", "GITHUB_TOKEN"} { + if token := os.Getenv(name); token != "" { + req.Header.Set("Authorization", "Bearer "+token) + break + } + } + resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req) + if err != nil { + return fmt.Errorf("asking GitHub: %w", err) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return fmt.Errorf("asking GitHub: %w", err) + } + if resp.StatusCode != http.StatusOK { + return githubError{resp.StatusCode, resp.Status + " for " + path} + } + if err := json.Unmarshal(body, v); err != nil { + return fmt.Errorf("reading GitHub's answer for %s: %w", path, err) + } + return nil +} + +// githubPolicy describes a GitHub Actions trust policy: a repository with +// one of a branch, an environment or its pull requests. +type githubPolicy struct { + Repo string + Branch string + Environment string + PullRequests bool + // Workflow is a file in .github/workflows or a path, optionally followed + // by @ and the ref it runs from. + Workflow string + Event string +} + +// build reads the repository's IDs and subject format from GitHub and +// returns the policy's subject and claims. notes receives what it assumed. +func (p githubPolicy) build(notes io.Writer) (string, map[string]string, error) { + owner, name, ok := strings.Cut(p.Repo, "/") + if !ok || owner == "" || name == "" || strings.Contains(name, "/") { + return "", nil, newError(kindInvalid, "--github-repo %q is not owner/repo", p.Repo) + } + var repo githubRepo + if err := githubGet("/repos/"+owner+"/"+name, &repo); githubStatus(err) == http.StatusNotFound { + return "", nil, newError(kindNotFound, "GitHub has no repository %s that this CLI can read; for a private one, set GH_TOKEN to a token that can read it", p.Repo) + } else if err != nil { + return "", nil, withKind(kindUnavailable, err) + } + owner, name, _ = strings.Cut(repo.FullName, "/") + tmpl := githubSubjectTemplate{UseDefault: true, UseImmutableSubject: !repo.CreatedAt.Before(immutableSubjectsSince)} + err := githubGet("/repos/"+repo.FullName+"/actions/oidc/customization/sub", &tmpl) + switch status := githubStatus(err); { + case status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusNotFound: + format := "name-based" + if tmpl.UseImmutableSubject { + format = "immutable" + } + fmt.Fprintf(notes, "Could not read the OIDC subject settings of %s, so the subject assumes the default, %s format of a repository created %s. "+ + "Set GH_TOKEN to a token that can read the repository's Actions settings to check, or pass --subject.\n", + repo.FullName, format, repo.CreatedAt.Format("2006-01-02")) + case err != nil: + return "", nil, withKind(kindUnavailable, err) + } + prefix := tmpl.SubClaimPrefix + switch { + case prefix != "": + case tmpl.UseImmutableSubject: + prefix = fmt.Sprintf("repo:%s@%d/%s@%d", owner, repo.Owner.ID, name, repo.ID) + default: + prefix = "repo:" + repo.FullName + } + repoID, ownerID := strconv.FormatInt(repo.ID, 10), strconv.FormatInt(repo.Owner.ID, 10) + claims := map[string]string{"repository_id": repoID, "repository_owner_id": ownerID} + // Each subject key GitHub can write, with its value for this policy. + values := map[string]string{ + "repository": repo.FullName, "repository_owner": owner, + "repository_id": repoID, "repository_owner_id": ownerID, + } + // scope is the claim that tells this policy's jobs apart: the branch's + // ref or the environment. + context, scope := "pull_request", "" + if !p.PullRequests { + ref := repo.DefaultBranch + if p.Branch != "" { + ref, scope = p.Branch, "ref" + values["ref"] = "refs/heads/" + p.Branch + context = "ref:refs/heads/" + subjectValue(p.Branch) + } else { + scope = "environment" + values["environment"] = p.Environment + context = "environment:" + subjectValue(p.Environment) + } + claims["event_name"] = p.Event + claims["workflow_ref"] = workflowRef(repo.FullName, p.Workflow, ref) + values["event_name"], values["workflow_ref"] = claims["event_name"], claims["workflow_ref"] + } + keys := []string{"repo", "context"} + if !tmpl.UseDefault && len(tmpl.IncludeClaimKeys) > 0 { + keys = tmpl.IncludeClaimKeys + } + // A subject without the context would admit jobs of any branch or + // environment, so the claim pins it instead. + if scope != "" && !slices.Contains(keys, "context") && !slices.Contains(keys, scope) { + claims[scope] = values[scope] + } + parts := make([]string, len(keys)) + for i, key := range keys { + value, known := values[key] + switch { + case key == "repo": + parts[i] = prefix + case key == "context": + parts[i] = context + case known: + parts[i] = key + ":" + subjectValue(value) + default: + return "", nil, newError(kindInvalid, "%s puts %s in its OIDC subject (%s), which this policy cannot know; pass --subject and --claim instead of --github-repo", + repo.FullName, key, strings.Join(keys, ", ")) + } + } + return strings.Join(parts, ":"), claims, nil +} + +// subjectValue escapes a value as GitHub does in subjects. +func subjectValue(s string) string { + return strings.ReplaceAll(s, ":", "%3A") +} + +// workflowRef writes the workflow_ref claim of a workflow file that runs from +// branch, unless workflow names its own ref after @. +func workflowRef(repo, workflow, branch string) string { + path, ref, ok := strings.Cut(workflow, "@") + switch { + case !ok: + ref = "refs/heads/" + branch + case !strings.HasPrefix(ref, "refs/"): + ref = "refs/heads/" + ref + } + if !strings.Contains(path, "/") { + path = ".github/workflows/" + path + } + return repo + "/" + path + "@" + ref +} diff --git a/cmd/projects.go b/cmd/projects.go index f16b573..052e782 100644 --- a/cmd/projects.go +++ b/cmd/projects.go @@ -227,7 +227,7 @@ var ( authCmd = &cobra.Command{ Use: "auth", - Short: "Manage user and service permissions.", + Short: "Manage permissions, and exchange CI identity tokens for tokens.", } whoamiCmd = &cobra.Command{ diff --git a/cmd/root.go b/cmd/root.go index 1018bfc..487f26a 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -49,7 +49,9 @@ func init() { api.OnTokenExpiry = (&expiryNotice{w: os.Stderr, now: time.Now}).observe // Configure projects.go initProjectsCmd() + initExchangeCmd() initTokenCmd() + initTrustCmd() initAuditCmd() // Configure deployments.go initDeploymentsCmd() diff --git a/cmd/services.go b/cmd/services.go index a5a6e34..f26b72a 100644 --- a/cmd/services.go +++ b/cmd/services.go @@ -323,29 +323,48 @@ var serviceURLCmd = &cobra.Command{ return err } project, service := cfg.Project(), cfg.Service() - services, err := client.ListServices(project, service) + urls, err := lookupServiceURLs(client, project, service) if err != nil { - return fmt.Errorf("listing services: %w", err) - } - for _, svc := range services { - if svc.Name != service { - continue - } - urls := serviceURLs(project, svc) - if len(urls) == 0 { - return newError(kindNotFound, "service %s has no domains yet; it gets them with its first deployment", service) - } - return result(struct { - URLs []string `json:"urls"` - }{urls}, func(w io.Writer) error { - _, err := fmt.Fprintln(w, strings.Join(urls, "\n")) - return err - }) + return err } - return newError(kindNotFound, "service %s not found", service) + return result(struct { + URLs []string `json:"urls"` + }{urls}, func(w io.Writer) error { + _, err := fmt.Fprintln(w, strings.Join(urls, "\n")) + return err + }) }), } +// lookupServiceURLs asks the inspect route, which a token bound to the +// service may read, and falls back to the listing on servers without it. +func lookupServiceURLs(client *api.Client, project, service string) ([]string, error) { + noDomains := newError(kindNotFound, "service %s has no domains yet; it gets them with its first deployment", service) + svc, err := client.InspectService(project, service) + switch { + case err == nil && len(svc.URLs) == 0: + return nil, noDomains + case err == nil: + return svc.URLs, nil + case !errors.Is(err, api.ErrNoInspectAPI): + return nil, fmt.Errorf("inspecting service: %w", err) + } + services, err := client.ListServices(project, service) + if err != nil { + return nil, fmt.Errorf("listing services: %w", err) + } + for _, svc := range services { + if svc.Name != service { + continue + } + if urls := serviceURLs(project, svc); len(urls) > 0 { + return urls, nil + } + return nil, noDomains + } + return nil, newError(kindNotFound, "service %s not found", service) +} + // serviceURLs orders a service's domains as URLs: linked custom domains first, // then the canonical -. ones, shortest first. func serviceURLs(project string, svc api.Service) []string { diff --git a/cmd/services_test.go b/cmd/services_test.go index 9f3a40a..eed0e90 100644 --- a/cmd/services_test.go +++ b/cmd/services_test.go @@ -197,3 +197,60 @@ func TestShowServiceLogs(t *testing.T) { }) } } + +func TestLookupServiceURLs(t *testing.T) { + const ( + inspect = "GET /projects/p/services/web/inspect" + list = "GET /projects/p/services/web" + ) + for _, tc := range []struct { + Name string + Routes map[string]string + Statuses map[string]int + Want []string + WantKind errorKind + WantCalls []string + }{ + { + Name: "Inspect", + Routes: map[string]string{inspect: `{"name":"web","domains":["p-web.valar.app","web.example.com"],"urls":["https://web.example.com","https://p-web.valar.app"]}`}, + Want: []string{"https://web.example.com", "https://p-web.valar.app"}, WantCalls: []string{inspect}, + }, + { + Name: "InspectWithoutDomains", Routes: map[string]string{inspect: `{"name":"web","urls":[]}`}, + WantKind: kindNotFound, WantCalls: []string{inspect}, + }, + { + Name: "InspectNotFound", Routes: map[string]string{inspect: `{"error":"service not found"}`}, Statuses: map[string]int{inspect: http.StatusNotFound}, + WantKind: kindNotFound, WantCalls: []string{inspect}, + }, + { + Name: "InspectRefused", Routes: map[string]string{inspect: `{"error":"token is bound to service api"}`}, Statuses: map[string]int{inspect: http.StatusForbidden}, + WantKind: kindNotAllowed, WantCalls: []string{inspect}, + }, + { + Name: "OlderServer", + Routes: map[string]string{list: `[{"name":"webapp","domains":["p-webapp.valar.app"]},{"name":"web","domains":["p-web.valar.app","web.example.com"]}]`}, + Want: []string{"https://web.example.com", "https://p-web.valar.app"}, WantCalls: []string{inspect, list}, + }, + { + Name: "OlderServerUnknownService", Routes: map[string]string{list: `[{"name":"webapp"}]`}, + WantKind: kindNotFound, WantCalls: []string{inspect, list}, + }, + } { + t.Run(tc.Name, func(t *testing.T) { + client, requests := newFakeAPIWithStatus(t, tc.Routes, tc.Statuses) + got, err := lookupServiceURLs(client, "p", "web") + if tc.WantKind != 0 { + if err == nil || classify(err, kindFailed) != tc.WantKind { + t.Errorf("error %v of kind %v, want kind %v", err, classify(err, kindFailed), tc.WantKind) + } + } else if err != nil || !reflect.DeepEqual(got, tc.Want) { + t.Errorf("lookupServiceURLs = %v, %v; want %v", got, err, tc.Want) + } + if calls := routeOrder(*requests); !reflect.DeepEqual(calls, tc.WantCalls) { + t.Errorf("requests %v, want %v", calls, tc.WantCalls) + } + }) + } +} diff --git a/cmd/token.go b/cmd/token.go index 0899a54..93d8d05 100644 --- a/cmd/token.go +++ b/cmd/token.go @@ -7,6 +7,7 @@ import ( "net/url" "os" "regexp" + "slices" "strconv" "strings" "sync" @@ -78,9 +79,14 @@ var ( tokenService string tokenScopes []string tokenTTL string + tokenAgent bool ) -var tokenIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) +// maxAgentTTL is the platform's limit for agent tokens (RFC-0011). +const maxAgentTTL = 30 * 24 * time.Hour + +// idPattern matches the IDs of tokens and trust policies. +var idPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) var ( tokenCmd = &cobra.Command{ @@ -96,7 +102,7 @@ binding, can create tokens. These commands need a newer Valar platform.`, } tokenCreateCmd = &cobra.Command{ - Use: "create [--project p] [--service s] [--scopes read,deploy] [--ttl 90d] name", + Use: "create [--project p] [--service s] [--scopes read,deploy] [--ttl 90d] [--agent] name", Short: "Create a token and print it once.", Long: `Create a token that acts as you, and print it once. @@ -110,12 +116,20 @@ A token for CI that pushes and deploys one project needs only read and deploy: 12h. It defaults to 90 days and is at most 365 days, and the token expires no later than the token that creates it. +--agent creates a token for an AI agent's MCP client. It works only at the +platform's MCP endpoint, not with this CLI or the API, needs --project, can +only read, and lasts 7 days by default and at most 30: + + valar token create claude --agent --project acme --ttl 30d + +` + agentClientHelp(mcpURL(config.DefaultEndpoint)) + ` + The token goes to stdout and everything else to stderr, so TOKEN=$(valar token create ci) captures only the token. Valar shows it this once: store it right away.`, Args: cobra.ExactArgs(1), Run: runAndHandle(func(cmd *cobra.Command, args []string) error { - req, ttl, err := newTokenRequest(args[0], tokenProject, tokenService, tokenScopes, tokenTTL) + req, ttl, err := newTokenRequest(args[0], tokenProject, tokenService, tokenScopes, tokenTTL, tokenAgent) if err != nil { return err } @@ -190,11 +204,20 @@ func ttlString(d time.Duration) string { // newTokenRequest checks the flags of token create and returns the request // and the lifetime it asks for, zero for the server's default. -func newTokenRequest(name, project, service string, scopes []string, ttl string) (api.TokenRequest, time.Duration, error) { +func newTokenRequest(name, project, service string, scopes []string, ttl string, agent bool) (api.TokenRequest, time.Duration, error) { req := api.TokenRequest{Name: name, Project: project, Service: service, Scopes: scopes} if service != "" && project == "" { return req, 0, newError(kindInvalid, "--service needs --project") } + if agent { + if project == "" { + return req, 0, newError(kindInvalid, "--agent needs --project: an agent token acts on one project") + } + if len(scopes) > 0 && !slices.Equal(scopes, []string{"read"}) { + return req, 0, newError(kindInvalid, "agent tokens can only read; leave out --scopes") + } + req.Kind, req.Scopes = "agent", []string{"read"} + } if ttl == "" { return req, 0, nil } @@ -202,10 +225,38 @@ func newTokenRequest(name, project, service string, scopes []string, ttl string) if err != nil { return req, 0, withKind(kindInvalid, err) } + if agent && d > maxAgentTTL { + return req, 0, newError(kindInvalid, "agent tokens last at most 30 days; --ttl %s is longer", ttl) + } req.TTL = ttlString(d) return req, d, nil } +// mcpURL is the MCP endpoint next to the API's /v2 endpoint. +func mcpURL(endpoint string) string { + return strings.TrimSuffix(strings.TrimSuffix(endpoint, "/"), "/v2") + "/mcp" +} + +// agentClientHelp says how to give MCP clients an agent token without +// writing it into their configuration (RFC-0011). +func agentClientHelp(mcp string) string { + return `An MCP client reaches ` + mcp + ` with the header +"Authorization: Bearer ". Keep the token in a password manager or the +client's secret store and give it to the client as VALAR_AGENT_TOKEN, which +Claude Code expands in its configuration: + + claude mcp add --transport http valar ` + mcp + ` \ + --header 'Authorization: Bearer ${VALAR_AGENT_TOKEN}' + +Other clients that speak Streamable HTTP take the same URL and header, such +as in an mcpServers entry: + + {"mcpServers": {"valar": {"type": "http", "url": "` + mcp + `", + "headers": {"Authorization": "Bearer ${VALAR_AGENT_TOKEN}"}}}} + +Do not run the agent where it can read ~/.valar, which holds your own token.` +} + // createToken mints a token and writes its value alone to w, and what it // grants to progress. func createToken(client *api.Client, req api.TokenRequest, ttl time.Duration, w, progress io.Writer, now time.Time) error { @@ -213,7 +264,15 @@ func createToken(client *api.Client, req api.TokenRequest, ttl time.Duration, w, if err != nil { return err } - return emit(w, token, func(w io.Writer) error { + agent := req.Kind == "agent" + var doc any = token + if agent { + doc = struct { + *api.MintedToken + MCPURL string `json:"mcpUrl"` + }{token, mcpURL(client.Endpoint)} + } + return emit(w, doc, func(w io.Writer) error { fmt.Fprintf(progress, "Created token %s.\n", token.Name) tw := ansiterm.NewTabWriter(progress, 6, 0, 1, ' ', 0) writeRows(tw, tokenRows(token.Token, now)) @@ -224,8 +283,13 @@ func createToken(client *api.Client, req api.TokenRequest, ttl time.Duration, w, fmt.Fprintln(progress, "It expires with the token that created it, before the --ttl asked for.") } fmt.Fprintln(progress, "Store the token now; Valar shows it only once:") - _, err := fmt.Fprintln(w, token.Value) - return err + if _, err := fmt.Fprintln(w, token.Value); err != nil { + return err + } + if agent { + fmt.Fprintln(progress, "\n"+agentClientHelp(mcpURL(client.Endpoint))) + } + return nil }) } @@ -273,7 +337,7 @@ func printTokens(w io.Writer, tokens []api.Token, withOwner bool, now time.Time) } func revokeToken(client *api.Client, project, id string, w io.Writer) error { - if !tokenIDPattern.MatchString(id) { + if !idPattern.MatchString(id) { return newError(kindInvalid, "%q is not a token ID; 'valar token list' shows them", id) } if project != "" { @@ -381,7 +445,8 @@ func initTokenCmd() { tokenCreateCmd.Flags().StringVar(&tokenProject, "project", "", "Bind the token to this project") tokenCreateCmd.Flags().StringVar(&tokenService, "service", "", "Bind the token to this service of the project") tokenCreateCmd.Flags().StringSliceVar(&tokenScopes, "scopes", nil, "What the token may do: read, deploy, invoke, kv or all (default all)") - tokenCreateCmd.Flags().StringVar(&tokenTTL, "ttl", "", "Lifetime, such as 30d or 12h (default 90d)") + tokenCreateCmd.Flags().StringVar(&tokenTTL, "ttl", "", "Lifetime, such as 30d or 12h (default 90d, 7d for --agent)") + tokenCreateCmd.Flags().BoolVar(&tokenAgent, "agent", false, "Create a read-only token for an MCP client, bound to --project") tokenListCmd.Flags().StringVar(&tokenProject, "project", "", "List the tokens bound to this project instead of yours") tokenRevokeCmd.Flags().StringVar(&tokenProject, "project", "", "Revoke a token from this project's list") tokenCmd.AddCommand(tokenCreateCmd, tokenListCmd, tokenRevokeCmd) diff --git a/cmd/token_test.go b/cmd/token_test.go index 8c446da..f06ecac 100644 --- a/cmd/token_test.go +++ b/cmd/token_test.go @@ -198,6 +198,7 @@ func TestNewTokenRequest(t *testing.T) { Project, Service string Scopes []string TTL string + Agent bool Want api.TokenRequest WantKind errorKind }{ @@ -210,9 +211,17 @@ func TestNewTokenRequest(t *testing.T) { {Name: "Service", Project: "acme", Service: "web", Want: api.TokenRequest{Name: "ci", Project: "acme", Service: "web"}}, {Name: "ServiceWithoutProject", Service: "web", WantKind: kindInvalid}, {Name: "BadTTL", TTL: "soon", WantKind: kindInvalid}, + {Name: "Agent", Project: "acme", Agent: true, Want: api.TokenRequest{Name: "ci", Kind: "agent", Project: "acme", Scopes: []string{"read"}}}, + { + Name: "AgentForServiceAtMost", Project: "acme", Service: "web", Scopes: []string{"read"}, TTL: "30d", Agent: true, + Want: api.TokenRequest{Name: "ci", Kind: "agent", Project: "acme", Service: "web", Scopes: []string{"read"}, TTL: "720h"}, + }, + {Name: "AgentWithoutProject", Agent: true, WantKind: kindInvalid}, + {Name: "AgentThatDeploys", Project: "acme", Scopes: []string{"read", "deploy"}, Agent: true, WantKind: kindInvalid}, + {Name: "AgentBeyond30Days", Project: "acme", TTL: "31d", Agent: true, WantKind: kindInvalid}, } { t.Run(tc.Name, func(t *testing.T) { - req, _, err := newTokenRequest("ci", tc.Project, tc.Service, tc.Scopes, tc.TTL) + req, _, err := newTokenRequest("ci", tc.Project, tc.Service, tc.Scopes, tc.TTL, tc.Agent) if tc.WantKind != 0 { if got := classify(err, kindFailed); err == nil || got != tc.WantKind { t.Errorf("error %v of kind %v, want kind %v", err, got, tc.WantKind) @@ -289,6 +298,65 @@ func TestCreateToken(t *testing.T) { } } +func TestCreateToken_Agent(t *testing.T) { + const minted = `{"id":"` + ciTokenID + `","kind":"agent","name":"claude","project":"acme","scopes":["read"],"parent":"` + rootTokenID + + `","createdAt":"2026-11-21T12:00:00Z","expiresAt":"2026-11-28T12:00:00Z","value":"valar_at_secret"}` + req := api.TokenRequest{Name: "claude", Kind: "agent", Project: "acme", Scopes: []string{"read"}} + t.Run("Human", func(t *testing.T) { + setJSON(t, false) + client, requests := newFakeAPI(t, map[string]string{"POST /tokens": minted}) + var out, progress bytes.Buffer + if err := createToken(client, req, 0, &out, &progress, tokenNow); err != nil { + t.Fatalf("createToken: %v", err) + } + if got, want := (*requests)[0].Body, `{"name":"claude","kind":"agent","project":"acme","scopes":["read"]}`; got != want { + t.Errorf("body = %s, want %s", got, want) + } + if out.String() != "valar_at_secret\n" { + t.Errorf("stdout %q, want only the token", out.String()) + } + mcp := client.Endpoint + "/mcp" + containsAll(t, "progress", progress.String(), + "Kind:", "agent", "Binding:", "project acme", + "claude mcp add --transport http valar "+mcp, + "--header 'Authorization: Bearer ${VALAR_AGENT_TOKEN}'", + `"url": "`+mcp+`"`, + "~/.valar", + ) + if strings.Contains(progress.String(), "valar_at_secret") { + t.Errorf("progress %q shows the token", progress.String()) + } + }) + t.Run("JSON", func(t *testing.T) { + setJSON(t, true) + client, _ := newFakeAPI(t, map[string]string{"POST /tokens": minted}) + var out, progress bytes.Buffer + if err := createToken(client, req, 0, &out, &progress, tokenNow); err != nil { + t.Fatalf("createToken: %v", err) + } + var doc struct { + api.MintedToken + MCPURL string `json:"mcpUrl"` + } + if err := json.Unmarshal(out.Bytes(), &doc); err != nil || doc.Value != "valar_at_secret" || doc.Kind != "agent" || doc.MCPURL != client.Endpoint+"/mcp" { + t.Errorf("stdout %s decodes to %+v, %v", out.String(), doc, err) + } + }) +} + +func TestMCPURL(t *testing.T) { + for in, want := range map[string]string{ + "https://api.valar.dev/v2": "https://api.valar.dev/mcp", + "https://api.valar.dev/v2/": "https://api.valar.dev/mcp", + "https://valar.example.com/api/v2": "https://valar.example.com/api/mcp", + "http://localhost:8080": "http://localhost:8080/mcp", + } { + if got := mcpURL(in); got != want { + t.Errorf("mcpURL(%q) = %q, want %q", in, got, want) + } + } +} + func TestCreateToken_Refused(t *testing.T) { for _, tc := range []struct { Name string @@ -526,7 +594,7 @@ func TestPrintUserInfo(t *testing.T) { func runTokenCLI(t *testing.T, endpoint string, args ...string) string { t.Helper() t.Cleanup(func() { - tokenProject, tokenService, tokenScopes, tokenTTL = "", "", nil, "" + tokenProject, tokenService, tokenScopes, tokenTTL, tokenAgent = "", "", nil, "", false auditProject, auditLimit, auditBefore = "", defaultAuditLimit, 0 }) return runCLI(t, endpoint, args...) @@ -545,6 +613,11 @@ func TestTokenCommands_Flags(t *testing.T) { []string{"token", "create", "ci", "--project", "acme", "--scopes", "read,deploy", "--ttl", "30d"}, "POST /tokens", ciMinted, `{"name":"ci","project":"acme","scopes":["read","deploy"],"ttl":"720h"}`, }, + { + "CreateAgent", + []string{"token", "create", "claude", "--agent", "--project", "acme", "--ttl", "30d"}, + "POST /tokens", ciMinted, `{"name":"claude","kind":"agent","project":"acme","scopes":["read"],"ttl":"720h"}`, + }, {"ListProject", []string{"token", "list", "--project", "acme"}, "GET /projects/acme/tokens", `[]`, ""}, {"RevokeProject", []string{"token", "revoke", ciTokenID, "--project", "acme"}, "DELETE /projects/acme/tokens/" + ciTokenID, `{"revoked":1}`, ""}, {"AuditActiveProject", []string{"audit"}, "GET /projects/p/audit", `[]`, ""}, diff --git a/cmd/trust.go b/cmd/trust.go new file mode 100644 index 0000000..e5e886e --- /dev/null +++ b/cmd/trust.go @@ -0,0 +1,366 @@ +package cmd + +import ( + "fmt" + "io" + "os" + "regexp" + "slices" + "sort" + "strings" + "time" + + "github.com/juju/ansiterm" + "github.com/spf13/cobra" + "github.com/valar/cli/api" + "github.com/valar/cli/config" +) + +var ( + trustProject string + trustService string + trustIssuer string + trustSubject string + trustClaims []string + trustForce bool + trustGitHub githubPolicy +) + +// riskyEvents run with the repository's credentials on input that pull +// requests or comments control. +var riskyEvents = []string{"pull_request_target", "workflow_run", "issue_comment"} + +// immutableSubject matches a GitHub subject that carries the repository's ID. +var immutableSubject = regexp.MustCompile(`^repo:[^:/]+@[0-9]+/[^:]+@[0-9]+(:|$)`) + +var ( + trustCmd = &cobra.Command{ + Use: "trust", + Short: "Let CI jobs deploy without a stored token.", + Long: `Let CI jobs deploy without a stored token. + +A trust policy lets a CI job exchange its provider's identity token for a token +that acts as you, bound to one service with read and deploy, for an hour +('valar auth exchange'; the Valar GitHub Action does it on its own). Policies +need permission to manage the project and a token created in the console or +with authctl, and an installation that trusts the CI provider's identity +tokens. Deleting a policy revokes its tokens.`, + } + + trustAddCmd = &cobra.Command{ + Use: "add --service s (--github-repo owner/repo ... | --subject sub [--claim k=v]...)", + Aliases: []string{"create"}, + Short: "Add a trust policy for a service or for pull request previews.", + Long: `Add a trust policy for a service or for pull request previews. + +For GitHub Actions, --github-repo builds the policy: it reads the repository's +ID, its owner's ID and its subject format from GitHub, and pins both IDs, so a +renamed or re-registered repository or owner does not match. Give one of: + + --branch main --workflow deploy.yml + Jobs of .github/workflows/deploy.yml on main, triggered by --event + (push by default), may deploy the service. + + --environment production --workflow deploy.yml + Jobs that name the environment in that workflow, run from the default + branch, may deploy; --workflow deploy.yml@refs/heads/release names + another ref. Protect the environment with deployment branch rules: + GitHub issues its subject to every job that names it. + + --pull-requests + Each pull request of the repository may deploy only the preview whose + name is the --service prefix, which ends in *, followed by its number: + --service 'webpr*' admits webpr42 to pull request 42. A private + repository may give pull requests from forks identity tokens too. + + valar trust add --service web --github-repo acme/web --branch main --workflow deploy.yml + valar trust add --service 'webpr*' --github-repo acme/web --pull-requests + +For a private repository, or to read whether it uses immutable subjects, set +GH_TOKEN to a GitHub token that can read it, such as GH_TOKEN=$(gh auth token). + +Without --github-repo, --subject is the identity token's sub claim, matched +exactly, and each --claim k=v another claim it must carry. --issuer defaults to +GitHub Actions' issuer and must be one the installation trusts. + +Policies for pull_request_target, workflow_run and issue_comment jobs, which +run with the repository's credentials on input that others control, and +hand-written ones that admit pull requests to a service rather than to its +previews need --force.`, + Args: cobra.NoArgs, + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + project, err := commandProject(trustProject) + if err != nil { + return err + } + req, err := newTrustPolicyRequest(trustService, trustIssuer, trustSubject, trustClaims, trustGitHub, trustForce, os.Stderr) + if err != nil { + return err + } + client, err := globalConfiguration.APIClient() + if err != nil { + return err + } + return addTrustPolicy(client, project, req, stdout, os.Stderr) + }), + } + + trustListCmd = &cobra.Command{ + Use: "list [--project p]", + Aliases: []string{"ls"}, + Short: "List the project's trust policies, oldest first.", + Args: cobra.NoArgs, + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + project, err := commandProject(trustProject) + if err != nil { + return err + } + client, err := globalConfiguration.APIClient() + if err != nil { + return err + } + return listTrustPolicies(client, project, stdout, time.Now()) + }), + } + + trustRemoveCmd = &cobra.Command{ + Use: "remove [--project p] id", + Aliases: []string{"delete", "rm"}, + Short: "Remove a trust policy and revoke its tokens.", + Args: cobra.ExactArgs(1), + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + project, err := commandProject(trustProject) + if err != nil { + return err + } + client, err := globalConfiguration.APIClient() + if err != nil { + return err + } + return removeTrustPolicy(client, project, args[0], stdout) + }), + } +) + +// commandProject is the --project flag, or the project of .valar.yml, +// VALAR_PROJECT or the active context. +func commandProject(flag string) (string, error) { + project := flag + if project == "" { + cfg, err := config.NewServiceConfigWithFallback(functionConfiguration, nil, globalConfiguration) + if err != nil { + return "", err + } + project = cfg.Project() + } + if err := api.VerifyProjectName(project); err != nil { + return "", withKind(kindInvalid, err) + } + return project, nil +} + +// newTrustPolicyRequest checks the flags of trust add and, with a GitHub +// repository, asks GitHub for the subject and claims. Without force, it +// refuses policies for risky events and hand-written ones that admit pull +// requests to a service. notes receives warnings and what it assumed. +func newTrustPolicyRequest(service, issuer, subject string, claimArgs []string, github githubPolicy, force bool, notes io.Writer) (api.TrustPolicyRequest, error) { + req := api.TrustPolicyRequest{Service: service, Issuer: issuer} + preview, isPreview := strings.CutSuffix(service, "*") + switch { + case service == "": + return req, newError(kindInvalid, "--service is required: a service name, or a preview prefix followed by *") + case api.VerifyServiceName(preview) != nil: + return req, newError(kindInvalid, "--service %q is neither a service name nor a preview prefix followed by *", service) + } + claims, err := parseClaims(claimArgs) + if err != nil { + return req, err + } + if github.Repo == "" { + if github.Branch != "" || github.Environment != "" || github.PullRequests || github.Workflow != "" { + return req, newError(kindInvalid, "--branch, --environment, --pull-requests and --workflow need --github-repo") + } + if subject == "" { + return req, newError(kindInvalid, "give --github-repo, or --subject with the identity token's sub claim") + } + if !isPreview && !force && slices.Contains(strings.Split(subject, ":"), "pull_request") { + return req, newError(kindInvalid, "subject %s admits every pull request of the repository to %s; use a preview prefix such as --service '%spr*', or pass --force", subject, service, service) + } + if err := allowEvent(claims["event_name"], force); err != nil { + return req, err + } + if strings.HasPrefix(issuer, api.GitHubIssuer) && claims["repository_id"] == "" && !immutableSubject.MatchString(subject) && !strings.Contains(subject, "repository_id:") { + fmt.Fprintln(notes, "Warning: the policy pins no repository ID, so a repository that later takes over the name would match. Add --claim repository_id=, or use --github-repo.") + } + req.Subject, req.Claims = subject, claims + return req, nil + } + if err := github.check(isPreview, subject); err != nil { + return req, err + } + if err := allowEvent(github.Event, force); err != nil { + return req, err + } + sub, built, err := github.build(notes) + if err != nil { + return req, err + } + for k, v := range claims { + if b, ok := built[k]; ok && b != v { + return req, newError(kindInvalid, "--claim %s=%s contradicts %s=%s from GitHub", k, v, k, b) + } + built[k] = v + } + if err := allowEvent(built["event_name"], force); err != nil { + return req, err + } + req.Subject, req.Claims = sub, built + return req, nil +} + +func allowEvent(event string, force bool) error { + if force || !slices.Contains(riskyEvents, event) { + return nil + } + return newError(kindInvalid, "%s jobs run with the repository's credentials on input that pull requests or comments control; pass --force to admit them anyway", event) +} + +// check refuses flag combinations that build no sensible policy. +func (p githubPolicy) check(preview bool, subject string) error { + kinds := 0 + for _, set := range []bool{p.Branch != "", p.Environment != "", p.PullRequests} { + if set { + kinds++ + } + } + switch { + case subject != "": + return newError(kindInvalid, "--github-repo writes the subject; leave out --subject") + case kinds != 1: + return newError(kindInvalid, "--github-repo needs exactly one of --branch, --environment and --pull-requests") + case p.PullRequests && !preview: + return newError(kindInvalid, "--pull-requests needs a preview prefix such as --service 'webpr*'") + case p.PullRequests && (p.Workflow != "" || p.Event != "push"): + return newError(kindInvalid, "--pull-requests pins no workflow or event; leave out --workflow and --event") + case !p.PullRequests && preview: + return newError(kindInvalid, "a preview prefix needs --pull-requests; branch and environment jobs have no pull request number") + case !p.PullRequests && p.Workflow == "": + return newError(kindInvalid, "--workflow is required with --branch and --environment, such as --workflow deploy.yml") + case p.Event == "": + return newError(kindInvalid, "--event must not be empty") + } + return nil +} + +// parseClaims reads k=v pairs. +func parseClaims(args []string) (map[string]string, error) { + if len(args) == 0 { + return nil, nil + } + claims := make(map[string]string, len(args)) + for _, arg := range args { + k, v, ok := strings.Cut(arg, "=") + if !ok || k == "" { + return nil, newError(kindInvalid, "--claim %q is not name=value", arg) + } + if _, dup := claims[k]; dup { + return nil, newError(kindInvalid, "--claim %s is given twice", k) + } + claims[k] = v + } + return claims, nil +} + +func addTrustPolicy(client *api.Client, project string, req api.TrustPolicyRequest, w, progress io.Writer) error { + policy, err := client.CreateTrustPolicy(project, req) + if err != nil { + return err + } + return emit(w, policy, func(w io.Writer) error { + if policy.Warning != "" { + fmt.Fprintf(progress, "Warning: %s.\n", policy.Warning) + } + fmt.Fprintf(w, "Added trust policy %s for %s/%s.\n", policy.ID, project, policy.Service) + tw := ansiterm.NewTabWriter(w, 6, 0, 1, ' ', 0) + writeRows(tw, trustRows(*policy)) + return tw.Flush() + }) +} + +func trustRows(p api.TrustPolicy) [][2]string { + rows := [][2]string{{"Issuer", p.Issuer}, {"Subject", p.Subject}} + for _, k := range sortedKeys(p.Claims) { + rows = append(rows, [2]string{"Claim " + k, p.Claims[k]}) + } + return rows +} + +func sortedKeys(m map[string]string) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +func listTrustPolicies(client *api.Client, project string, w io.Writer, now time.Time) error { + policies, err := client.ListTrustPolicies(project) + if err != nil { + return err + } + return emit(w, policies, func(w io.Writer) error { + tw := ansiterm.NewTabWriter(w, 6, 0, 1, ' ', 0) + fmt.Fprintln(tw, "ID\tSERVICE\tSUBJECT\tCLAIMS\tISSUER\tCREATED BY\tCREATED") + for _, p := range policies { + claims := make([]string, 0, len(p.Claims)) + for _, k := range sortedKeys(p.Claims) { + claims = append(claims, k+"="+p.Claims[k]) + } + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", p.ID, p.Service, p.Subject, orDash(strings.Join(claims, ",")), + p.Issuer, p.CreatedBy, relative(p.CreatedAt, now)) + } + return tw.Flush() + }) +} + +func removeTrustPolicy(client *api.Client, project, id string, w io.Writer) error { + if !idPattern.MatchString(id) { + return newError(kindInvalid, "%q is not a trust policy ID; 'valar trust list' shows them", id) + } + n, err := client.DeleteTrustPolicy(project, id) + if err != nil { + return err + } + return emit(w, struct { + ID string `json:"id"` + Revoked int `json:"revoked"` + }{id, n}, func(w io.Writer) error { + tokens := "tokens" + if n == 1 { + tokens = "token" + } + _, err := fmt.Fprintf(w, "Removed trust policy %s and revoked %d %s.\n", id, n, tokens) + return err + }) +} + +func initTrustCmd() { + add := trustAddCmd.Flags() + add.StringVar(&trustService, "service", "", "Service the policy deploys, or a preview prefix followed by *") + add.StringVar(&trustIssuer, "issuer", api.GitHubIssuer, "Issuer of the identity tokens") + add.StringVar(&trustSubject, "subject", "", "The identity token's sub claim, matched exactly") + add.StringArrayVar(&trustClaims, "claim", nil, "Another claim the identity token must carry, as name=value (repeatable)") + add.StringVar(&trustGitHub.Repo, "github-repo", "", "Build the policy for this GitHub repository, as owner/repo") + add.StringVar(&trustGitHub.Branch, "branch", "", "With --github-repo: admit jobs on this branch") + add.StringVar(&trustGitHub.Environment, "environment", "", "With --github-repo: admit jobs that name this environment") + add.BoolVar(&trustGitHub.PullRequests, "pull-requests", false, "With --github-repo: admit each pull request to its own preview") + add.StringVar(&trustGitHub.Workflow, "workflow", "", "With --branch or --environment: the workflow file, such as deploy.yml") + add.StringVar(&trustGitHub.Event, "event", "push", "With --branch or --environment: the event that triggers the workflow") + add.BoolVar(&trustForce, "force", false, "Admit pull_request_target, workflow_run or issue_comment jobs, or pull requests to a service") + for _, c := range []*cobra.Command{trustAddCmd, trustListCmd, trustRemoveCmd} { + c.Flags().StringVar(&trustProject, "project", "", "Project of the policy, instead of the active one") + } + trustCmd.AddCommand(trustAddCmd, trustListCmd, trustRemoveCmd) + rootCmd.AddCommand(trustCmd) +} diff --git a/cmd/trust_test.go b/cmd/trust_test.go new file mode 100644 index 0000000..703eabd --- /dev/null +++ b/cmd/trust_test.go @@ -0,0 +1,543 @@ +package cmd + +import ( + "bytes" + "cmp" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/valar/cli/api" +) + +const ( + policyID = "00112233445566778899aabbccddeeff" + policyJSON = `{"id":"` + policyID + `","service":"web","issuer":"https://token.actions.githubusercontent.com","subject":"repo:acme/web:ref:refs/heads/main","claims":{"repository_id":"123","event_name":"push"},"createdBy":"alice","createdAt":"2026-11-21T10:00:00Z"}` + previewJSON = `{"id":"ffeeddccbbaa99887766554433221100","service":"webpr*","issuer":"https://token.actions.githubusercontent.com","subject":"repo:acme/web:pull_request","claims":{},"createdBy":"bob","createdAt":"2026-11-20T12:00:00Z"}` + policiesPath = "/projects/acme/trust-policies" +) + +// fakeGitHub serves GitHub API paths and records the Authorization header +// of each request. +func fakeGitHub(t *testing.T, routes map[string]string, statuses map[string]int) *[]string { + t.Helper() + var auth []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + auth = append(auth, r.Header.Get("Authorization")) + if status, ok := statuses[r.URL.Path]; ok { + w.WriteHeader(status) + w.Write([]byte(`{"message":"Not Found"}`)) + return + } + body, ok := routes[r.URL.Path] + if !ok { + http.NotFound(w, r) + return + } + w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + prev := githubAPI + githubAPI = srv.URL + t.Cleanup(func() { githubAPI = prev }) + return &auth +} + +const ( + githubRepoJSON = `{"id":123,"full_name":"Acme/Web","default_branch":"master","created_at":"2020-01-02T00:00:00Z","owner":{"id":45}}` + newRepoJSON = `{"id":123,"full_name":"Acme/Web","default_branch":"main","created_at":"2026-08-01T00:00:00Z","owner":{"id":45}}` + repoPath = "/repos/acme/web" + subPath = "/repos/Acme/Web/actions/oidc/customization/sub" + defaultSub = `{"use_default":true}` +) + +func TestNewTrustPolicyRequest_GitHub(t *testing.T) { + ids := map[string]string{"repository_id": "123", "repository_owner_id": "45"} + with := func(extra map[string]string) map[string]string { + m := map[string]string{} + for k, v := range ids { + m[k] = v + } + for k, v := range extra { + m[k] = v + } + return m + } + for _, tc := range []struct { + Name string + Service string + Policy githubPolicy + Claims []string + Repo, Sub string + SubStatus int + WantSubject string + WantClaims map[string]string + WantNote string + }{ + { + Name: "Branch", Service: "web", + Policy: githubPolicy{Branch: "main", Workflow: "deploy.yml", Event: "push"}, + Repo: githubRepoJSON, Sub: defaultSub, + WantSubject: "repo:Acme/Web:ref:refs/heads/main", + WantClaims: with(map[string]string{"event_name": "push", "workflow_ref": "Acme/Web/.github/workflows/deploy.yml@refs/heads/main"}), + }, + { + Name: "EnvironmentImmutable", Service: "web", + Policy: githubPolicy{Environment: "prod:eu", Workflow: ".github/workflows/cd.yml", Event: "workflow_dispatch"}, + Repo: githubRepoJSON, Sub: `{"use_default":true,"use_immutable_subject":true}`, + WantSubject: "repo:Acme@45/Web@123:environment:prod%3Aeu", + WantClaims: with(map[string]string{"event_name": "workflow_dispatch", "workflow_ref": "Acme/Web/.github/workflows/cd.yml@refs/heads/master"}), + }, + { + Name: "EnvironmentFromRef", Service: "web", + Policy: githubPolicy{Environment: "prod", Workflow: "cd.yml@release", Event: "push"}, + Repo: githubRepoJSON, Sub: `{"use_default":false,"include_claim_keys":["repo","context"]}`, + WantSubject: "repo:Acme/Web:environment:prod", + WantClaims: with(map[string]string{"event_name": "push", "workflow_ref": "Acme/Web/.github/workflows/cd.yml@refs/heads/release"}), + }, + { + Name: "PullRequests", Service: "webpr*", + Policy: githubPolicy{PullRequests: true, Event: "push"}, + Claims: []string{"repository_visibility=private"}, + Repo: githubRepoJSON, Sub: defaultSub, + WantSubject: "repo:Acme/Web:pull_request", + WantClaims: with(map[string]string{"repository_visibility": "private"}), + }, + { + Name: "Prefix", Service: "webpr*", + Policy: githubPolicy{PullRequests: true, Event: "push"}, + Repo: newRepoJSON, Sub: `{"use_default":true,"use_immutable_subject":true,"sub_claim_prefix":"repo:Acme@45/Web@123"}`, + WantSubject: "repo:Acme@45/Web@123:pull_request", + WantClaims: ids, + }, + { + Name: "CustomKeys", Service: "web", + Policy: githubPolicy{Branch: "main", Workflow: "deploy.yml", Event: "push"}, + Repo: githubRepoJSON, Sub: `{"use_default":false,"include_claim_keys":["repository_owner_id","repository_id","context"],"sub_claim_prefix":"repo:Acme/Web"}`, + WantSubject: "repository_owner_id:45:repository_id:123:ref:refs/heads/main", + WantClaims: with(map[string]string{"event_name": "push", "workflow_ref": "Acme/Web/.github/workflows/deploy.yml@refs/heads/main"}), + }, + { + Name: "CustomKeysForEnvironment", Service: "web", + Policy: githubPolicy{Environment: "prod", Workflow: "deploy.yml", Event: "push"}, + Repo: githubRepoJSON, Sub: `{"use_default":false,"include_claim_keys":["repo","environment","workflow_ref"],"sub_claim_prefix":"repo:Acme/Web"}`, + WantSubject: "repo:Acme/Web:environment:prod:workflow_ref:Acme/Web/.github/workflows/deploy.yml@refs/heads/master", + WantClaims: with(map[string]string{"event_name": "push", "workflow_ref": "Acme/Web/.github/workflows/deploy.yml@refs/heads/master"}), + }, + { + Name: "NewRepoUnreadableSettings", Service: "webpr*", + Policy: githubPolicy{PullRequests: true, Event: "push"}, + Repo: newRepoJSON, SubStatus: http.StatusNotFound, + WantSubject: "repo:Acme@45/Web@123:pull_request", + WantClaims: ids, + WantNote: "assumes the default, immutable format of a repository created 2026-08-01", + }, + { + Name: "OldRepoUnreadableSettings", Service: "web", + Policy: githubPolicy{Branch: "main", Workflow: "deploy.yml", Event: "push"}, + Repo: githubRepoJSON, SubStatus: http.StatusForbidden, + WantSubject: "repo:Acme/Web:ref:refs/heads/main", + WantClaims: with(map[string]string{"event_name": "push", "workflow_ref": "Acme/Web/.github/workflows/deploy.yml@refs/heads/main"}), + WantNote: "assumes the default, name-based format", + }, + } { + t.Run(tc.Name, func(t *testing.T) { + routes := map[string]string{repoPath: tc.Repo, subPath: tc.Sub} + statuses := map[string]int{} + if tc.SubStatus != 0 { + statuses[subPath] = tc.SubStatus + } + t.Setenv("GH_TOKEN", "gh-secret") + auth := fakeGitHub(t, routes, statuses) + tc.Policy.Repo = "acme/web" + var notes bytes.Buffer + req, err := newTrustPolicyRequest(tc.Service, api.GitHubIssuer, "", tc.Claims, tc.Policy, false, ¬es) + if err != nil { + t.Fatalf("newTrustPolicyRequest: %v", err) + } + want := api.TrustPolicyRequest{Service: tc.Service, Issuer: api.GitHubIssuer, Subject: tc.WantSubject, Claims: tc.WantClaims} + if !reflect.DeepEqual(req, want) { + t.Errorf("request\n got %+v\nwant %+v", req, want) + } + if tc.WantNote == "" && notes.Len() != 0 || !strings.Contains(notes.String(), tc.WantNote) { + t.Errorf("notes %q, want %q", notes.String(), tc.WantNote) + } + for _, a := range *auth { + if a != "Bearer gh-secret" { + t.Errorf("GitHub got Authorization %q, want GH_TOKEN", a) + } + } + }) + } +} + +func TestNewTrustPolicyRequest_Refused(t *testing.T) { + branch := githubPolicy{Repo: "acme/web", Branch: "main", Workflow: "deploy.yml", Event: "push"} + for _, tc := range []struct { + Name string + Service string + Subject string + Claims []string + Policy githubPolicy + Repo, Sub string + WantKind errorKind + Want string + }{ + {Name: "NoService", Subject: "s", WantKind: kindInvalid, Want: "--service is required"}, + {Name: "BadService", Service: "web-1", Subject: "s", WantKind: kindInvalid, Want: "neither a service name"}, + {Name: "StarInside", Service: "w*b", Subject: "s", WantKind: kindInvalid, Want: "neither a service name"}, + {Name: "NoSubject", Service: "web", WantKind: kindInvalid, Want: "give --github-repo, or --subject"}, + {Name: "BadClaim", Service: "web", Subject: "s", Claims: []string{"novalue"}, WantKind: kindInvalid, Want: "is not name=value"}, + {Name: "TwiceClaim", Service: "web", Subject: "s", Claims: []string{"a=1", "a=2"}, WantKind: kindInvalid, Want: "given twice"}, + {Name: "BranchWithoutRepo", Service: "web", Subject: "s", Policy: githubPolicy{Branch: "main"}, WantKind: kindInvalid, Want: "need --github-repo"}, + {Name: "RepoAndSubject", Service: "web", Subject: "s", Policy: branch, WantKind: kindInvalid, Want: "leave out --subject"}, + {Name: "NoKind", Service: "web", Policy: githubPolicy{Repo: "acme/web", Workflow: "d.yml", Event: "push"}, WantKind: kindInvalid, Want: "exactly one of"}, + {Name: "TwoKinds", Service: "web", Policy: githubPolicy{Repo: "acme/web", Branch: "main", Environment: "prod", Workflow: "d.yml", Event: "push"}, WantKind: kindInvalid, Want: "exactly one of"}, + {Name: "PullRequestsForService", Service: "web", Policy: githubPolicy{Repo: "acme/web", PullRequests: true, Event: "push"}, WantKind: kindInvalid, Want: "needs a preview prefix"}, + {Name: "PullRequestsWorkflow", Service: "webpr*", Policy: githubPolicy{Repo: "acme/web", PullRequests: true, Workflow: "d.yml", Event: "push"}, WantKind: kindInvalid, Want: "pins no workflow"}, + {Name: "BranchForPreviews", Service: "webpr*", Policy: branch, WantKind: kindInvalid, Want: "needs --pull-requests"}, + {Name: "NoWorkflow", Service: "web", Policy: githubPolicy{Repo: "acme/web", Branch: "main", Event: "push"}, WantKind: kindInvalid, Want: "--workflow is required"}, + {Name: "BadRepo", Service: "web", Policy: githubPolicy{Repo: "acme", Branch: "main", Workflow: "d.yml", Event: "push"}, WantKind: kindInvalid, Want: "is not owner/repo"}, + {Name: "UnknownRepo", Service: "web", Policy: branch, WantKind: kindNotFound, Want: "GitHub has no repository acme/web"}, + { + Name: "CustomSubject", Service: "web", Policy: branch, Repo: githubRepoJSON, + Sub: `{"use_default":false,"include_claim_keys":["repo","context","job_workflow_ref"]}`, + WantKind: kindInvalid, Want: "puts job_workflow_ref in its OIDC subject (repo, context, job_workflow_ref)", + }, + { + Name: "PreviewWithWorkflowInSubject", Service: "webpr*", Policy: githubPolicy{Repo: "acme/web", PullRequests: true, Event: "push"}, Repo: githubRepoJSON, + Sub: `{"use_default":false,"include_claim_keys":["repo","context","workflow_ref"]}`, + WantKind: kindInvalid, Want: "puts workflow_ref in its OIDC subject", + }, + { + Name: "ContradictingClaim", Service: "web", Policy: branch, Claims: []string{"event_name=workflow_dispatch"}, Repo: githubRepoJSON, Sub: defaultSub, + WantKind: kindInvalid, Want: "contradicts event_name=push", + }, + } { + t.Run(tc.Name, func(t *testing.T) { + routes := map[string]string{subPath: tc.Sub} + if tc.Repo != "" { + routes[repoPath] = tc.Repo + } + fakeGitHub(t, routes, nil) + if tc.Policy.Event == "" && tc.Policy.Repo != "" { + tc.Policy.Event = "push" + } + _, err := newTrustPolicyRequest(tc.Service, api.GitHubIssuer, tc.Subject, tc.Claims, tc.Policy, false, io.Discard) + if err == nil || !strings.Contains(err.Error(), tc.Want) || classify(err, kindFailed) != tc.WantKind { + t.Errorf("error %v of kind %v, want kind %v containing %q", err, classify(err, kindFailed), tc.WantKind, tc.Want) + } + }) + } +} + +func TestNewTrustPolicyRequest_ByHand(t *testing.T) { + req, err := newTrustPolicyRequest("web", "https://gitlab.example.com", "project_path:acme/web:ref_type:branch:ref:main", + []string{"project_id=7", "namespace_id=3"}, githubPolicy{Event: "push"}, false, io.Discard) + if err != nil { + t.Fatal(err) + } + want := api.TrustPolicyRequest{ + Service: "web", Issuer: "https://gitlab.example.com", Subject: "project_path:acme/web:ref_type:branch:ref:main", + Claims: map[string]string{"project_id": "7", "namespace_id": "3"}, + } + if !reflect.DeepEqual(req, want) { + t.Errorf("request %+v, want %+v", req, want) + } +} + +func TestAddTrustPolicy(t *testing.T) { + warned := strings.Replace(policyJSON, `"createdBy"`, `"warning":"rules allow service::acme, which the service account of every preview inherits","createdBy"`, 1) + setJSON(t, false) + client, requests := newFakeAPI(t, map[string]string{"POST " + policiesPath: warned}) + var out, progress bytes.Buffer + req := api.TrustPolicyRequest{Service: "web", Subject: "repo:acme/web:ref:refs/heads/main", Issuer: api.GitHubIssuer, Claims: map[string]string{"repository_id": "123"}} + if err := addTrustPolicy(client, "acme", req, &out, &progress); err != nil { + t.Fatalf("addTrustPolicy: %v", err) + } + if got, want := (*requests)[0].Body, `{"service":"web","subject":"repo:acme/web:ref:refs/heads/main","issuer":"https://token.actions.githubusercontent.com","claims":{"repository_id":"123"}}`; got != want { + t.Errorf("body = %s, want %s", got, want) + } + want := []string{ + "Added trust policy " + policyID + " for acme/web.", + "Issuer: https://token.actions.githubusercontent.com", + "Subject: repo:acme/web:ref:refs/heads/main", + "Claim event_name: push", + "Claim repository_id: 123", + } + if got := lines(out.String()); !reflect.DeepEqual(got, want) { + t.Errorf("printed\n got %q\nwant %q", got, want) + } + if got := progress.String(); got != "Warning: rules allow service::acme, which the service account of every preview inherits.\n" { + t.Errorf("progress %q, want the warning", got) + } +} + +func TestTrustPolicies_Refused(t *testing.T) { + for _, tc := range []struct { + Name string + Status int + Body string + WantKind errorKind + Want string + }{ + {"Duplicate", http.StatusConflict, `{"error":"an identical trust policy exists"}`, kindConflict, "an identical trust policy exists"}, + {"Child", http.StatusForbidden, `{"error":"only tokens minted in the console or with authctl can create trust policies"}`, kindNotAllowed, "only tokens minted in the console"}, + {"Disabled", http.StatusNotFound, `{"error":"deploys from CI are not enabled on this installation"}`, kindNotFound, "deploys from CI are not enabled"}, + {"BadIssuer", http.StatusBadRequest, `{"error":"issuer must be one of https://token.actions.githubusercontent.com"}`, kindInvalid, "issuer must be one of"}, + } { + t.Run(tc.Name, func(t *testing.T) { + setJSON(t, false) + client, _ := newFakeAPIWithStatus(t, map[string]string{"POST " + policiesPath: tc.Body}, map[string]int{"POST " + policiesPath: tc.Status}) + var out, progress bytes.Buffer + err := addTrustPolicy(client, "acme", api.TrustPolicyRequest{Service: "web", Subject: "s"}, &out, &progress) + if err == nil || !strings.Contains(err.Error(), tc.Want) || classify(err, kindFailed) != tc.WantKind { + t.Errorf("error %v of kind %v, want kind %v containing %q", err, classify(err, kindFailed), tc.WantKind, tc.Want) + } + if out.Len() != 0 || progress.Len() != 0 { + t.Errorf("printed %q and %q on a refusal", out.String(), progress.String()) + } + }) + } +} + +func TestListTrustPolicies(t *testing.T) { + setJSON(t, false) + client, _ := newFakeAPI(t, map[string]string{"GET " + policiesPath: "[" + policyJSON + "," + previewJSON + "]"}) + var out bytes.Buffer + if err := listTrustPolicies(client, "acme", &out, tokenNow); err != nil { + t.Fatal(err) + } + want := []string{ + "ID SERVICE SUBJECT CLAIMS ISSUER CREATED BY CREATED", + policyID + " web repo:acme/web:ref:refs/heads/main event_name=push,repository_id=123 https://token.actions.githubusercontent.com alice 2 hours ago", + "ffeeddccbbaa99887766554433221100 webpr* repo:acme/web:pull_request - https://token.actions.githubusercontent.com bob 1 day ago", + } + if got := lines(out.String()); !reflect.DeepEqual(got, want) { + t.Errorf("table\n got %q\nwant %q", got, want) + } +} + +func TestRemoveTrustPolicy(t *testing.T) { + for _, tc := range []struct { + Name string + ID string + Revoked string + Want string + WantKind errorKind + }{ + {Name: "None", ID: policyID, Revoked: `{"revoked":0}`, Want: "Removed trust policy " + policyID + " and revoked 0 tokens."}, + {Name: "One", ID: policyID, Revoked: `{"revoked":1}`, Want: "Removed trust policy " + policyID + " and revoked 1 token."}, + {Name: "BadID", ID: "web", WantKind: kindInvalid, Want: "is not a trust policy ID"}, + } { + t.Run(tc.Name, func(t *testing.T) { + setJSON(t, false) + client, requests := newFakeAPI(t, map[string]string{"DELETE " + policiesPath + "/" + policyID: tc.Revoked}) + var out bytes.Buffer + err := removeTrustPolicy(client, "acme", tc.ID, &out) + if tc.WantKind != 0 { + if err == nil || !strings.Contains(err.Error(), tc.Want) || classify(err, kindFailed) != tc.WantKind { + t.Errorf("error %v, want kind %v containing %q", err, tc.WantKind, tc.Want) + } + if len(*requests) != 0 { + t.Errorf("sent %v for an invalid ID", *requests) + } + return + } + if err != nil { + t.Fatal(err) + } + if got := strings.TrimSpace(out.String()); got != tc.Want { + t.Errorf("printed %q, want %q", got, tc.Want) + } + }) + } +} + +func TestTrustCommands_OlderServer(t *testing.T) { + setJSON(t, false) + client, _ := newFakeAPI(t, nil) + for name, err := range map[string]error{ + "add": addTrustPolicy(client, "acme", api.TrustPolicyRequest{Service: "web", Subject: "s"}, io.Discard, io.Discard), + "list": listTrustPolicies(client, "acme", io.Discard, tokenNow), + "remove": removeTrustPolicy(client, "acme", policyID, io.Discard), + } { + if !errors.Is(err, api.ErrNoTrustAPI) { + t.Errorf("%s: error = %v, want ErrNoTrustAPI", name, err) + } + } +} + +// runTrustCLI runs the root command and resets the trust flags afterwards. +func runTrustCLI(t *testing.T, endpoint string, args ...string) string { + t.Helper() + t.Cleanup(func() { + trustProject, trustService, trustIssuer, trustSubject, trustClaims, trustForce = "", "", api.GitHubIssuer, "", nil, false + trustGitHub = githubPolicy{Event: "push"} + }) + return runCLI(t, endpoint, args...) +} + +func TestTrustCommands_Flags(t *testing.T) { + for _, tc := range []struct { + Name string + Args []string + Route string + Response string + WantBody string + }{ + { + "Add", + []string{"trust", "add", "--service", "web", "--subject", "repo:acme/web:ref:refs/heads/main", "--claim", "repository_id=123"}, + "POST /projects/p/trust-policies", policyJSON, + `{"service":"web","subject":"repo:acme/web:ref:refs/heads/main","issuer":"https://token.actions.githubusercontent.com","claims":{"repository_id":"123"}}`, + }, + { + "CreateWithIssuer", + []string{"trust", "create", "--project", "acme", "--service", "webpr*", "--subject", "x", "--issuer", "https://gitlab.example.com"}, + "POST " + policiesPath, previewJSON, `{"service":"webpr*","subject":"x","issuer":"https://gitlab.example.com"}`, + }, + {"List", []string{"trust", "list", "--project", "acme"}, "GET " + policiesPath, "[" + policyJSON + "]", ""}, + {"Delete", []string{"trust", "delete", policyID}, "DELETE /projects/p/trust-policies/" + policyID, `{"revoked":2}`, ""}, + } { + t.Run(tc.Name, func(t *testing.T) { + writeServiceConfig(t, deployConfig) + client, requests := newFakeAPI(t, map[string]string{tc.Route: tc.Response}) + out := runTrustCLI(t, client.Endpoint, tc.Args...) + if got := routeOrder(*requests); len(got) != 1 || got[0] != tc.Route { + t.Fatalf("requests %v, want [%s]", got, tc.Route) + } + if tc.WantBody != "" && (*requests)[0].Body != tc.WantBody { + t.Errorf("body = %s, want %s", (*requests)[0].Body, tc.WantBody) + } + if !json.Valid([]byte(out)) { + t.Errorf("output %q is not JSON", out) + } + }) + } +} + +func TestWorkflowRef(t *testing.T) { + for _, tc := range []struct{ Workflow, Branch, Want string }{ + {"deploy.yml", "main", "acme/web/.github/workflows/deploy.yml@refs/heads/main"}, + {".github/workflows/deploy.yml", "main", "acme/web/.github/workflows/deploy.yml@refs/heads/main"}, + {"deploy.yml@release", "main", "acme/web/.github/workflows/deploy.yml@refs/heads/release"}, + {"deploy.yml@refs/tags/v1", "main", "acme/web/.github/workflows/deploy.yml@refs/tags/v1"}, + } { + if got := workflowRef("acme/web", tc.Workflow, tc.Branch); got != tc.Want { + t.Errorf("workflowRef(%q, %q) = %q, want %q", tc.Workflow, tc.Branch, got, tc.Want) + } + } +} + +func TestNewTrustPolicyRequest_SubjectTemplates(t *testing.T) { + branch := githubPolicy{Repo: "acme/web", Branch: "main", Workflow: "deploy.yml", Event: "push"} + env := githubPolicy{Repo: "acme/web", Environment: "prod", Workflow: "deploy.yml", Event: "push"} + previews := githubPolicy{Repo: "acme/web", PullRequests: true, Event: "push"} + for _, tc := range []struct { + Name string + Keys string + Policy githubPolicy + WantSubject string + // WantScope is the ref or environment claim the subject leaves out. + WantScope map[string]string + WantErr string + }{ + {Name: "RepoOnlyEnvironment", Keys: `["repo"]`, Policy: env, WantSubject: "repo:Acme/Web", WantScope: map[string]string{"environment": "prod"}}, + {Name: "RepoOnlyBranch", Keys: `["repo"]`, Policy: branch, WantSubject: "repo:Acme/Web", WantScope: map[string]string{"ref": "refs/heads/main"}}, + {Name: "RepoOnlyPreviews", Keys: `["repo"]`, Policy: previews, WantSubject: "repo:Acme/Web"}, + {Name: "IDsAndContext", Keys: `["repository_owner_id","repository_id","context"]`, Policy: env, WantSubject: "repository_owner_id:45:repository_id:123:environment:prod"}, + {Name: "EnvironmentKey", Keys: `["repo","environment"]`, Policy: env, WantSubject: "repo:Acme/Web:environment:prod"}, + {Name: "RefKey", Keys: `["repo","ref"]`, Policy: branch, WantSubject: "repo:Acme/Web:ref:refs/heads/main"}, + { + Name: "OwnerAndWorkflow", Keys: `["repository_owner","workflow_ref"]`, Policy: branch, + WantSubject: "repository_owner:Acme:workflow_ref:Acme/Web/.github/workflows/deploy.yml@refs/heads/main", + WantScope: map[string]string{"ref": "refs/heads/main"}, + }, + { + Name: "RepositoryAndEvent", Keys: `["repository","event_name"]`, Policy: env, + WantSubject: "repository:Acme/Web:event_name:push", WantScope: map[string]string{"environment": "prod"}, + }, + {Name: "EnvironmentKeyForBranch", Keys: `["repo","environment"]`, Policy: branch, WantErr: "puts environment in its OIDC subject"}, + {Name: "RefKeyForPreviews", Keys: `["repo","ref"]`, Policy: previews, WantErr: "puts ref in its OIDC subject"}, + } { + t.Run(tc.Name, func(t *testing.T) { + fakeGitHub(t, map[string]string{ + repoPath: githubRepoJSON, + subPath: `{"use_default":false,"include_claim_keys":` + tc.Keys + `,"sub_claim_prefix":"repo:Acme/Web"}`, + }, nil) + service := "web" + if tc.Policy.PullRequests { + service = "webpr*" + } + req, err := newTrustPolicyRequest(service, api.GitHubIssuer, "", nil, tc.Policy, false, io.Discard) + if tc.WantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.WantErr) { + t.Errorf("error %v, want one containing %q", err, tc.WantErr) + } + return + } + if err != nil { + t.Fatal(err) + } + if req.Subject != tc.WantSubject { + t.Errorf("subject %q, want %q", req.Subject, tc.WantSubject) + } + for _, k := range []string{"ref", "environment"} { + if req.Claims[k] != tc.WantScope[k] { + t.Errorf("claim %s = %q, want %q (claims %v)", k, req.Claims[k], tc.WantScope[k], req.Claims) + } + } + }) + } +} + +func TestNewTrustPolicyRequest_Guards(t *testing.T) { + const pull = "repo:acme/web:pull_request" + pinned := []string{"repository_id=123"} + for _, tc := range []struct { + Name string + Service string + Issuer string + Subject string + Claims []string + Policy githubPolicy + Force bool + WantErr string + WantNote bool + }{ + {Name: "PullRequestsToService", Service: "web", Subject: pull, Claims: pinned, WantErr: "admits every pull request of the repository to web"}, + {Name: "PullRequestsInCustomSubject", Service: "web", Subject: "repo:acme/web:pull_request:job_workflow_ref:x", Claims: pinned, WantErr: "admits every pull request"}, + {Name: "PullRequestsToServiceForced", Service: "web", Subject: pull, Claims: pinned, Force: true}, + {Name: "PullRequestsToPreviews", Service: "webpr*", Subject: pull, Claims: pinned}, + {Name: "TargetEvent", Service: "web", Subject: "repo:acme/web:ref:refs/heads/main", Claims: []string{"repository_id=123", "event_name=pull_request_target"}, WantErr: "pull_request_target jobs"}, + {Name: "TargetEventForced", Service: "web", Subject: "repo:acme/web:ref:refs/heads/main", Claims: []string{"repository_id=123", "event_name=issue_comment"}, Force: true}, + {Name: "BuilderWorkflowRun", Service: "web", Policy: githubPolicy{Repo: "acme/web", Branch: "main", Workflow: "d.yml", Event: "workflow_run"}, WantErr: "workflow_run jobs"}, + {Name: "BuilderClaimedEvent", Service: "webpr*", Claims: []string{"event_name=pull_request_target"}, Policy: githubPolicy{Repo: "acme/web", PullRequests: true, Event: "push"}, WantErr: "pull_request_target jobs"}, + {Name: "NoRepositoryID", Service: "web", Subject: "repo:acme/web:ref:refs/heads/main", WantNote: true}, + {Name: "ImmutableSubject", Service: "web", Subject: "repo:acme@45/web@123:ref:refs/heads/main"}, + {Name: "RepositoryIDInSubject", Service: "web", Subject: "repository_owner_id:45:repository_id:123:ref:refs/heads/main"}, + {Name: "OtherIssuer", Service: "web", Issuer: "https://gitlab.example.com", Subject: "project_path:acme/web:ref_type:branch:ref:main"}, + } { + t.Run(tc.Name, func(t *testing.T) { + fakeGitHub(t, map[string]string{repoPath: githubRepoJSON, subPath: defaultSub}, nil) + issuer := cmp.Or(tc.Issuer, api.GitHubIssuer) + var notes bytes.Buffer + _, err := newTrustPolicyRequest(tc.Service, issuer, tc.Subject, tc.Claims, tc.Policy, tc.Force, ¬es) + switch { + case tc.WantErr != "" && (err == nil || !strings.Contains(err.Error(), tc.WantErr) || classify(err, kindFailed) != kindInvalid): + t.Errorf("error %v, want an invalid one containing %q", err, tc.WantErr) + case tc.WantErr == "" && err != nil: + t.Errorf("error %v, want none", err) + } + if got := strings.Contains(notes.String(), "pins no repository ID"); got != tc.WantNote { + t.Errorf("notes %q, want the repository ID warning: %v", notes.String(), tc.WantNote) + } + }) + } +} diff --git a/config/context.go b/config/context.go index 909c716..5b26fe4 100644 --- a/config/context.go +++ b/config/context.go @@ -120,6 +120,18 @@ func (cfg *CLIConfig) Endpoint() string { return url } +// EndpointOrDefault is the endpoint for requests that need no token: +// VALAR_ENDPOINT, the active context's, or DefaultEndpoint. +func (cfg *CLIConfig) EndpointOrDefault() string { + if cfg.env.Endpoint != "" { + return cfg.env.Endpoint + } + if url := cfg.Endpoints[cfg.Contexts[cfg.ActiveContext].Endpoint].URL; url != "" { + return url + } + return DefaultEndpoint +} + func (cfg *CLIConfig) Project() string { if cfg.env.Project != "" { return cfg.env.Project diff --git a/skills/valar/SKILL.md b/skills/valar/SKILL.md index 8473a0a..4b41084 100644 --- a/skills/valar/SKILL.md +++ b/skills/valar/SKILL.md @@ -27,7 +27,7 @@ Set the credentials in the environment rather than running the interactive `vala These take precedence over `~/.valar/config` and `.valar.yml`. Check them with `valar whoami --json`, which also shows the token's binding, scopes and expiry. A token with only `read` and `deploy` builds and deploys but cannot change variables, domains or permissions. -For CI, the user creates a token bound to the project with `valar token create ci --project --scopes read,deploy` and stores it as the CI secret `VALAR_TOKEN`. The value is shown once. Leave creating and revoking tokens to the user. +For CI, the user creates a token bound to the project with `valar token create ci --project --scopes read,deploy` and stores it as the CI secret `VALAR_TOKEN`. The value is shown once. Where the installation trusts GitHub's identity tokens, a trust policy (`valar trust add`) lets a workflow with `permissions: id-token: write` deploy without a stored token. Leave creating and revoking tokens and trust policies to the user. ## Always use `--json`