From 3d4d994c6e4c49db3e510efdde218e8adc3f56d3 Mon Sep 17 00:00:00 2001 From: jerryfane Date: Tue, 10 Nov 2026 15:40:18 +0100 Subject: [PATCH 1/2] OAuth failures show the provider's description to the owner; Show value flags invisible characters (144) Google answers invalid_client both for an unknown client and a wrong secret and tells them apart only in error_description, which the keyring dropped. It is now kept apart from the error text: plain ASCII, at most 160 bytes, and dropped if it echoes the refresh token, secret or client ID. It shows in the owner's failing status on the key page, never in agents' 503 bodies or the audit. Show value warns when a single-line value holds a non-ASCII (often invisible) character, naming its code point and position, or is wrapped in quotes. --- internal/dashboard/pages.go | 2 +- internal/dashboard/reveal.go | 26 +++++++++++++++- internal/dashboard/reveal_test.go | 21 +++++++++++++ internal/server/oauth2.go | 52 ++++++++++++++++++++++++++++--- internal/server/oauth2_test.go | 28 +++++++++++++++++ 5 files changed, 122 insertions(+), 7 deletions(-) diff --git a/internal/dashboard/pages.go b/internal/dashboard/pages.go index 775cb4f..9a2a443 100644 --- a/internal/dashboard/pages.go +++ b/internal/dashboard/pages.go @@ -238,7 +238,7 @@ Sign in with Apple: {"service":"NAME","auth":"sign-in-with-apple-sign","si

Shown because you asked. Copy what you need and leave this page; it is not kept, and the audit log records that it was shown.

{{range .Values}}
{{end}} +{{.Value}}{{else}}{{end}}{{with .Warning}}

This value {{.}}.

{{end}}
{{end}}
{{template "bottom"}}{{end}} diff --git a/internal/dashboard/reveal.go b/internal/dashboard/reveal.go index bd096d8..125ab6d 100644 --- a/internal/dashboard/reveal.go +++ b/internal/dashboard/reveal.go @@ -2,7 +2,9 @@ package dashboard import ( "encoding/base64" + "fmt" "net/http" + "strings" "github.com/gitmoot/keyring/internal/store" ) @@ -19,6 +21,28 @@ type revealedValue struct { // normalizes line endings and drops a leading newline. Exact string Multiline bool + // Warning names what a copy-paste may have added: characters that do + // not show, or quotes around the value. Never the characters' values. + Warning string +} + +// valueWarning describes invisible or wrapping characters in a single-line +// value (file values such as PEM keys are expected to be multi-line). +func valueWarning(v string) string { + if strings.ContainsAny(v, "\n\r") { + return "" + } + n := 0 + for _, r := range v { + n++ + if r > 0x7e || (r < 0x20 && r != '\t') { + return fmt.Sprintf("contains a character that is not plain ASCII (U+%04X at character %d), often an invisible one from copying; paste the value again", r, n) + } + } + if len(v) >= 2 && (v[0] == '"' && v[len(v)-1] == '"' || v[0] == '\'' && v[len(v)-1] == '\'') { + return "starts and ends with quotes; if the provider's value has none, replace it without them" + } + return "" } func (b *Backend) revealKey(w http.ResponseWriter, r *http.Request, sid string) { @@ -49,7 +73,7 @@ func (b *Backend) revealKey(w http.ResponseWriter, r *http.Request, sid string) label = part } values = append(values, revealedValue{ID: "value-" + string(rune('a'+i)), Label: label, Value: v, Exact: base64.StdEncoding.EncodeToString([]byte(v)), - Multiline: len(v) > 120 || containsNewline(v)}) + Multiline: len(v) > 120 || containsNewline(v), Warning: valueWarning(v)}) shown = append(shown, full) } if len(values) == 0 { diff --git a/internal/dashboard/reveal_test.go b/internal/dashboard/reveal_test.go index c186e6d..d52ad98 100644 --- a/internal/dashboard/reveal_test.go +++ b/internal/dashboard/reveal_test.go @@ -100,3 +100,24 @@ func TestShowPartialKeyAndExactCopy(t *testing.T) { t.Fatal("Copy does not carry the exact value") } } + +// #144: Show value flags what a copy-paste may have added to a single-line +// value: an invisible character, or quotes around it. +func TestShowValueFlagsInvisibleCharactersAndQuotes(t *testing.T) { + e := newEnv(t) + for name, c := range map[string]struct{ value, want string }{ + "ZW_KEY": {"GOCSPX-abc\u200bdef", "U+200B at character 11"}, + "QUOTE_KEY": {`"GOCSPX-abcdef"`, "starts and ends with quotes"}, + "OK_KEY": {"GOCSPX-abcdef", ""}, + } { + if err := store.Set(e.backend.StorePath, name, c.value); err != nil { + t.Fatal(err) + } + keys, _ := store.Load(e.backend.StorePath) + e.proxy.Swap(e.proxy.Config(), keys) + body := html.UnescapeString(e.request("POST", "/keys/"+name+"/reveal", url.Values{"password": {password}}).Body.String()) + if c.want == "" && strings.Contains(body, "This value ") || c.want != "" && !strings.Contains(body, c.want) { + t.Errorf("%s: warning wrong", name) + } + } +} diff --git a/internal/server/oauth2.go b/internal/server/oauth2.go index 232cc73..62ce862 100644 --- a/internal/server/oauth2.go +++ b/internal/server/oauth2.go @@ -37,10 +37,12 @@ const ( var errOAuthRejected = errors.New("refresh token or client rejected") // oauthError is a failed refresh. Its text is safe to show and log: it never -// holds a token, a secret or the provider's free-text description. +// holds a token, a secret or the provider's free-text description. The +// description is kept apart, checked, for the owner's dashboard only (#144). type oauthError struct { - rejected bool - msg string + rejected bool + msg string + description string } func (e *oauthError) Error() string { return e.msg } @@ -214,6 +216,11 @@ func (h *Handler) OAuthFailure(keyName string) (message string, reconnect bool) if e != nil && e.err != nil { msg = e.err.Error() rejected = errors.Is(e.err, errOAuthRejected) + var oe *oauthError + if errors.As(e.err, &oe) && oe.description != "" { + // For the owner only; agents' 503 bodies carry msg alone. + msg += ` — provider said: "` + oe.description + `"` + } } h.oauth.mu.Unlock() if msg != "" { @@ -225,6 +232,30 @@ func (h *Handler) OAuthFailure(keyName string) (message string, reconnect bool) var oauthErrorCode = regexp.MustCompile(`^[a-z0-9_]{1,64}$`) +// oauthDescription is the provider's error_description fit to show: printable +// ASCII, at most 160 bytes, and "" if it contains the refresh token, secret or +// client ID (a provider could echo them). +func oauthDescription(d, refresh, secret, clientID string) string { + d = strings.TrimSpace(d) + if d == "" { + return "" + } + for _, v := range []string{refresh, secret, clientID} { + if v != "" && strings.Contains(d, v) { + return "" + } + } + if len(d) > 160 { + d = d[:160] + } + for i := 0; i < len(d); i++ { + if d[i] < 0x20 || d[i] > 0x7e { + return "" + } + } + return d +} + // usableAccessToken reports whether token may go into an Authorization // header: 1 to 8192 printable ASCII characters, no spaces. func usableAccessToken(token string) bool { @@ -276,6 +307,10 @@ func (h *Handler) fetchAccessToken(ctx context.Context, cfg policy.OAuth2, refre TokenType string `json:"token_type"` ExpiresIn json.RawMessage `json:"expires_in"` Error string `json:"error"` + // Description tells cases apart that share one code (Google's + // invalid_client: "The OAuth client was not found." for the ID, + // "Unauthorized" for the secret). + Description string `json:"error_description"` } decodeErr := json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&body) if resp.StatusCode != http.StatusOK { @@ -283,11 +318,18 @@ func (h *Handler) fetchAccessToken(ctx context.Context, cfg policy.OAuth2, refre if decodeErr == nil && oauthErrorCode.MatchString(body.Error) { code = body.Error } + described := func(rejected bool, format string, args ...any) (string, time.Duration, error) { + t, l, err := fail(rejected, format, args...) + if decodeErr == nil { + err.(*oauthError).description = oauthDescription(body.Description, refresh, secret, cfg.ClientID) + } + return t, l, err + } switch body.Error { case "invalid_grant", "invalid_client", "unauthorized_client": - return fail(true, "the provider rejected the refresh token or client (%s); connect the account again", code) + return described(true, "the provider rejected the refresh token or client (%s); connect the account again", code) } - return fail(false, "token endpoint answered %d (%s)", resp.StatusCode, code) + return described(false, "token endpoint answered %d (%s)", resp.StatusCode, code) } if decodeErr != nil { return fail(false, "token endpoint sent invalid JSON") diff --git a/internal/server/oauth2_test.go b/internal/server/oauth2_test.go index 0e50d4e..e5e66d5 100644 --- a/internal/server/oauth2_test.go +++ b/internal/server/oauth2_test.go @@ -309,3 +309,31 @@ func TestOAuthTestKeyMintsWithGivenRefreshToken(t *testing.T) { t.Fatalf("test request %s with %q", r.URL.Path, authOf(r)) } } + +// #144: the owner's failure status carries the provider's description so +// cases sharing one code can be told apart (Google's invalid_client: client +// not found vs. wrong secret); agents' 503 bodies still do not. +func TestOAuthFailureDescriptionForTheOwnerOnly(t *testing.T) { + up, _ := upstream(t) + te := newTokenEndpoint(t, 3600) + te.reply = func(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + io.WriteString(w, `{"error":"invalid_client","error_description":"Unauthorized"}`) + } + h, _, _ := newOAuthHandler(t, up.URL, te.srv.URL, policy.Access{Paths: []string{"/"}}) + w := call(h, "GET", "/api/v1/x", testToken, nil) + if w.Code != http.StatusServiceUnavailable || strings.Contains(w.Body.String(), "Unauthorized") { + t.Fatalf("agent body: %d %q", w.Code, w.Body) + } + msg, rejected := h.OAuthFailure("API_KEY") + if !rejected || !strings.Contains(msg, `invalid_client`) || !strings.Contains(msg, `provider said: "Unauthorized"`) { + t.Fatalf("owner status = %q", msg) + } + // A description that echoes a secret, or is not plain text, is dropped. + for _, d := range []string{"bad " + testRefresh, "line\nbreak", strings.Repeat("é", 3)} { + if got := oauthDescription(d, testRefresh, "s", "c"); got != "" { + t.Errorf("%q kept as %q", d, got) + } + } +} From e4a0d9e2d1434efb99797f900b05ba15b93f2b48 Mon Sep 17 00:00:00 2001 From: jerryfane Date: Tue, 10 Nov 2026 15:48:38 +0100 Subject: [PATCH 2/2] oauth2: build the failure error directly (#145 review P3) --- internal/server/oauth2.go | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/internal/server/oauth2.go b/internal/server/oauth2.go index 62ce862..697af19 100644 --- a/internal/server/oauth2.go +++ b/internal/server/oauth2.go @@ -318,18 +318,16 @@ func (h *Handler) fetchAccessToken(ctx context.Context, cfg policy.OAuth2, refre if decodeErr == nil && oauthErrorCode.MatchString(body.Error) { code = body.Error } - described := func(rejected bool, format string, args ...any) (string, time.Duration, error) { - t, l, err := fail(rejected, format, args...) - if decodeErr == nil { - err.(*oauthError).description = oauthDescription(body.Description, refresh, secret, cfg.ClientID) - } - return t, l, err - } + e := &oauthError{msg: fmt.Sprintf("oauth2 refresh failed: token endpoint answered %d (%s)", resp.StatusCode, code)} switch body.Error { case "invalid_grant", "invalid_client", "unauthorized_client": - return described(true, "the provider rejected the refresh token or client (%s); connect the account again", code) + e.rejected = true + e.msg = "oauth2 refresh failed: the provider rejected the refresh token or client (" + code + "); connect the account again" + } + if decodeErr == nil { + e.description = oauthDescription(body.Description, refresh, secret, cfg.ClientID) } - return described(false, "token endpoint answered %d (%s)", resp.StatusCode, code) + return "", 0, e } if decodeErr != nil { return fail(false, "token endpoint sent invalid JSON")