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
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ valar service list --json | jq -r '.[].name'
valar config init [--token token] [--project project] [--url url] [--name name] [--force]
```

Before storing a token, `config init` and `config endpoint set` (when the endpoint has a URL) ask the platform about it with `/users/info`: they refuse agent tokens, which are for MCP clients, and warn when the token expires within 14 days.

The CLI writes `~/.valar/config`, which holds tokens, readable only by you (mode 0600, in a 0700 directory). When it rewrites a configuration file that other users can read, it tightens the file to 0600 and says so on stderr.

#### Dump the current configuration as YAML

```bash
Expand Down Expand Up @@ -407,6 +411,52 @@ valar builds status [--exit] [buildid]
valar whoami
```

Prints the user, their projects and, on platforms that report it, what the token in use grants: its kind, binding, scopes, creation, expiry, last use and the token that created it.

### Tokens

These commands need a newer Valar platform; against an older one they fail with "the server has no token API".

A token created with `valar token create` acts as you. It is a child of the token that creates it: it expires no later than that token and is revoked with it. Only a token created in the console or with authctl, with full access and no project binding, can create tokens.

#### Create a token

```bash
valar token create [--project project] [--service service] [--scopes read,deploy] [--ttl 90d] 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:

```bash
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.

#### List tokens

```bash
valar token list [--project project]
```

Lists your tokens, including revoked and expired ones for 30 days. With `--project`, it lists every token bound to the project, whoever owns it, and needs permission to manage the project.

#### Revoke a token

```bash
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.

### Audit log

```bash
valar audit [--project project] [--limit n] [--before id]
```

Shows the active project's audit log, newest first: an attempt row before each change made through the API and a result row after it, with the token, client and source address, and per-minute counts of refused requests. It needs permission to manage the project and a newer Valar platform. A page holds `--limit` rows (100 by default, at most 500); when a page is full, the command for the next one is printed to stderr.

### Permissions

#### View permissions
Expand Down
67 changes: 67 additions & 0 deletions api/audit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package api

import (
"errors"
"net/http"
"net/url"
"strconv"
"time"
)

// ErrNoAuditAPI is returned when the server predates the audit log route.
var ErrNoAuditAPI = errors.New("the server has no audit log API; it needs a newer Valar platform")

// MaxAuditPage is the most rows the server returns in one page.
const MaxAuditPage = 500

// Audit row kinds: an attempt is written before a change and a result after
// it; a count sums a minute's refused requests.
const (
AuditAttempt = "attempt"
AuditResult = "result"
AuditCount = "count"
)

// AuditEvent is a row of a project's audit log.
type AuditEvent struct {
ID int64 `json:"id"`
At time.Time `json:"at"`
Kind string `json:"kind"`
AttemptID int64 `json:"attemptId,omitempty"`
Principal string `json:"principal"`
Owner string `json:"owner,omitempty"`
TokenID string `json:"tokenId,omitempty"`
Client string `json:"client,omitempty"`
SourceIP string `json:"sourceIp,omitempty"`
Service string `json:"service,omitempty"`
Operation string `json:"operation"`
Tool string `json:"tool,omitempty"`
Target string `json:"target,omitempty"`
Status int `json:"status,omitempty"`
Count int `json:"count"`
}

// ListAuditEvents returns a page of the project's audit log, newest first,
// with IDs below before if it is positive. A limit of 0 asks for the server's
// default page size.
func (client *Client) ListAuditEvents(project string, before int64, limit int) ([]AuditEvent, error) {
params := url.Values{}
if before > 0 {
params.Set("before", strconv.FormatInt(before, 10))
}
if limit > 0 {
params.Set("limit", strconv.Itoa(limit))
}
path := "/projects/" + project + "/audit"
if len(params) > 0 {
path += "?" + params.Encode()
}
var events []AuditEvent
if err := client.request(http.MethodGet, path, &events, nil); err != nil {
if unknownRoute(err) {
return nil, ErrNoAuditAPI
}
return nil, err
}
return events, nil
}
78 changes: 78 additions & 0 deletions api/audit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package api

import (
"errors"
"net/http"
"reflect"
"testing"
"time"
)

func TestListAuditEvents(t *testing.T) {
for _, tc := range []struct {
Name string
Before int64
Limit int
WantQuery string
}{
{"FirstPage", 0, 0, ""},
{"Limit", 0, 50, "limit=50"},
{"NextPage", 1201, 100, "before=1201&limit=100"},
} {
t.Run(tc.Name, func(t *testing.T) {
var query string
client, requests := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) {
query = r.URL.RawQuery
w.Write([]byte(`[{"id":1200,"at":"2026-11-21T10:00:00Z","kind":"result","attemptId":1199,"principal":"human::alice",` +
`"tokenId":"` + ciID + `","client":"valar-cli/4.9.0","sourceIp":"192.0.2.1","service":"web",` +
`"operation":"deploys.submit","target":"deployment=7","status":200,"count":0}]`))
})
events, err := client.ListAuditEvents("acme", tc.Before, tc.Limit)
if err != nil {
t.Fatalf("ListAuditEvents: %v", err)
}
if want := (recordedRequest{http.MethodGet, "/projects/acme/audit", ""}); (*requests)[0] != want {
t.Errorf("request %+v, want %+v", (*requests)[0], want)
}
if query != tc.WantQuery {
t.Errorf("query = %q, want %q", query, tc.WantQuery)
}
want := []AuditEvent{{
ID: 1200, At: time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC), Kind: AuditResult, AttemptID: 1199,
Principal: "human::alice", TokenID: ciID, Client: "valar-cli/4.9.0", SourceIP: "192.0.2.1", Service: "web",
Operation: "deploys.submit", Target: "deployment=7", Status: 200,
}}
if !reflect.DeepEqual(events, want) {
t.Errorf("events\n got %+v\nwant %+v", events, want)
}
})
}
}

func TestListAuditEvents_Errors(t *testing.T) {
for _, tc := range []struct {
Name string
Status int
Body string
WantOld bool
WantErr string
}{
{"UnknownRoute", http.StatusNotFound, "404 page not found\n", true, ErrNoAuditAPI.Error()},
{"Forbidden", http.StatusForbidden, `{"error":"forbidden"}`, false, "Forbidden: forbidden"},
{"Disabled", http.StatusServiceUnavailable, `{"error":"the audit log is disabled"}`, false, "Service Unavailable: the audit log is disabled"},
} {
t.Run(tc.Name, func(t *testing.T) {
client, _ := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tc.Status)
w.Write([]byte(tc.Body))
})
_, err := client.ListAuditEvents("acme", 0, 0)
if got := errors.Is(err, ErrNoAuditAPI); got != tc.WantOld {
t.Errorf("errors.Is(%v, ErrNoAuditAPI) = %v, want %v", err, got, tc.WantOld)
}
if err == nil || err.Error() != tc.WantErr {
t.Errorf("error = %v, want %q", err, tc.WantErr)
}
})
}
}
45 changes: 25 additions & 20 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -72,6 +73,18 @@ func (err Error) Unwrap() error {
return err.ServerError
}

// unknownRoute reports whether err is the router's answer to a route the
// server does not serve: a 404 or 405 in plain text, while API errors are JSON.
func unknownRoute(err error) bool {
var apiErr Error
if !errors.As(err, &apiErr) {
return false
}
var jsonErr JSONError
missing := apiErr.StatusCode == http.StatusNotFound || apiErr.StatusCode == http.StatusMethodNotAllowed
return missing && !errors.As(apiErr.ServerError, &jsonErr)
}

func parseErrorResponse(body []byte) error {
serverErr := JSONError{}
if err := json.Unmarshal(body, &serverErr); err != nil {
Expand Down Expand Up @@ -238,9 +251,7 @@ func (client *Client) SubmitBuild(project, service string, buildRequest *BuildRe

// AbortBuild aborts a scheduled or running build.
func (client *Client) AbortBuild(project, service, id string) error {
var (
path = fmt.Sprintf("/projects/%s/services/%s/builds/%s/abort", project, service, id)
)
path := fmt.Sprintf("/projects/%s/services/%s/builds/%s/abort", project, service, id)
var resp struct{}
if err := client.request("POST", path, &resp, nil); err != nil {
return err
Expand All @@ -256,9 +267,7 @@ func (client *Client) DeleteService(project, service string) error {

// Sets a service' status. A disabled service cannot receive any requests.
func (client *Client) ChangeServiceStatus(project, service string, disabled bool) error {
var (
path = fmt.Sprintf("/projects/%s/services/%s/status?disabled=%v", project, service, disabled)
)
path := fmt.Sprintf("/projects/%s/services/%s/status?disabled=%v", project, service, disabled)
if err := client.request("POST", path, nil, nil); err != nil {
return err
}
Expand Down Expand Up @@ -336,9 +345,7 @@ func (decoder *logEntryDecoder) finish(streamErr error) error {

// ShowBuildLogs retrieves a specific build task logs.
func (client *Client) ShowBuildLogs(project, service, id string, consumer func(LogEntry)) error {
var (
path = fmt.Sprintf("/projects/%s/services/%s/builds/%s/logs", project, service, id)
)
path := fmt.Sprintf("/projects/%s/services/%s/builds/%s/logs", project, service, id)
decoder := newLogEntryDecoder(consumer)
err := client.streamOnce(path, decoder)
return decoder.finish(err)
Expand Down Expand Up @@ -497,9 +504,7 @@ func (client *Client) AddDomain(project, domain string) (map[string]string, erro
}

func (client *Client) DeleteDomain(project, domain string) error {
var (
path = fmt.Sprintf("/projects/%s/domains/%s", project, domain)
)
path := fmt.Sprintf("/projects/%s/domains/%s", project, domain)
if err := client.request(http.MethodDelete, path, nil, nil); err != nil {
return err
}
Expand Down Expand Up @@ -710,16 +715,12 @@ func (client *Client) SetSchedule(project, service string, sched Schedule) error
}

func (client *Client) DeleteSchedule(project, service, schedule string) error {
var (
path = fmt.Sprintf("/projects/%s/services/%s/schedules/%s", project, service, schedule)
)
path := fmt.Sprintf("/projects/%s/services/%s/schedules/%s", project, service, schedule)
return client.request(http.MethodDelete, path, nil, nil)
}

func (client *Client) TriggerSchedule(project, service, schedule string) error {
var (
path = fmt.Sprintf("/projects/%s/services/%s/schedules/%s/trigger", project, service, schedule)
)
path := fmt.Sprintf("/projects/%s/services/%s/schedules/%s/trigger", project, service, schedule)
return client.request(http.MethodPost, path, nil, nil)
}

Expand Down Expand Up @@ -868,9 +869,13 @@ type Permission struct {
State string `json:"state"`
}

// UserInfo is the calling principal. Token is nil on servers that predate
// tokens with grants.
type UserInfo struct {
Name string `json:"name"`
Projects []string `json:"projects"`
Name string `json:"name"`
Projects []string `json:"projects"`
Principal string `json:"principal,omitempty"`
Token *Token `json:"token,omitempty"`
}

type Service struct {
Expand Down
11 changes: 2 additions & 9 deletions api/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,16 +69,9 @@ func envPath(project, service string) string {
return fmt.Sprintf("/projects/%s/services/%s/env", project, service)
}

// envError maps a route the server does not know to ErrNoEnvAPI. The router
// answers those in plain text, while API errors are JSON.
// envError maps a route the server does not know to ErrNoEnvAPI.
func envError(err error) error {
var apiErr Error
if !errors.As(err, &apiErr) {
return err
}
var jsonErr JSONError
missing := apiErr.StatusCode == http.StatusNotFound || apiErr.StatusCode == http.StatusMethodNotAllowed
if missing && !errors.As(apiErr.ServerError, &jsonErr) {
if unknownRoute(err) {
return ErrNoEnvAPI
}
return err
Expand Down
8 changes: 1 addition & 7 deletions api/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,7 @@ func settingsPath(project, service string) string {

// settingsError maps a route the server does not know to ErrNoSettingsAPI.
func settingsError(err error) error {
var apiErr Error
if !errors.As(err, &apiErr) {
return err
}
var jsonErr JSONError
missing := apiErr.StatusCode == http.StatusNotFound || apiErr.StatusCode == http.StatusMethodNotAllowed
if missing && !errors.As(apiErr.ServerError, &jsonErr) {
if unknownRoute(err) {
return ErrNoSettingsAPI
}
return err
Expand Down
Loading