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: 1 addition & 1 deletion internal/dashboard/pages.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ Sign in with Apple: <code>{"service":"NAME","auth":"sign-in-with-apple-sign","si
<div class="card">
<p class="warnbox">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.</p>
{{range .Values}}<label>{{.Label}}{{if .Multiline}}<textarea id="{{.ID}}" data-exact="{{.Exact}}" readonly autocomplete="off" spellcheck="false" rows="8">
{{.Value}}</textarea>{{else}}<input id="{{.ID}}" data-exact="{{.Exact}}" readonly autocomplete="off" spellcheck="false" value="{{.Value}}">{{end}}</label><div class="actions"><button type="button" data-copy="{{.ID}}">Copy {{.Label}}</button></div>{{end}}
{{.Value}}</textarea>{{else}}<input id="{{.ID}}" data-exact="{{.Exact}}" readonly autocomplete="off" spellcheck="false" value="{{.Value}}">{{end}}</label>{{with .Warning}}<p class="warnbox">This value {{.}}.</p>{{end}}<div class="actions"><button type="button" data-copy="{{.ID}}">Copy {{.Label}}</button></div>{{end}}
<div class="actions"><a class="btn ghost" href="/keys/{{.Name}}">Done</a></div></div>
{{template "bottom"}}{{end}}

Expand Down
26 changes: 25 additions & 1 deletion internal/dashboard/reveal.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package dashboard

import (
"encoding/base64"
"fmt"
"net/http"
"strings"

"github.com/gitmoot/keyring/internal/store"
)
Expand All @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down
21 changes: 21 additions & 0 deletions internal/dashboard/reveal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
50 changes: 45 additions & 5 deletions internal/server/oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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 != "" {
Expand All @@ -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 {
Expand Down Expand Up @@ -276,18 +307,27 @@ 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 {
code := "no error code"
if decodeErr == nil && oauthErrorCode.MatchString(body.Error) {
code = body.Error
}
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 fail(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 fail(false, "token endpoint answered %d (%s)", resp.StatusCode, code)
return "", 0, e
}
if decodeErr != nil {
return fail(false, "token endpoint sent invalid JSON")
Expand Down
28 changes: 28 additions & 0 deletions internal/server/oauth2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
Loading