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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# TLSPROXY Release Notes

## next

### :wrench: Misc

* Register `[]any` and `map[string]any` with `encoding/gob` in `passkeys` so JWT claims containing arrays (such as
`"th"` or `"groups"`) or nested objects can be persisted to disk, propagate `depth` cleanly without persisting it in
`user.Claims`, and prefer the authenticated passkey's `email` query parameter over `redirectClaims["email"]` during
`RefreshID`.

## v0.26.5

### :wrench: Misc
Expand Down
33 changes: 22 additions & 11 deletions proxy/internal/passkeys/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"crypto/subtle"
_ "embed"
"encoding/base64"
"encoding/gob"
"encoding/hex"
"encoding/json"
"errors"
Expand Down Expand Up @@ -68,6 +69,8 @@ var (
)

func init() {
gob.Register([]any(nil))
gob.Register(map[string]any(nil))
authTemplate = template.Must(template.New("passkey-auth").Parse(authEmbed))
manageTemplate = template.Must(template.New("passkey-manage").Parse(manageEmbed))
}
Expand Down Expand Up @@ -326,12 +329,13 @@ func (m *Manager) HandleCallback(w http.ResponseWriter, req *http.Request) {
return
}

depth, _ := redirectClaims["depth"].(float64)
token, _, err := m.cfg.OtherCookieManager.ValidateAuthTokenCookie(req)
needLogin := err != nil
if !needLogin && mode == "RefreshID" {
email, _ := redirectClaims["email"].(string)
email := req.Form.Get("email")
if email == "" {
email = req.Form.Get("email")
email, _ = redirectClaims["email"].(string)
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || (email != "" && claims["email"] != email) {
Expand All @@ -345,16 +349,15 @@ func (m *Manager) HandleCallback(w http.ResponseWriter, req *http.Request) {
if needLogin {
switch mode {
case "RegisterNewID", "RefreshID":
depth, _ := redirectClaims["depth"].(int)
req.URL.Scheme = "https"
req.URL.Host = req.Host
opts := []idp.Option{
idp.WithDepth(depth + 1),
idp.WithDepth(int(depth) + 1),
}
if mode == "RefreshID" {
email, _ := redirectClaims["email"].(string)
email := req.Form.Get("email")
if email == "" {
email = req.Form.Get("email")
email, _ = redirectClaims["email"].(string)
}
opts = append(opts, idp.WithLoginHint(email))
}
Expand Down Expand Up @@ -467,7 +470,7 @@ func (m *Manager) HandleCallback(w http.ResponseWriter, req *http.Request) {
}
}
m.cfg.EventRecorder.Record("passkey check request")
m.setAuthToken(w, req, originalURL, claims)
m.setAuthToken(w, req, originalURL, claims, int(depth))

case "AddKey":
if req.Method != "POST" {
Expand All @@ -491,7 +494,7 @@ func (m *Manager) HandleCallback(w http.ResponseWriter, req *http.Request) {
return
}
m.cfg.EventRecorder.Record("passkey addkey request")
m.setAuthToken(w, req, originalURL, claims)
m.setAuthToken(w, req, originalURL, claims, int(depth))

case "Switch":
if req.Method != "POST" {
Expand Down Expand Up @@ -752,7 +755,7 @@ func (m *Manager) deleteKey(email string, id Bytes) (retErr error) {
return commit(true, nil)
}

func (m *Manager) setAuthToken(w http.ResponseWriter, req *http.Request, u *url.URL, claims map[string]any) {
func (m *Manager) setAuthToken(w http.ResponseWriter, req *http.Request, u *url.URL, claims map[string]any, depth int) {
if u == nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
Expand All @@ -772,6 +775,10 @@ func (m *Manager) setAuthToken(w http.ResponseWriter, req *http.Request, u *url.
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
delete(claims, "depth")
if depth > 0 {
claims["depth"] = depth
}
if err := m.cfg.CookieManager.SetAuthTokenCookie(w, req, subject, email, sid, u.Host, claims); err != nil {
m.cfg.Logger.Errorf("ERR SetAuthTokenCookie: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
Expand Down Expand Up @@ -910,9 +917,11 @@ func (m *Manager) processAttestation(claims map[string]any, host, jsargs string,
u = m.db.Handles[h]
}
if u == nil {
uc := maps.Clone(challenge.claims)
delete(uc, "depth")
u = &user{
Handle: challenge.uid,
Claims: challenge.claims,
Claims: uc,
}
uids := base64.RawURLEncoding.EncodeToString(challenge.uid)
if m.db.Handles == nil {
Expand Down Expand Up @@ -1079,7 +1088,9 @@ func (m *Manager) processAssertion(host, jsargs string, token *jwt.Token) (claim
if token != nil {
// Refresh claims if ID matches.
if nc, ok := token.Claims.(jwt.MapClaims); ok && nc["sub"] == u.Claims["sub"] && nc["email"] == u.Claims["email"] {
u.Claims = nc
uc := maps.Clone(map[string]any(nc))
delete(uc, "depth")
u.Claims = uc
}
}

Expand Down
65 changes: 63 additions & 2 deletions proxy/internal/passkeys/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import (
cbor "github.com/fxamacker/cbor/v2"

"github.com/c2FmZQ/tlsproxy/proxy/internal/cookiemanager"
"github.com/c2FmZQ/tlsproxy/proxy/internal/fromctx"
"github.com/c2FmZQ/tlsproxy/proxy/internal/idp"
"github.com/c2FmZQ/tlsproxy/proxy/internal/sid"
"github.com/c2FmZQ/tlsproxy/proxy/internal/tokenmanager"
Expand Down Expand Up @@ -84,10 +85,12 @@ func TestAssertionOptionsUnknownEmail(t *testing.T) {

type fakeIDP struct {
loginRequested bool
lastOpts idp.LoginOptions
}

func (f *fakeIDP) RequestLogin(w http.ResponseWriter, req *http.Request, origURL string, opts ...idp.Option) {
f.loginRequested = true
f.lastOpts = idp.ApplyOptions(opts)
http.Redirect(w, req, "https://idp.example.com/login", http.StatusFound)
}

Expand Down Expand Up @@ -184,15 +187,15 @@ func TestDuplicateCredentialIDAndRefreshIDLoop(t *testing.T) {
}

// RefreshID when OtherCookieManager has a valid token for a DIFFERENT user (bob@example.com)
// must trigger Other.RequestLogin rather than looping.
// must trigger Other.RequestLogin for alice@example.com (even if redirectClaims had email=bob@example.com).
req := httptest.NewRequest(http.MethodGet, "https://example.com/passkey", nil)
w := httptest.NewRecorder()
sid.SetSessionID(w, req, "sid123")
for _, c := range w.Result().Cookies() {
req.AddCookie(c)
}
u, _ := url.Parse("https://example.com/dest")
redirectTok, _, err := tm.URLToken(httptest.NewRecorder(), req, u, map[string]any{"email": "alice@example.com"})
redirectTok, _, err := tm.URLToken(httptest.NewRecorder(), req, u, map[string]any{"email": "bob@example.com", "depth": 1})
if err != nil {
t.Fatalf("URLToken: %v", err)
}
Expand All @@ -213,4 +216,62 @@ func TestDuplicateCredentialIDAndRefreshIDLoop(t *testing.T) {
if !otherIDP.loginRequested {
t.Errorf("HandleCallback(RefreshID) with mismatched user token did not request login from Other IdP")
}
if got := otherIDP.lastOpts.LoginHint(); got != "alice@example.com" {
t.Errorf("Other.RequestLogin LoginHint = %q, want %q", got, "alice@example.com")
}
if got := otherIDP.lastOpts.Depth(); got != 2 {
t.Errorf("Other.RequestLogin Depth = %d, want 2", got)
}

// Verify processAssertion succeeds when OtherCookieManager's token contains []any (e.g. "th"),
// map[string]any, and "depth", and that "depth" is stripped from persisted user.Claims.
reqWithTH := httptest.NewRequest(http.MethodGet, "https://example.com/passkey", nil)
reqWithTH = reqWithTH.WithContext(fromctx.WithTokenHash(reqWithTH.Context(), "prev-token-hash"))
w = httptest.NewRecorder()
if err := otherCM.SetAuthTokenCookie(w, reqWithTH, "alice", "alice@example.com", "sid123", "example.com", map[string]any{
"groups": []string{"admin", "users"},
"meta": map[string]any{"role": "owner"},
"depth": 1,
}); err != nil {
t.Fatalf("SetAuthTokenCookie(alice with th): %v", err)
}
for _, c := range w.Result().Cookies() {
reqWithTH.AddCookie(c)
}
aliceTok, _, err := otherCM.ValidateAuthTokenCookie(reqWithTH)
if err != nil {
t.Fatalf("ValidateAuthTokenCookie(alice): %v", err)
}
aso, err := m.assertionOptions("alice@example.com")
if err != nil {
t.Fatalf("assertionOptions(alice): %v", err)
}
id, cd, ad, sig, vh, err := auth.Get(aso)
if err != nil {
t.Fatalf("auth.Get: %v", err)
}
assertArgs, _ := json.Marshal(map[string]any{
"id": base64.RawURLEncoding.EncodeToString(id),
"clientDataJSON": Bytes(cd),
"authenticatorData": Bytes(ad),
"signature": Bytes(sig),
"userHandle": Bytes(vh),
"loginId": "alice@example.com",
})
if _, err := m.processAssertion("example.com", string(assertArgs), aliceTok); err != nil {
t.Fatalf("processAssertion with []any/map[string]any claims: %v", err)
}
reloadedDB := m.db
reloadedDB.Handles = nil
reloadedDB.Subjects = nil
if err := store.ReadDataFile(passkeyFile, &reloadedDB); err != nil {
t.Fatalf("ReadDataFile after processAssertion: %v", err)
}
aliceUser := reloadedDB.Handles[reloadedDB.Subjects["alice@example.com"]]
if _, ok := aliceUser.Claims["th"].([]any); !ok {
t.Errorf("reloadedDB Claims[th] = %T (%v), want []any", aliceUser.Claims["th"], aliceUser.Claims["th"])
}
if _, ok := aliceUser.Claims["depth"]; ok {
t.Errorf("reloadedDB Claims[depth] = %v, want nil", aliceUser.Claims["depth"])
}
}
Loading