diff --git a/README.md b/README.md index 1a92b79..d4851de 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/api/client.go b/api/client.go index 5ab6aab..2bf90f3 100644 --- a/api/client.go +++ b/api/client.go @@ -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 { diff --git a/api/logstream.go b/api/logstream.go index 766dcbe..63899e6 100644 --- a/api/logstream.go +++ b/api/logstream.go @@ -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) diff --git a/api/token.go b/api/token.go new file mode 100644 index 0000000..5df69f4 --- /dev/null +++ b/api/token.go @@ -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 "" +} diff --git a/api/token_test.go b/api/token_test.go new file mode 100644 index 0000000..d2daee0 --- /dev/null +++ b/api/token_test.go @@ -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) + } + } + }) + } +} diff --git a/cmd/output.go b/cmd/output.go index 1539673..6ae0040 100644 --- a/cmd/output.go +++ b/cmd/output.go @@ -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 { @@ -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) } diff --git a/cmd/root.go b/cmd/root.go index 0ef3a15..bb541a0 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -3,8 +3,10 @@ package cmd import ( "fmt" "os" + "time" "github.com/spf13/cobra" + "github.com/valar/cli/api" "github.com/valar/cli/config" ) @@ -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 diff --git a/cmd/token.go b/cmd/token.go new file mode 100644 index 0000000..fa702f3 --- /dev/null +++ b/cmd/token.go @@ -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 --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 +} diff --git a/cmd/token_test.go b/cmd/token_test.go new file mode 100644 index 0000000..e86eda0 --- /dev/null +++ b/cmd/token_test.go @@ -0,0 +1,134 @@ +package cmd + +import ( + "bytes" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/valar/cli/api" +) + +const ( + valarHint = "Create a new token at https://console.valar.dev/api-tokens/new and use it with 'valar config endpoint set --token ' or VALAR_TOKEN." + otherHint = "Create a new token in the Valar console and use it with 'valar config endpoint set --token ' or VALAR_TOKEN." + valarAPI = "https://api.valar.dev/v2" + hostedAPI = "https://valar.example.com/v2" + day = 24 * time.Hour +) + +func TestExpiryNotice(t *testing.T) { + now := time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC) + for _, tc := range []struct { + Name string + Endpoint string + Expires []time.Time + Want string + }{ + {"WithinWindow", valarAPI, []time.Time{now.Add(6 * day)}, "Warning: your Valar token expires in 6 days, at 2026-11-27 10:00 UTC. " + valarHint + "\n"}, + {"OncePerInvocation", valarAPI, []time.Time{now.Add(3 * time.Hour), now.Add(3 * time.Hour), now.Add(time.Hour)}, "Warning: your Valar token expires in 3 hours, at 2026-11-21 13:00 UTC. " + valarHint + "\n"}, + {"BeyondWindow", valarAPI, []time.Time{now.Add(15 * day)}, ""}, + {"BeyondThenWithin", valarAPI, []time.Time{now.Add(15 * day), now.Add(14 * day)}, "Warning: your Valar token expires in 14 days, at 2026-12-05 10:00 UTC. " + valarHint + "\n"}, + {"OtherEndpoint", hostedAPI, []time.Time{now.Add(13 * day)}, "Warning: your Valar token expires in 13 days, at 2026-12-04 10:00 UTC. " + otherHint + "\n"}, + } { + t.Run(tc.Name, func(t *testing.T) { + var out bytes.Buffer + notice := &expiryNotice{w: &out, now: func() time.Time { return now }} + for _, expires := range tc.Expires { + notice.observe(tc.Endpoint, expires) + } + if out.String() != tc.Want { + t.Errorf("got %q, want %q", out.String(), tc.Want) + } + }) + } +} + +func TestUntilExpiry(t *testing.T) { + for _, tc := range []struct { + Left time.Duration + Want string + }{ + {5*day - time.Second, "in 5 days"}, + {2 * day, "in 2 days"}, + {47 * time.Hour, "in 47 hours"}, + {2 * time.Hour, "in 2 hours"}, + {90 * time.Minute, "in 90 minutes"}, + {time.Minute, "in 1 minute"}, + {10 * time.Second, "within a minute"}, + {-time.Minute, "within a minute"}, + } { + t.Run(tc.Want, func(t *testing.T) { + if got := untilExpiry(tc.Left); got != tc.Want { + t.Errorf("untilExpiry(%s) = %q, want %q", tc.Left, got, tc.Want) + } + }) + } +} + +func TestExpiryNotice_OnceAcrossRequests(t *testing.T) { + const token = "valar_ut_0123456789abcdef" + expires := time.Now().Add(3 * day).UTC().Truncate(time.Second) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(api.TokenExpiresHeader, expires.Format(time.RFC3339)) + if r.URL.Path == "/" { + w.Write([]byte(`{"version":"v2"}`)) + return + } + w.Write([]byte(`{"name":"ada"}`)) + })) + t.Cleanup(srv.Close) + var out bytes.Buffer + prev := api.OnTokenExpiry + api.OnTokenExpiry = (&expiryNotice{w: &out, now: time.Now}).observe + t.Cleanup(func() { api.OnTokenExpiry = prev }) + + client, err := api.NewClient(srv.URL, token) + if err != nil { + t.Fatalf("new client: %v", err) + } + for range 3 { + if _, err := client.UserInfo(); err != nil { + t.Fatalf("UserInfo: %v", err) + } + } + if n := strings.Count(out.String(), "Warning:"); n != 1 { + t.Errorf("warned %d times, want once: %q", n, out.String()) + } + if !strings.Contains(out.String(), expires.Format("2006-01-02 15:04 MST")) { + t.Errorf("warning %q lacks the expiry", out.String()) + } + if strings.Contains(out.String(), token) { + t.Errorf("warning %q prints the token", out.String()) + } +} + +func TestReportError_TokenRefused(t *testing.T) { + const reason = "token 3f2a... expired at 2027-02-18T10:00:00Z" + refused := fmt.Errorf("listing services: %w", api.Error{ + StatusCode: http.StatusUnauthorized, + ServerError: api.TokenRefusedError{Reason: reason, Endpoint: valarAPI}, + }) + for _, tc := range []struct { + Name string + JSON bool + Want string + }{ + {"Human", false, "listing services: Unauthorized: " + reason + "\n" + valarHint + "\n"}, + {"JSON", true, `{"error":{"kind":"notAllowed","message":"listing services: Unauthorized: ` + reason + `\n` + valarHint + `"}}` + "\n"}, + } { + t.Run(tc.Name, func(t *testing.T) { + setJSON(t, tc.JSON) + var stderr bytes.Buffer + if code := reportError(&stderr, refused, kindFailed, false); code != int(kindNotAllowed) { + t.Errorf("code %d, want %d", code, kindNotAllowed) + } + if stderr.String() != tc.Want { + t.Errorf("stderr %q, want %q", stderr.String(), tc.Want) + } + }) + } +}