diff --git a/README.md b/README.md index 5c6d59a..5951bb6 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/api/audit.go b/api/audit.go new file mode 100644 index 0000000..7d67cc6 --- /dev/null +++ b/api/audit.go @@ -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 +} diff --git a/api/audit_test.go b/api/audit_test.go new file mode 100644 index 0000000..695af25 --- /dev/null +++ b/api/audit_test.go @@ -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) + } + }) + } +} diff --git a/api/client.go b/api/client.go index afcda98..19f59ee 100644 --- a/api/client.go +++ b/api/client.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -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 { @@ -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 @@ -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 } @@ -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) @@ -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 } @@ -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) } @@ -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 { diff --git a/api/env.go b/api/env.go index cb23ee4..c33556d 100644 --- a/api/env.go +++ b/api/env.go @@ -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 diff --git a/api/settings.go b/api/settings.go index bf2e283..055660b 100644 --- a/api/settings.go +++ b/api/settings.go @@ -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 diff --git a/api/token.go b/api/token.go index 5df69f4..1fd122e 100644 --- a/api/token.go +++ b/api/token.go @@ -1,6 +1,9 @@ package api import ( + "bytes" + "encoding/json" + "errors" "net/http" "regexp" "strings" @@ -58,3 +61,91 @@ func tokenRefusal(header http.Header) string { } return "" } + +// ErrNoTokenAPI is returned when the server predates the token routes. +var ErrNoTokenAPI = errors.New("the server has no token API; it needs a newer Valar platform") + +// Token is a token's grant, never its value. Owner is set only in a project's +// token list. Times the server leaves out are zero. +type Token struct { + ID string `json:"id,omitempty"` + Kind string `json:"kind"` + Name string `json:"name,omitempty"` + Owner string `json:"owner,omitempty"` + Project string `json:"project,omitempty"` + Service string `json:"service,omitempty"` + Scopes []string `json:"scopes"` + Consumer string `json:"consumer,omitempty"` + Parent string `json:"parent,omitempty"` + CreatedAt time.Time `json:"createdAt,omitzero"` + ExpiresAt time.Time `json:"expiresAt,omitzero"` + LastUsed time.Time `json:"lastUsed,omitzero"` + RevokedAt time.Time `json:"revokedAt,omitzero"` +} + +// MintedToken is a new token with its value, which the server returns only once. +type MintedToken struct { + Token + Value string `json:"value"` +} + +// TokenRequest mints a token. TTL is a Go duration; empty means the server's default. +type TokenRequest struct { + Name string `json:"name"` + Project string `json:"project,omitempty"` + Service string `json:"service,omitempty"` + Scopes []string `json:"scopes,omitempty"` + TTL string `json:"ttl,omitempty"` +} + +// tokensPath is the caller's tokens, or with project set the project's. +func tokensPath(project string) string { + if project == "" { + return "/tokens" + } + return "/projects/" + project + "/tokens" +} + +func tokenError(err error) error { + if unknownRoute(err) { + return ErrNoTokenAPI + } + return err +} + +// CreateToken mints a child of the calling token, which must have been created +// in the console or with authctl. +func (client *Client) CreateToken(req TokenRequest) (*MintedToken, error) { + payload, err := json.Marshal(req) + if err != nil { + return nil, err + } + var token MintedToken + if err := client.request(http.MethodPost, "/tokens", &token, bytes.NewReader(payload)); err != nil { + return nil, tokenError(err) + } + return &token, nil +} + +// ListTokens returns the caller's tokens, or with project set the tokens bound +// to that project, revoked and expired ones included. +func (client *Client) ListTokens(project string) ([]Token, error) { + var tokens []Token + if err := client.request(http.MethodGet, tokensPath(project), &tokens, nil); err != nil { + return nil, tokenError(err) + } + return tokens, nil +} + +// RevokeToken revokes a token and the tokens it created, from the caller's +// tokens or with project set from the project's, and returns how many tokens +// it revoked. +func (client *Client) RevokeToken(project, id string) (int, error) { + var resp struct { + Revoked int `json:"revoked"` + } + if err := client.request(http.MethodDelete, tokensPath(project)+"/"+id, &resp, nil); err != nil { + return 0, tokenError(err) + } + return resp.Revoked, nil +} diff --git a/api/token_test.go b/api/token_test.go index 695f2ed..d74b8a6 100644 --- a/api/token_test.go +++ b/api/token_test.go @@ -5,6 +5,7 @@ import ( "io" "net/http" "net/http/httptest" + "reflect" "testing" "time" ) @@ -121,3 +122,145 @@ func TestTokenRefused(t *testing.T) { }) } } + +const ( + rootID = "0123456789abcdef0123456789abcdef" + ciID = "fedcba9876543210fedcba9876543210" +) + +func TestTokenRequests(t *testing.T) { + created := time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC) + expires := created.Add(2160 * time.Hour) + ci := `{"id":"` + ciID + `","kind":"user","name":"ci","project":"acme","scopes":["deploy","read"],"parent":"` + rootID + + `","createdAt":"2026-11-21T10:00:00Z","expiresAt":"2027-02-19T10:00:00Z"` + client, requests := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch r.Method + " " + r.URL.Path { + case "POST /tokens": + w.WriteHeader(http.StatusCreated) + w.Write([]byte(ci + `,"value":"valar_ut_secret"}`)) + case "GET /tokens": + w.Write([]byte(`[` + ci + `}]`)) + case "GET /projects/acme/tokens": + w.Write([]byte(`[` + ci + `,"owner":"alice"}]`)) + case "DELETE /tokens/" + ciID, "DELETE /projects/acme/tokens/" + ciID: + w.Write([]byte(`{"revoked":2}`)) + default: + http.NotFound(w, r) + } + }) + want := Token{ + ID: ciID, Kind: "user", Name: "ci", Project: "acme", Scopes: []string{"deploy", "read"}, Parent: rootID, + CreatedAt: created, ExpiresAt: expires, + } + + minted, err := client.CreateToken(TokenRequest{Name: "ci", Project: "acme", Scopes: []string{"read", "deploy"}, TTL: "2160h"}) + if err != nil { + t.Fatalf("CreateToken: %v", err) + } + if !reflect.DeepEqual(*minted, MintedToken{Token: want, Value: "valar_ut_secret"}) { + t.Errorf("minted %+v", *minted) + } + own, err := client.ListTokens("") + if err != nil || len(own) != 1 || !reflect.DeepEqual(own[0], want) { + t.Errorf("ListTokens(\"\") = %+v, %v", own, err) + } + project, err := client.ListTokens("acme") + if err != nil || len(project) != 1 || project[0].Owner != "alice" { + t.Errorf("ListTokens(acme) = %+v, %v", project, err) + } + for _, p := range []string{"", "acme"} { + if n, err := client.RevokeToken(p, ciID); err != nil || n != 2 { + t.Errorf("RevokeToken(%q) = %d, %v", p, n, err) + } + } + + wantRequests := []recordedRequest{ + {http.MethodPost, "/tokens", `{"name":"ci","project":"acme","scopes":["read","deploy"],"ttl":"2160h"}`}, + {http.MethodGet, "/tokens", ""}, + {http.MethodGet, "/projects/acme/tokens", ""}, + {http.MethodDelete, "/tokens/" + ciID, ""}, + {http.MethodDelete, "/projects/acme/tokens/" + ciID, ""}, + } + if !reflect.DeepEqual(*requests, wantRequests) { + t.Errorf("requests\n got %+v\nwant %+v", *requests, wantRequests) + } +} + +func TestCreateToken_OmitsUnsetFields(t *testing.T) { + client, requests := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"kind":"user","scopes":["all"],"value":"v"}`)) + }) + if _, err := client.CreateToken(TokenRequest{Name: "laptop"}); err != nil { + t.Fatal(err) + } + if got, want := (*requests)[0].Body, `{"name":"laptop"}`; got != want { + t.Errorf("body = %s, want %s", got, want) + } +} + +// The router answers unknown routes in plain text; the token routes answer in JSON. +func TestTokenRoutes_Errors(t *testing.T) { + calls := map[string]func(*Client) error{ + "create": func(c *Client) error { _, err := c.CreateToken(TokenRequest{Name: "ci"}); return err }, + "list": func(c *Client) error { _, err := c.ListTokens(""); return err }, + "revoke": func(c *Client) error { _, err := c.RevokeToken("acme", ciID); return err }, + } + for _, tc := range []struct { + Name string + Status int + Body string + WantOld bool + WantErr string + }{ + {"UnknownRoute", http.StatusNotFound, "404 page not found\n", true, ErrNoTokenAPI.Error()}, + {"UnknownMethod", http.StatusMethodNotAllowed, "", true, ErrNoTokenAPI.Error()}, + {"NoSuchToken", http.StatusNotFound, `{"error":"token not found"}`, false, "Not Found: token not found"}, + { + "ChildMints", http.StatusForbidden, `{"error":"only tokens minted in the console or with authctl can mint tokens"}`, false, + "Forbidden: only tokens minted in the console or with authctl can mint tokens", + }, + } { + 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)) + }) + for name, call := range calls { + err := call(client) + if got := errors.Is(err, ErrNoTokenAPI); got != tc.WantOld { + t.Errorf("%s: errors.Is(%v, ErrNoTokenAPI) = %v, want %v", name, err, got, tc.WantOld) + } + if err == nil || err.Error() != tc.WantErr { + t.Errorf("%s: error = %v, want %q", name, err, tc.WantErr) + } + } + }) + } +} + +func TestUserInfo_Token(t *testing.T) { + for _, tc := range []struct { + Name string + Body string + Want *Token + }{ + {"Grant", `{"name":"alice","projects":["acme"],"principal":"human::alice","token":{"id":"` + ciID + + `","kind":"user","name":"ci","project":"acme","scopes":["read"],"parent":"` + rootID + + `","createdAt":"2026-11-21T10:00:00Z","lastUsed":"2026-11-21T11:00:00Z"}}`, &Token{ + ID: ciID, Kind: "user", Name: "ci", Project: "acme", Scopes: []string{"read"}, Parent: rootID, + CreatedAt: time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC), LastUsed: time.Date(2026, 11, 21, 11, 0, 0, 0, time.UTC), + }}, + {"OlderServer", `{"name":"alice","projects":["acme"]}`, nil}, + } { + t.Run(tc.Name, func(t *testing.T) { + client, _ := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(tc.Body)) }) + info, err := client.UserInfo() + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(info.Token, tc.Want) { + t.Errorf("token = %+v, want %+v", info.Token, tc.Want) + } + }) + } +} diff --git a/cmd/audit.go b/cmd/audit.go new file mode 100644 index 0000000..6b8f0fe --- /dev/null +++ b/cmd/audit.go @@ -0,0 +1,116 @@ +package cmd + +import ( + "fmt" + "io" + "os" + "strconv" + + "github.com/juju/ansiterm" + "github.com/spf13/cobra" + "github.com/valar/cli/api" + "github.com/valar/cli/config" +) + +const defaultAuditLimit = 100 + +var ( + auditProject string + auditLimit int + auditBefore int64 +) + +var auditCmd = &cobra.Command{ + Use: "audit [--project p] [--limit n] [--before id]", + Short: "Show a project's audit log, newest first.", + Long: `Show a project's audit log, newest first. + +The log lists the changes made to the project through the API, each with the +token, client and source address that made it: an attempt row before the +change and a result row after it. Count rows sum a minute's refused requests +and requests by legacy project tokens. + +It reads the active project unless --project names another, and needs +permission to manage the project. A page holds --limit rows, at most 500; +--before continues below the last ID of the previous page. This needs a newer +Valar platform.`, + Args: cobra.NoArgs, + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + project := auditProject + if project == "" { + cfg, err := config.NewServiceConfigWithFallback(functionConfiguration, nil, globalConfiguration) + if err != nil { + return err + } + project = cfg.Project() + } + client, err := globalConfiguration.APIClient() + if err != nil { + return err + } + return listAudit(client, project, auditBefore, auditLimit, stdout, os.Stderr) + }), +} + +// listAudit writes a page of the project's audit log to w and, when the page +// is full, the command for the next page to progress. +func listAudit(client *api.Client, project string, before int64, limit int, w, progress io.Writer) error { + if project == "" { + return newError(kindInvalid, "no project: pass --project, set VALAR_PROJECT or run in a folder with %s", functionConfiguration) + } + if err := api.VerifyProjectName(project); err != nil { + return withKind(kindInvalid, err) + } + if limit < 1 || limit > api.MaxAuditPage { + return newError(kindInvalid, "--limit must be between 1 and %d", api.MaxAuditPage) + } + if before < 0 { + return newError(kindInvalid, "--before must be an event ID") + } + events, err := client.ListAuditEvents(project, before, limit) + if err != nil { + return err + } + return emit(w, events, func(w io.Writer) error { + if err := printAudit(w, events); err != nil { + return err + } + if len(events) == limit { + next := fmt.Sprintf("valar audit --project %s --before %d", project, events[len(events)-1].ID) + if limit != defaultAuditLimit { + next += " --limit " + strconv.Itoa(limit) + } + fmt.Fprintf(progress, "Older rows: %s\n", next) + } + return nil + }) +} + +func printAudit(w io.Writer, events []api.AuditEvent) error { + tw := ansiterm.NewTabWriter(w, 6, 0, 1, ' ', 0) + fmt.Fprintln(tw, "ID\tTIME\tKIND\tPRINCIPAL\tTOKEN\tOPERATION\tSERVICE\tTARGET\tSTATUS\tSOURCE\tCLIENT") + for _, e := range events { + kind := e.Kind + if e.Kind == api.AuditCount { + kind = fmt.Sprintf("count (%d)", e.Count) + } + token := e.TokenID + if tokenIDPattern.MatchString(token) { + token = token[:8] + } + status := "-" + if e.Status != 0 { + status = strconv.Itoa(e.Status) + } + fmt.Fprintf(tw, "%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", e.ID, e.At.Local().Format("2006-01-02 15:04:05"), kind, + e.Principal, orDash(token), e.Operation, orDash(e.Service), orDash(e.Target), status, orDash(e.SourceIP), orDash(e.Client)) + } + return tw.Flush() +} + +func initAuditCmd() { + auditCmd.Flags().StringVar(&auditProject, "project", "", "Project to read (default the active project)") + auditCmd.Flags().IntVar(&auditLimit, "limit", defaultAuditLimit, "Rows per page, at most 500") + auditCmd.Flags().Int64Var(&auditBefore, "before", 0, "Show only rows with smaller IDs, to continue below the previous page") + rootCmd.AddCommand(auditCmd) +} diff --git a/cmd/audit_test.go b/cmd/audit_test.go new file mode 100644 index 0000000..c1b36e8 --- /dev/null +++ b/cmd/audit_test.go @@ -0,0 +1,109 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + + "github.com/valar/cli/api" +) + +const auditPage = `[{"id":1201,"at":"2026-11-21T10:00:01Z","kind":"result","attemptId":1200,"principal":"human::alice","tokenId":"` + ciTokenID + + `","client":"valar-cli/4.9.0","sourceIp":"192.0.2.1","service":"web","operation":"deploys.submit","target":"deployment=7","status":200,"count":0},` + + `{"id":1200,"at":"2026-11-21T10:00:00Z","kind":"attempt","principal":"human::alice","tokenId":"legacy-project","operation":"tokens.create","count":0},` + + `{"id":1190,"at":"2026-11-21T09:59:00Z","kind":"count","principal":"service::acme","operation":"env.patch","status":403,"count":3}]` + +func TestListAudit(t *testing.T) { + for _, tc := range []struct { + Name string + Limit int + WantHint string + }{ + {"FullPage", 3, "Older rows: valar audit --project acme --before 1190 --limit 3\n"}, + {"LastPage", 100, ""}, + } { + t.Run(tc.Name, func(t *testing.T) { + setJSON(t, false) + client, _ := newFakeAPI(t, map[string]string{"GET /projects/acme/audit": auditPage}) + var out, progress bytes.Buffer + if err := listAudit(client, "acme", 0, tc.Limit, &out, &progress); err != nil { + t.Fatalf("listAudit: %v", err) + } + got := lines(out.String()) + want := []string{ + "ID TIME KIND PRINCIPAL TOKEN OPERATION SERVICE TARGET STATUS SOURCE CLIENT", + "1201