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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ By default, Valar uses the default valarconfig file in `$HOME/.valar/config`. If
VALAR_TOKEN=... valar build push --wait
```

Tokens expire. Within 14 days of its token's expiry, a run prints one warning to stderr with the date and where to create a new token. A token that expired or was revoked fails with the server's reason.

### Machine-readable output

With `--json`, or `VALAR_OUTPUT=json`, every command prints its result as one JSON document on stdout. Lists are arrays of objects whose fields match the API's JSON. Logs (`service logs`, `build logs`, `build watch`, `batch logs`) are printed as one JSON object per line, progress goes to stderr, and an error is printed on stderr as:
Expand Down
6 changes: 2 additions & 4 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,13 @@ func (client *Client) request(method, path string, obj interface{}, post io.Read
return fmt.Errorf("submitting request: %w", err)
}
defer resp.Body.Close()
client.noteTokenExpiry(resp.Header)
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("fetching request: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return Error{
StatusCode: resp.StatusCode,
ServerError: parseErrorResponse(body),
}
return client.responseError(resp, body)
}
if obj != nil {
if err := json.Unmarshal(body, obj); err != nil {
Expand Down
6 changes: 2 additions & 4 deletions api/logstream.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,15 +120,13 @@ func (client *Client) streamOnce(path string, w io.Writer) error {
return fmt.Errorf("submitting request: %w", err)
}
defer resp.Body.Close()
client.noteTokenExpiry(resp.Header)
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("fetching response: %w", err)
}
return Error{
StatusCode: resp.StatusCode,
ServerError: parseErrorResponse(body),
}
return client.responseError(resp, body)
}
if contentType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")); err == nil && contentType == logStreamContentType {
return decodeFramedStream(resp.Body, w)
Expand Down
60 changes: 60 additions & 0 deletions api/token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package api

import (
"net/http"
"regexp"
"strings"
"time"
)

// TokenExpiresHeader carries the token's expiry as an RFC 3339 time. The
// platform sets it on responses to a token that expires within 14 days.
const TokenExpiresHeader = "Valar-Token-Expires"

// OnTokenExpiry, when set, is called for every response that carries
// TokenExpiresHeader.
var OnTokenExpiry func(endpoint string, expires time.Time)

// TokenRefusedError is a 401 whose challenge says the token expired or was
// revoked, such as "token 3f2a... expired at 2027-02-18T10:00:00Z".
type TokenRefusedError struct {
Reason string
Endpoint string
}

func (err TokenRefusedError) Error() string { return err.Reason }

var challengeDescription = regexp.MustCompile(`error_description="([^"]*)"`)

func (client *Client) noteTokenExpiry(header http.Header) {
value := header.Get(TokenExpiresHeader)
if value == "" || OnTokenExpiry == nil {
return
}
if expires, err := time.Parse(time.RFC3339, value); err == nil {
OnTokenExpiry(client.Endpoint, expires)
}
}

// responseError turns a non-2xx response into an Error.
func (client *Client) responseError(resp *http.Response, body []byte) error {
serverErr := parseErrorResponse(body)
if resp.StatusCode == http.StatusUnauthorized {
if reason := tokenRefusal(resp.Header); reason != "" {
serverErr = TokenRefusedError{Reason: reason, Endpoint: client.Endpoint}
}
}
return Error{StatusCode: resp.StatusCode, ServerError: serverErr}
}

// tokenRefusal returns a WWW-Authenticate reason saying the token expired or
// was revoked, or "".
func tokenRefusal(header http.Header) string {
for _, challenge := range header.Values("WWW-Authenticate") {
m := challengeDescription.FindStringSubmatch(challenge)
if m != nil && (strings.Contains(m[1], " expired at ") || strings.Contains(m[1], " was revoked at ")) {
return m[1]
}
}
return ""
}
123 changes: 123 additions & 0 deletions api/token_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package api

import (
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
)

type expiryCall struct {
Endpoint string
Expires time.Time
}

// recordExpiry captures OnTokenExpiry calls for one test.
func recordExpiry(t *testing.T) *[]expiryCall {
t.Helper()
var calls []expiryCall
prev := OnTokenExpiry
OnTokenExpiry = func(endpoint string, expires time.Time) {
calls = append(calls, expiryCall{endpoint, expires})
}
t.Cleanup(func() { OnTokenExpiry = prev })
return &calls
}

func newHeaderTestClient(t *testing.T, handler http.HandlerFunc) *Client {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
return &Client{Endpoint: srv.URL, http: &http.Client{}, stream: &http.Client{}}
}

func TestTokenExpiry_Reported(t *testing.T) {
expires := time.Date(2027, 2, 18, 10, 0, 0, 0, time.UTC)
for _, tc := range []struct {
Name string
Header string
Status int
Call func(*Client) error
Want bool
}{
{"Request", "2027-02-18T10:00:00Z", http.StatusOK, func(c *Client) error { _, err := c.UserInfo(); return err }, true},
{"FailedRequest", "2027-02-18T10:00:00Z", http.StatusNotFound, func(c *Client) error { _, err := c.UserInfo(); return err }, true},
{"Stream", "2027-02-18T10:00:00Z", http.StatusOK, func(c *Client) error { return c.StreamServiceLogs("p", "s", io.Discard, false, false, 0) }, true},
{"NoHeader", "", http.StatusOK, func(c *Client) error { _, err := c.UserInfo(); return err }, false},
{"Malformed", "next week", http.StatusOK, func(c *Client) error { _, err := c.UserInfo(); return err }, false},
} {
t.Run(tc.Name, func(t *testing.T) {
calls := recordExpiry(t)
client := newHeaderTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if tc.Header != "" {
w.Header().Set(TokenExpiresHeader, tc.Header)
}
w.WriteHeader(tc.Status)
w.Write([]byte(`{"error":"not found"}`))
})
tc.Call(client)
switch {
case !tc.Want && len(*calls) != 0:
t.Errorf("reported %v, want nothing", *calls)
case tc.Want && (len(*calls) != 1 || (*calls)[0] != expiryCall{client.Endpoint, expires}):
t.Errorf("reported %v, want one call with %s", *calls, expires)
}
})
}
}

func TestTokenRefused(t *testing.T) {
const (
expired = "token 3f2a... expired at 2027-02-18T10:00:00Z"
revoked = "token 3f2a... was revoked at 2026-11-21T10:00:00Z"
)
challenge := func(reason string) string {
return `Bearer error="invalid_token", error_description="` + reason + `"`
}
for _, tc := range []struct {
Name string
Status int
Challenge string
Body string
WantErr string
WantRefused bool
}{
{"Expired", http.StatusUnauthorized, challenge(expired), `{"error":"token 3f2a… expired at 2027-02-18T10:00:00Z"}`, "Unauthorized: " + expired, true},
{"Revoked", http.StatusUnauthorized, challenge(revoked), `{"error":"token 3f2a… was revoked at 2026-11-21T10:00:00Z"}`, "Unauthorized: " + revoked, true},
{"ExpiredWithoutJSONBody", http.StatusUnauthorized, challenge(expired), "Unauthorized\n", "Unauthorized: " + expired, true},
{"Unknown", http.StatusUnauthorized, challenge("unknown token"), `{"error":"unknown token"}`, "Unauthorized: unknown token", false},
{"NoChallenge", http.StatusUnauthorized, "", `{"error":"invalid credentials"}`, "Unauthorized: invalid credentials", false},
{"NotUnauthorized", http.StatusForbidden, challenge(expired), `{"error":"forbidden"}`, "Forbidden: forbidden", false},
} {
t.Run(tc.Name, func(t *testing.T) {
client := newHeaderTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if tc.Challenge != "" {
w.Header().Set("WWW-Authenticate", tc.Challenge)
}
w.WriteHeader(tc.Status)
w.Write([]byte(tc.Body))
})
for name, err := range map[string]error{
"request": func() error { _, err := client.UserInfo(); return err }(),
"stream": client.StreamServiceLogs("p", "s", io.Discard, false, false, 0),
} {
var apiErr Error
if !errors.As(err, &apiErr) || apiErr.StatusCode != tc.Status {
t.Fatalf("%s: got %v, want a %d API error", name, err, tc.Status)
}
if err.Error() != tc.WantErr {
t.Errorf("%s: error = %q, want %q", name, err.Error(), tc.WantErr)
}
var refused TokenRefusedError
if errors.As(err, &refused) != tc.WantRefused {
t.Errorf("%s: refused = %v, want %v", name, !tc.WantRefused, tc.WantRefused)
}
if tc.WantRefused && refused.Endpoint != client.Endpoint {
t.Errorf("%s: endpoint = %q, want %q", name, refused.Endpoint, client.Endpoint)
}
}
})
}
}
9 changes: 7 additions & 2 deletions cmd/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,11 @@ func reportError(w io.Writer, err error, fallback errorKind, printed bool) int {
kind := classify(err, fallback)
var cliErr *cliError
silent := printed || errors.As(err, &cliErr) && cliErr.silent
message := err.Error()
var refused api.TokenRefusedError
if errors.As(err, &refused) {
message += "\n" + renewHint(refused.Endpoint)
}
switch {
case outputJSON:
var doc struct {
Expand All @@ -134,12 +139,12 @@ func reportError(w io.Writer, err error, fallback errorKind, printed bool) int {
} `json:"error"`
}
doc.Error.Kind = kind.String()
doc.Error.Message = err.Error()
doc.Error.Message = message
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.Encode(doc)
case !silent:
fmt.Fprintln(w, err)
fmt.Fprintln(w, message)
}
return int(kind)
}
Expand Down
3 changes: 3 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package cmd
import (
"fmt"
"os"
"time"

"github.com/spf13/cobra"
"github.com/valar/cli/api"
"github.com/valar/cli/config"
)

Expand Down Expand Up @@ -44,6 +46,7 @@ func init() {
config.Abort = func(msg string) {
exitWithError(newError(kindInvalid, "%s", msg), kindInvalid, false)
}
api.OnTokenExpiry = (&expiryNotice{w: os.Stderr, now: time.Now}).observe
// Configure projects.go
initProjectsCmd()
// Configure deployments.go
Expand Down
65 changes: 65 additions & 0 deletions cmd/token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package cmd

import (
"fmt"
"io"
"net/url"
"sync"
"time"

"github.com/valar/cli/config"
)

// tokenExpiryWarning matches when the platform starts sending api.TokenExpiresHeader.
const tokenExpiryWarning = 14 * 24 * time.Hour

// expiryNotice warns about the token's expiry once per invocation.
type expiryNotice struct {
w io.Writer
now func() time.Time
once sync.Once
}

func (n *expiryNotice) observe(endpoint string, expires time.Time) {
left := expires.Sub(n.now())
if left > tokenExpiryWarning {
return
}
n.once.Do(func() {
fmt.Fprintf(n.w, "Warning: your Valar token expires %s, at %s. %s\n",
untilExpiry(left), expires.UTC().Format("2006-01-02 15:04 MST"), renewHint(endpoint))
})
}

// untilExpiry rounds d to days, hours or minutes.
func untilExpiry(d time.Duration) string {
unit, size := "minute", time.Minute
switch {
case d < time.Minute:
return "within a minute"
case d >= 48*time.Hour:
unit, size = "day", 24*time.Hour
case d >= 2*time.Hour:
unit, size = "hour", time.Hour
}
n := int((d + size/2) / size)
if n != 1 {
unit += "s"
}
return fmt.Sprintf("in %d %s", n, unit)
}

// renewHint says where to create a replacement token and how to use it.
func renewHint(endpoint string) string {
where := "in the Valar console"
if consoleKnown(endpoint) {
where = "at https://console.valar.dev/api-tokens/new"
}
return "Create a new token " + where + " and use it with 'valar config endpoint set <endpoint> --token <token>' or VALAR_TOKEN."
}

func consoleKnown(endpoint string) bool {
u, err := url.Parse(endpoint)
def, _ := url.Parse(config.DefaultEndpoint)
return err == nil && u.Host == def.Host
}
Loading