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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 79 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<project>-<service>` domains.
Linked custom domains come first, then the service's own `<project>-<service>` 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]
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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
Expand Down
10 changes: 9 additions & 1 deletion api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion api/logstream.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion api/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
134 changes: 134 additions & 0 deletions api/trust.go
Original file line number Diff line number Diff line change
@@ -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
}
67 changes: 67 additions & 0 deletions api/trust_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
5 changes: 5 additions & 0 deletions api/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 := "-"
Expand Down
Loading