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
112 changes: 112 additions & 0 deletions pkgs/mcpx/internal/mcpauth/expand_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package mcpauth_test

import (
"encoding/base64"
"strings"
"testing"

"github.com/dezren39/mcpx/internal/mcpauth"
)

// The expansion contract (#1662, pinned by triage): only the braced
// ${VAR} shape is a reference. Every other $ in a credential is literal
// text that must reach the server byte-for-byte, and $${VAR} is the
// escape that writes a literal ${VAR}. These cases adapt the prepared
// probe for the defect: the BUG cases failed under the old os.Expand
// behaviour, the CTRL cases passed and must keep passing.

func basicWith(t *testing.T, user, pass string, get func(string) string) string {
t.Helper()
r, err := (&mcpauth.Auth{Type: "basic", Username: user, Password: pass}).ResolveWith(get)
if err != nil {
t.Fatal(err)
}
if len(r.Missing) > 0 {
t.Fatalf("Missing = %v, want none for a literal credential", r.Missing)
}
return r.Headers["Authorization"]
}

func wantBasic(user, pass string) string {
return "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))
}

func TestLiteralDollarCredentialsReachTheServerVerbatim(t *testing.T) {
home := func(name string) string {
if name == "HOME" {
return "/home/daemon"
}
return ""
}
// A literal password ending in a digit-dollar segment is not the
// special variable $2.
if got := basicWith(t, "u", "hunter$2", home); got != wantBasic("u", "hunter$2") {
t.Errorf("Authorization = %q, want the literal %q", got, wantBasic("u", "hunter$2"))
}
// '$$' in a literal password is not the special variable $.
if got := basicWith(t, "u", "pa$$word", home); got != wantBasic("u", "pa$$word") {
t.Errorf("Authorization = %q, want the literal %q", got, wantBasic("u", "pa$$word"))
}
// A $-segment naming a variable that IS set is not spliced into the
// credential: only the braced shape is a reference.
if got := basicWith(t, "u", "s3cret$HOME", home); got != wantBasic("u", "s3cret$HOME") {
t.Errorf("Authorization = %q, want the literal %q (decoded payload must not contain the daemon's HOME)", got, wantBasic("u", "s3cret$HOME"))
}
// An env value that merely mentions a price keeps it.
r2, err := (&mcpauth.Auth{Type: "env", Env: map[string]string{"NOTE": "cost is $5"}}).ResolveWith(
func(string) string { return "" })
if err != nil {
t.Fatal(err)
}
if r2.Env["NOTE"] != "cost is $5" || len(r2.Missing) > 0 {
t.Errorf("Env[NOTE] = %q, Missing = %v; want the literal value and no Missing", r2.Env["NOTE"], r2.Missing)
}
}

func TestExpansionContractShapes(t *testing.T) {
get := func(name string) string {
if name == "MY_TOKEN" {
return "tok"
}
return ""
}
bearer := func(tok string) *mcpauth.Resolved {
r, err := (&mcpauth.Auth{Type: "bearer", Token: tok}).ResolveWith(get)
if err != nil {
t.Fatal(err)
}
return r
}
// CTRL: the braced reference form expands.
if r := bearer("${MY_TOKEN}"); r.Headers["Authorization"] != "Bearer "+"tok" || len(r.Missing) != 0 {
t.Errorf("reference: got %v, Missing %v", r.Headers, r.Missing)
}
// The escape renders the literal text ${VAR} and references nothing.
if r := bearer("$${MY_TOKEN}"); r.Headers["Authorization"] != "Bearer "+"${MY_TOKEN}" || len(r.Missing) != 0 {
t.Errorf("escape: got %v, Missing %v; want the literal reference text", r.Headers, r.Missing)
}
// Literal shapes survive byte-for-byte: bare name, trailing $, and
// braced-looking text that is not a plain name.
for _, lit := range []string{"$MY_TOKEN", "abc$", "${MY_TOKEN:-fallback}", "${}", "${UNTERMINATED"} {
if r := bearer(lit); r.Headers["Authorization"] != "Bearer "+lit || len(r.Missing) != 0 {
t.Errorf("%q: got %v, Missing %v; want it literal with no Missing", lit, r.Headers, r.Missing)
}
}
// A reference and a literal $ in one value: only the reference moves.
if r := bearer("${MY_TOKEN}-$5"); r.Headers["Authorization"] != "Bearer "+"tok"+"-$5" {
t.Errorf("mixed: got %v", r.Headers)
}
// CTRL: a genuinely referenced, unset variable is still reported.
r3 := bearer("${NOT_THERE}")
if len(r3.Missing) != 1 || !strings.Contains(r3.Missing[0], "NOT_THERE") {
t.Errorf("missing: Missing = %v, want [NOT_THERE]", r3.Missing)
}
// A header value with a literal $ digit is untouched too.
h, err := (&mcpauth.Auth{Type: "header", Header: "X-Key", Value: "fee$2"}).ResolveWith(get)
if err != nil {
t.Fatal(err)
}
if h.Headers["X-Key"] != "fee$2" || len(h.Missing) != 0 {
t.Errorf("header: got %v, Missing %v", h.Headers, h.Missing)
}
}
80 changes: 70 additions & 10 deletions pkgs/mcpx/internal/mcpauth/mcpauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@
// This package covers the first two cases completely and gives the third a
// place to attach, because building OAuth before anything needs it would be
// guessing at a shape.
//
// Expansion contract for credential values (Token, Username, Password,
// header and query values, and non-empty Env values): only the braced
// shape ${VAR} is a reference and expands through the lookup. Every other
// $ is literal text, byte-for-byte — $VAR, $2, $$, a trailing $, and a
// ${...} whose contents are not a plain variable name all reach the
// server exactly as written, so a credential like "hunter$2" or
// "pa$$word" is never rewritten and never contributes a name to
// Resolved.Missing. To write a literal ${VAR}, double the dollar:
// $${VAR} renders the literal text ${VAR}. Missing names only variables
// that a genuine ${VAR} reference named and the lookup could not supply.
package mcpauth

import (
Expand All @@ -31,7 +42,9 @@ type Auth struct {
Type string `json:"type,omitempty"`

// Token is used by bearer. Expanded, so ${GITHUB_TOKEN} works and the
// secret itself never has to be in the file.
// secret itself never has to be in the file. Only the braced ${VAR}
// shape expands — see the package doc for the expansion contract,
// including the $${VAR} escape for writing a literal ${VAR}.
Token string `json:"token,omitempty"`

// Username and Password are used by basic.
Expand Down Expand Up @@ -109,18 +122,45 @@ func (a *Auth) ResolveWith(get func(name string) string) (*Resolved, error) {
return out, nil
}

// expand applies the expansion contract from the package doc: only
// the braced ${VAR} shape is a reference. Every other $ is literal
// text, and $${VAR} is the escape that writes a literal ${VAR}.
expand := func(v string) string {
if v == "" {
return ""
if !strings.Contains(v, "$") {
return v
}
expanded := os.Expand(v, func(name string) string {
got := get(name)
if got == "" {
out.Missing = append(out.Missing, name)
var b strings.Builder
b.Grow(len(v))
for i := 0; i < len(v); {
if v[i] != '$' {
b.WriteByte(v[i])
i++
continue
}
rest := v[i:]
if strings.HasPrefix(rest, "$${") {
// The escape: $${VAR} writes the literal text ${VAR}.
if _, n, ok := bracedName(rest[1:]); ok {
b.WriteString(rest[1 : 1+n])
i += 1 + n
continue
}
}
return got
})
return expanded
if strings.HasPrefix(rest, "${") {
if name, n, ok := bracedName(rest); ok {
got := get(name)
if got == "" {
out.Missing = append(out.Missing, name)
}
b.WriteString(got)
i += n
continue
}
}
b.WriteByte('$')
i++
}
return b.String()
}

for k, v := range a.Env {
Expand Down Expand Up @@ -280,6 +320,26 @@ func isPureRef(v string) bool {
return len(v) > 0
}

// bracedName parses a ${NAME} reference at the start of s, where NAME is
// letters, digits and underscores. It returns the name and the length of
// the whole reference. Anything else — an empty name, a name with other
// characters (such as a shell ${VAR:-default}), or a missing closing
// brace — is not a reference under the expansion contract and is left
// literal by the caller.
func bracedName(s string) (string, int, bool) {
if !strings.HasPrefix(s, "${") {
return "", 0, false
}
i := 2
for i < len(s) && (s[i] == '_' || '0' <= s[i] && s[i] <= '9' || 'a' <= s[i] && s[i] <= 'z' || 'A' <= s[i] && s[i] <= 'Z') {
i++
}
if i == 2 || i >= len(s) || s[i] != '}' {
return "", 0, false
}
return s[2:i], i + 1, true
}

// isShellSpecialVar is os.Expand's set: the characters that, directly
// after $, form a complete one-character variable reference.
func isShellSpecialVar(c byte) bool {
Expand Down
Loading