Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Bind SAML logins to the browser that started them
rcourtmanb3b60f063224
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 7a04ad6bac..781bd1f3b8 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -8955,6 +8955,17 @@ into its in-memory IdP descriptor as base64 DER, which crewjam/saml can readwhen it verifies the IdP's ACS Responses and LogoutResponses. No agentregistration, enrolment, install, update or removal path changed.+### SAML logins bound to the browser that started them++`internal/api/saml_service.go` and `internal/api/saml_handlers.go` changed only+so `/api/saml/{id}/login` records each SAML AuthnRequest against a short-lived+login cookie and `/api/saml/{id}/acs` accepts the IdP's signed answer to it+once, in that browser, at default settings, reposting the IdP's cross-site+delivery once from Pulse's origin so the cookie arrives. Signed content+carrying a prefixed attribute or namespace declaration named like a SAML+attribute is refused. No agent+registration, enrolment, install, update or removal path changed.+### Demo write guard ignores websocket upgrade headers`internal/api/demo_middleware.go` changed only so a `POST`, `PUT`, `PATCH` ordiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 25e4feaca9..720412f6a6 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -5210,6 +5210,67 @@ in `internal/api/audit_handlers_test.go` replays one user's signed responseinto another user's browser and proves the victim's session survives and therefusal is audited.+The SAML ACS at `/api/saml/{id}/acs` accepts a Response, at default settings,+only as the IdP's answer to a login the presenting browser started. crewjam/saml+refuses a Response unless its `InResponseTo`, and that of each bearer+`SubjectConfirmationData`, is one of the request IDs its caller supplies, and+Pulse used to supply none, so with `allowIdpInitiated` off, the default, every+SAML login failed with "Authentication failed". `SAMLService.MakeAuthRequest`+in `internal/api/saml_service.go` therefore records each AuthnRequest ID, on+the provider's own service, with the sanitized `returnTo` and the hash of a+random token that `handleSAMLLogin` sets as the `HttpOnly`, `SameSite=Lax`+cookie `pulse_saml_login` (`__Host-pulse_saml_login` over HTTPS) for ten+minutes. A browser that already holds a token keeps it, so logins started one+after another in several tabs all stay valid. A record is honored for ten+minutes, judged when the Response spends it, unless the 1,024-record cap+evicts it first, oldest first. The IdP delivers its Response by a cross-site+HTTP-POST, which browsers send without `SameSite=Lax` cookies, so+`handleSAMLACS` answers a POST that carries a `SAMLResponse` or+`SAMLart` but no login cookie with a page that posts the same fields once more+from Pulse's own origin. The form has no `action`, so it returns to the URL+the IdP posted to, path prefix included, its script carries the request's CSP+nonce, and a marker field prevents a second repost. `SAMLService.ProcessResponse`+then has crewjam check the Response against every outstanding request ID and+reads the request it answers from the canonical form goxmldsig verified for+the signature covering the assertion crewjam returned, never from crewjam's+parsed fields, taking only an `InResponseTo` written without a prefix: the+signed `Response`'s, or that of the `Response` inside a signed+`ArtifactResponse`, when the IdP signed the message, and otherwise that of+every `SubjectConfirmationData` in the returned assertion's own `Subject`,+which must agree and of which there must be at least one, and no other signed+assertion may carry its ID. Other assertions in the Response, and assertions+in `Advice`, do not take part. That record is+spent only when it is bound to the presenting browser's token, and the login+returns to the recorded `returnTo`, not to the posted `RelayState`, which+`MakeAuthRequest` now escapes into the redirect query so a `returnTo` with its+own query string is not cut short at the IdP. A Response answering another browser's login, an unknown,+expired or already spent request, or none is refused with the+`saml_validation_failed` redirect and a failed `saml_login` audit event, and+refusing another browser's Response leaves that browser's record for it. With+`allowIdpInitiated` on, crewjam skips `InResponseTo`, so a Response answering+any request or none is accepted in any browser without the cookie or the+repost and returns to its posted `RelayState`, as before. In both modes the+signature verifier refuses signed content carrying a prefixed attribute or a+namespace declaration named like an un-namespaced attribute crewjam reads from+a Response or Assertion, such as `xmlns:IssueInstant`, `xmlns:NotOnOrAfter` or+`ext:ID`: encoding/xml fills an un-namespaced attribute field from any+attribute with that local name, and exclusive canonicalization leaves an+unused declaration out of the signed form, so appending one let a stale signed+Response pass crewjam's age checks, and an IdP-initiated login could be+replayed indefinitely. The records live in memory, so a+restart or a saved provider change (which replaces the provider's service;+a metadata refresh keeps the records) during the IdP round trip, or a login+started on a host that does not share cookies with the configured public+URL's, leaves the Response unmatched and the user starts the login again. Two logins started at+the same moment in a browser that holds no token yet each mint one and only+the last cookie set survives, so the other fails the same way, and, as with+OIDC login state, a flood of unauthenticated login starts can evict pending+records.+`TestSAMLACSAuditsResponseNotAnsweringThisBrowsersLogin` in+`internal/api/audit_handlers_test.go` delivers one browser's signed Response to+another browser with a login in progress and proves it is refused and audited+while its own browser completes the login.+Alert delivery diagnosis is a read-only monitoring API contract.`GET /api/alerts/delivery-diagnosis?alertIdentifier=<id>` returns the alertmanager's current delivery-policy projection for one active alert, including@@ -6511,11 +6572,9 @@ migrating. `TestContract_SAMLManualIDPCertificateVerifiesIdPSignatures` in`internal/api/contract_test.go` signs an ACS Response and a LogoutResponse withone test IdP key and proves an inline-certificate provider, a certificate-fileprovider and a metadata provider accept both alike, while a Response signed by-another key is refused. The proof enables IdP-initiated responses because-`SAMLService.ProcessResponse` records no AuthnRequest IDs: with-`allowIdpInitiated` off, crewjam refuses every ACS Response on `InResponseTo`-whatever its signature. That is a known open exception, not part of this-contract.+another key is refused. The proof runs at default settings, with each+Response answering an AuthnRequest that `SAMLService.MakeAuthRequest`+recorded for the test browser, as the SAML ACS binding above requires.That same SSO provider-detail boundary must return the non-secret nestedprovider configuration used by the settings edit form. `GET/api/security/sso/providers/{id}` may keep the flat list/card fields fordiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex cc3cc4c71c..1093076371 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -6895,6 +6895,16 @@ the PEM the administrator pasted and `idpCertFile` the path of a PEM file, sonothing persisted changes or needs migrating. No storage, retention, backup,migration or recovery path is added or moved.+### SAML logins bound to the browser that started them++`internal/api/saml_service.go` keeps each outstanding SAML AuthnRequest ID in+memory on the provider's service, with the login's return path and the hash of+the browser's `pulse_saml_login` cookie token, and honors it for ten minutes+(at most 1,024 records; expired ones are dropped on the next login). The cookie+expires after ten minutes. Nothing is persisted, so a restart during the IdP+round trip refuses the returning Response and the user signs in again. No+storage, retention, backup, migration or recovery path is added or moved.+### Demo write guard ignores websocket upgrade headers`internal/api/demo_middleware.go` no longer exempts every request carryingdiff --git a/internal/api/audit_handlers_test.go b/internal/api/audit_handlers_test.goindex 57e40f74cc..cf49bf20d1 100644--- a/internal/api/audit_handlers_test.go+++ b/internal/api/audit_handlers_test.go@@ -2,11 +2,13 @@ package apiimport ("context"+ "encoding/base64""encoding/json""fmt""net""net/http""net/http/httptest"+ "net/url""strings""testing""time"@@ -1131,3 +1133,46 @@ func TestSAMLSLOAuditsLogoutResponseNotBoundToSession(t *testing.T) {t.Fatalf("expected one successful saml_slo_callback event, got %+v", completions)}}++// At the ACS, a correctly signed Response answering another browser's login is+// refused, creates no session and is audited as a binding refusal, while the+// browser that started that login completes it and is audited as a success.+func TestSAMLACSAuditsResponseNotAnsweringThisBrowsersLogin(t *testing.T) {+ previousManager := GetTenantAuditManager()+ SetTenantAuditManager(nil)+ t.Cleanup(func() {+ SetTenantAuditManager(previousManager)+ })+ logger := &testAuditLoggerNoVerify{}+ setAuditLogger(t, logger)++ idp := newSAMLManualCertTestIdP(t)+ router, service := newSAMLACSTestRouter(t, idp, false)+ attackerRequestID, attackerToken := startSAMLTestLogin(t, router, "", "/")+ _, victimToken := startSAMLTestLogin(t, router, "", "/")+ form := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, attackerRequestID))}}++ loginEvents := func() []audit.Event {+ var events []audit.Event+ for _, event := range logger.events {+ if event.EventType == "saml_login" {+ events = append(events, event)+ }+ }+ return events+ }++ assertSAMLLoginRefused(t, deliverSAMLTestResponse(t, router, form, victimToken), "another browser's Response")+ refusals := loginEvents()+ if len(refusals) != 1 || refusals[0].Success ||+ refusals[0].Details != "SAML response does not answer a login started in this browser" {+ t.Fatalf("expected one failed saml_login binding refusal, got %+v", refusals)+ }++ logger.events = nil+ assertSAMLLoginSucceeded(t, deliverSAMLTestResponse(t, router, form, attackerToken), "/?saml=success", "the Response's own browser")+ completions := loginEvents()+ if len(completions) != 1 || !completions[0].Success || completions[0].Details != "SAML login success via okta" {+ t.Fatalf("expected one successful saml_login event, got %+v", completions)+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 8a335d11e8..a02232fc8d 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -4453,9 +4453,10 @@ func TestContract_SAMLLoginRejectsUnsupportedMethods(t *testing.T) {// A SAML provider configured by hand, with the IdP's SSO URL and its PEM// signing certificate pasted inline or named by IDPCertFile, verifies the// IdP's signatures with that certificate exactly as a provider configured from-// IdP metadata does: the ACS accepts the IdP's signed Response and reads the-// user from it, the IdP's signed answer to an SP-initiated logout completes-// that logout, and a Response signed by any other key is refused. Manual+// IdP metadata does: at default settings the ACS accepts the IdP's signed+// answer to an SP-initiated login and reads the user from it, the IdP's signed+// answer to an SP-initiated logout completes that logout, and a Response+// signed by any other key is refused. Manual// metadata used to hold the certificate as a PEM block where crewjam/saml// base64-decodes DER, so every signature check for these providers failed// before reaching the key.@@ -4485,34 +4486,32 @@ func TestContract_SAMLManualIDPCertificateVerifiesIdPSignatures(t *testing.T) {{name: "manual certificate file", cfg: manual("", certFile)},} {t.Run(tc.name, func(t *testing.T) {- // ProcessResponse records no AuthnRequest IDs, so by default- // crewjam refuses every Response on InResponseTo. Allowing- // IdP-initiated responses skips that check and leaves the- // signature, issuer, destination and timing checks to decide.- tc.cfg.AllowIDPInitiated = trueservice, err := NewSAMLService(context.Background(), "okta", tc.cfg, "https://pulse.example.com")if err != nil {t.Fatalf("NewSAMLService: %v", err)}+ browserKey := sessionHash("login-token")+ startLogin := func() string {+ t.Helper()+ redirectURL, err := service.MakeAuthRequest("/", browserKey)+ if err != nil {+ t.Fatalf("MakeAuthRequest: %v", err)+ }+ return samlTestAuthnRequestID(t, redirectURL)+ }- result, _, err := service.ProcessResponse(idp.acsPost(t, service))+ result, _, err := service.ProcessResponse(idp.acsPostAnswering(t, service, startLogin()), browserKey)if err != nil {t.Fatalf("ACS refused the configured IdP's signed Response: %s", samlRejectionDetail(err))}if result.Username != "alice" {t.Fatalf("ACS read username %q from the Response, want alice", result.Username)}- if _, _, err := service.ProcessResponse(impostor.acsPost(t, service)); err == nil {+ if _, _, err := service.ProcessResponse(impostor.acsPostAnswering(t, service, startLogin()), browserKey); err == nil {t.Fatal("ACS accepted a Response signed by a key the provider was not given")}- dataPath := t.TempDir()- resetSessionStoreForTests()- t.Cleanup(resetSessionStoreForTests)- resetCSRFStoreForTests()- t.Cleanup(resetCSRFStoreForTests)- InitSessionStore(dataPath)- InitCSRFStore(dataPath)+ useSAMLTestAuthStores(t)router := &Router{samlManager: NewSAMLServiceManager("https://pulse.example.com")}router.samlManager.services["okta"] = servicerequestID := startSAMLTestLogout(t, router, newSAMLTestSession(t, "alice"))diff --git a/internal/api/saml_handlers.go b/internal/api/saml_handlers.goindex b34723de02..4688838a07 100644--- a/internal/api/saml_handlers.go+++ b/internal/api/saml_handlers.go@@ -2,9 +2,11 @@ package apiimport ("context"+ "encoding/base64""encoding/json""errors""fmt"+ "html/template""net/http""strings""sync"@@ -155,13 +157,26 @@ func (r *Router) handleSAMLLogin(w http.ResponseWriter, req *http.Request) {}}- // Create SAML AuthnRequest- redirectURL, err := service.MakeAuthRequest(returnTo)+ // Create SAML AuthnRequest, bound to this browser's login cookie+ loginToken, err := samlLoginToken(req)+ if err != nil {+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to create SAML login binding")+ writeErrorResponse(w, http.StatusInternalServerError, "saml_auth_failed", "Failed to create authentication request", nil)+ return+ }+ redirectURL, err := service.MakeAuthRequest(returnTo, sessionHash(loginToken))if err != nil {log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to create SAML auth request")writeErrorResponse(w, http.StatusInternalServerError, "saml_auth_failed", "Failed to create authentication request", nil)return}+ cookiePolicy := getBrowserCookiePolicy(req)+ cookiePolicy.setHTTPOnly(w, &http.Cookie{+ Name: samlLoginCookieName(cookiePolicy.secure),+ Value: loginToken,+ Path: "/",+ MaxAge: int(samlRequestTTL / time.Second),+ })LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login_initiated", "", GetClientIP(req), req.URL.Path, true, "Provider: "+providerID)@@ -208,11 +223,29 @@ func (r *Router) handleSAMLACS(w http.ResponseWriter, req *http.Request) {return}+ if err := req.ParseForm(); err != nil {+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to parse SAML response form")+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", "", GetClientIP(req), req.URL.Path, false, "SAML response validation failed: failed to parse form: "+err.Error())+ r.redirectSAMLError(w, req, "", "saml_validation_failed")+ return+ }+ browserKey := samlLoginBrowserKey(req)+ if browserKey == "" && !service.AllowsIDPInitiated() && req.PostForm.Get(samlACSRepostField) == "" &&+ (req.PostForm.Get("SAMLResponse") != "" || req.PostForm.Get("SAMLart") != "") {+ writeSAMLACSRepost(w, req)+ return+ }+// Process SAML response- result, relayState, err := service.ProcessResponse(req)+ result, relayState, err := service.ProcessResponse(req, browserKey)if err != nil {- log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to process SAML response")- LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", "", GetClientIP(req), req.URL.Path, false, "SAML response validation failed: "+err.Error())+ if errors.Is(err, errSAMLResponseUnbound) {+ log.Warn().Err(err).Str("provider_id", providerID).Str("client_ip", GetClientIP(req)).Msg("SAML Response does not answer a login started in this browser")+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", "", GetClientIP(req), req.URL.Path, false, "SAML response does not answer a login started in this browser")+ } else {+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to process SAML response")+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", "", GetClientIP(req), req.URL.Path, false, "SAML response validation failed: "+err.Error())+ }r.redirectSAMLError(w, req, relayState, "saml_validation_failed")return}@@ -627,6 +660,101 @@ func samlSessionBindingKey(req *http.Request) string {return sessionHash(cookie.Value)}+// The SAML login cookie binds each SP-initiated login to the browser that+// started it. handleSAMLLogin sets it to a random token and records the+// AuthnRequest against the token's hash; the ACS accepts the IdP's Response+// only from a browser presenting that token. Like the session cookie it uses+// the __Host- prefix over HTTPS, so a related subdomain cannot plant a token+// of its own.+const (+ cookieNameSAMLLogin = "pulse_saml_login"+ cookieNameSAMLLoginSecure = "__Host-pulse_saml_login"+ samlLoginTokenBytes = 32+ // samlACSRepostField marks the ACS form writeSAMLACSRepost re-posts.+ samlACSRepostField = "PulseSAMLRepost"+)++func samlLoginCookieName(secure bool) string {+ if secure {+ return cookieNameSAMLLoginSecure+ }+ return cookieNameSAMLLogin+}++// readSAMLLoginCookie reads the login cookie the way readSessionCookie reads+// the session cookie.+func readSAMLLoginCookie(req *http.Request) (*http.Cookie, error) {+ if isConnectionSecure(req) {+ return req.Cookie(cookieNameSAMLLoginSecure)+ }+ if cookie, err := req.Cookie(cookieNameSAMLLogin); err == nil {+ return cookie, nil+ }+ return req.Cookie(cookieNameSAMLLoginSecure)+}++// samlLoginToken returns the login token the browser already holds, so that+// logins started in several tabs all stay bound to it, or a new one.+func samlLoginToken(req *http.Request) (string, error) {+ if cookie, err := readSAMLLoginCookie(req); err == nil && validSAMLLoginToken(cookie.Value) {+ return cookie.Value, nil+ }+ return generateRandomURLString(samlLoginTokenBytes)+}++func validSAMLLoginToken(token string) bool {+ if len(token) != base64.RawURLEncoding.EncodedLen(samlLoginTokenBytes) {+ return false+ }+ _, err := base64.RawURLEncoding.DecodeString(token)+ return err == nil+}++// samlLoginBrowserKey returns the binding key of the login token the request+// carries, or "" when it carries none.+func samlLoginBrowserKey(req *http.Request) string {+ cookie, err := readSAMLLoginCookie(req)+ if err != nil || !validSAMLLoginToken(cookie.Value) {+ return ""+ }+ return sessionHash(cookie.Value)+}++var samlACSRepostPage = template.Must(template.New("saml-acs-repost").Parse(`<!DOCTYPE html>+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Signing in to Pulse</title></head>+<body><form method="post">{{range .Fields}}<input type="hidden" name="{{.Name}}" value="{{.Value}}">{{end}}<p>Finishing sign-in…</p><noscript><button type="submit">Continue</button></noscript></form>+<script nonce="{{.Nonce}}">document.forms[0].submit();</script></body></html>+`))++// writeSAMLACSRepost answers the IdP's HTTP-POST delivery of a Response that+// arrived without the login cookie. The IdP's page posts to the ACS from+// another site, and browsers withhold SameSite=Lax cookies from cross-site+// POSTs, so the cookie that binds the login to this browser is missing on+// arrival in every browser. The page posts the same fields once more from+// Pulse's own origin, which carries the cookie. The form has no action, so it+// returns to the URL the IdP posted to, path prefix included, and the marker+// field stops a second repost: a browser that still has no cookie started no+// login here, and the ACS refuses its Response.+func writeSAMLACSRepost(w http.ResponseWriter, req *http.Request) {+ type field struct{ Name, Value string }+ page := struct {+ Fields []field+ Nonce string+ }{Nonce: CSPNonceFromContext(req.Context())}+ for _, name := range []string{"SAMLResponse", "SAMLart", "RelayState"} {+ if value := req.PostForm.Get(name); value != "" {+ page.Fields = append(page.Fields, field{Name: name, Value: value})+ }+ }+ page.Fields = append(page.Fields, field{Name: samlACSRepostField, Value: "1"})++ w.Header().Set("Content-Type", "text/html; charset=utf-8")+ w.Header().Set("Cache-Control", "no-store")+ if err := samlACSRepostPage.Execute(w, page); err != nil {+ log.Error().Err(err).Msg("Failed to write SAML ACS repost page")+ }+}+// clearSession clears the current session - properly invalidates server-side session// and clears both pulse_session and pulse_csrf cookiesfunc (r *Router) clearSession(w http.ResponseWriter, req *http.Request) {diff --git a/internal/api/saml_handlers_more_test.go b/internal/api/saml_handlers_more_test.goindex 0105dfc39b..ec1e80ca31 100644--- a/internal/api/saml_handlers_more_test.go+++ b/internal/api/saml_handlers_more_test.go@@ -10,10 +10,12 @@ import ("encoding/xml""errors""fmt"+ "html""io""net/http""net/http/httptest""net/url"+ "regexp""strings""testing""time"@@ -794,35 +796,450 @@ func (idp *samlManualCertTestIdP) metadataXML() string {// acsPost returns the HTTP-POST binding request to the service's ACS carrying// a signed, unsolicited (no InResponseTo) Response that identifies alice.func (idp *samlManualCertTestIdP) acsPost(t *testing.T, service *SAMLService) *http.Request {+ t.Helper()+ return samlTestACSRequest(service, url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, ""))}})+}++// acsPostAnswering returns the same request for an SP-initiated login: the+// Response and its SubjectConfirmationData answer the AuthnRequest requestID.+func (idp *samlManualCertTestIdP) acsPostAnswering(t *testing.T, service *SAMLService, requestID string) *http.Request {+ t.Helper()+ return samlTestACSRequest(service, url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, requestID))}})+}++// responseXML returns the Response the IdP posts to the service's ACS after+// authenticating alice, answering requestID ("" for an unsolicited one). Both+// the Response and its Assertion are signed.+func (idp *samlManualCertTestIdP) responseXML(t *testing.T, service *SAMLService, requestID string) []byte {+ t.Helper()+ return idp.signedResponseXML(t, service, requestID, "alice", nil)+}++// signedResponseXML is responseXML for the user nameID, with edit applied to+// the Assertion before the IdP signs it.+func (idp *samlManualCertTestIdP) signedResponseXML(t *testing.T, service *SAMLService, requestID, nameID string, edit func(*saml.Assertion)) []byte {t.Helper()spMetadata := service.sp.Metadata()authn := &saml.IdpAuthnRequest{IDP: idp.idp,HTTPRequest: httptest.NewRequest(http.MethodPost, "https://idp.example.com/sso", nil),+ Request: saml.AuthnRequest{ID: requestID},ServiceProviderMetadata: spMetadata,SPSSODescriptor: &spMetadata.SPSSODescriptors[0],ACSEndpoint: &saml.IndexedEndpoint{Binding: saml.HTTPPostBinding, Location: service.sp.AcsURL.String()},Now: time.Now(),}if err := (saml.DefaultAssertionMaker{}).MakeAssertion(authn, &saml.Session{- ID: "idp-session-alice",+ ID: "idp-session-" + nameID,CreateTime: time.Now(),ExpireTime: time.Now().Add(time.Hour),- Index: "idx-alice",- NameID: "alice",+ Index: "idx-" + nameID,+ NameID: nameID,}); err != nil {t.Fatalf("make assertion: %v", err)}+ if edit != nil {+ edit(authn.Assertion)+ }form, err := authn.PostBinding()if err != nil {t.Fatalf("sign ACS Response: %v", err)}- req := httptest.NewRequest(http.MethodPost, service.sp.AcsURL.String(),- strings.NewReader(url.Values{"SAMLResponse": {form.SAMLResponse}}.Encode()))+ raw, err := base64.StdEncoding.DecodeString(form.SAMLResponse)+ if err != nil {+ t.Fatalf("decode ACS Response: %v", err)+ }+ return raw+}++func samlTestACSRequest(service *SAMLService, form url.Values) *http.Request {+ req := httptest.NewRequest(http.MethodPost, service.sp.AcsURL.String(), strings.NewReader(form.Encode()))req.Header.Set("Content-Type", "application/x-www-form-urlencoded")return req}+// samlTestAuthnRequestID returns the ID of the AuthnRequest carried by an+// HTTP-Redirect binding URL to the IdP.+func samlTestAuthnRequestID(t *testing.T, redirectURL string) string {+ t.Helper()+ location, err := url.Parse(redirectURL)+ if err != nil || location.Host != "idp.example.com" {+ t.Fatalf("unexpected AuthnRequest redirect %q (%v)", redirectURL, err)+ }+ var authnRequest struct {+ ID string `xml:"ID,attr"`+ }+ if err := xml.Unmarshal(inflateSAMLTestPayload(t, location.Query().Get("SAMLRequest")), &authnRequest); err != nil {+ t.Fatalf("parse AuthnRequest: %v", err)+ }+ if authnRequest.ID == "" {+ t.Fatal("AuthnRequest has no ID")+ }+ return authnRequest.ID+}++// samlTestXMLAttr appends attr="value" to the first start tag named tag (any+// prefix) in doc, the way an attacker edits a signed Response in transit.+func samlTestXMLAttr(t *testing.T, doc []byte, tag, attr, value string) []byte {+ t.Helper()+ re := regexp.MustCompile(`<([A-Za-z0-9]+:)?` + tag + `[\s>/]`)+ loc := re.FindIndex(doc)+ if loc == nil {+ t.Fatalf("no <%s> in %s", tag, doc)+ }+ end := bytes.IndexByte(doc[loc[0]:], '>') + loc[0]+ if doc[end-1] == '/' {+ end--+ }+ out := append([]byte{}, doc[:end]...)+ out = append(out, []byte(` `+attr+`="`+value+`"`)...)+ return append(out, doc[end:]...)+}++// useSAMLTestAuthStores gives the test fresh session and CSRF stores and puts+// the previous ones back afterwards, so tests that run later still find the+// stores they were using.+func useSAMLTestAuthStores(t *testing.T) {+ t.Helper()+ dataPath := t.TempDir()++ sessionStoreMu.Lock()+ previousSessionStore, previousSessionPath := sessionStore, sessionStoreDataPath+ sessionStore, sessionStoreDataPath = nil, ""+ sessionStoreMu.Unlock()+ csrfStoreMu.Lock()+ previousCSRFStore, previousCSRFPath := csrfStore, csrfStoreDataPath+ csrfStore, csrfStoreDataPath = nil, ""+ csrfStoreMu.Unlock()+ InitSessionStore(dataPath)+ InitCSRFStore(dataPath)++ t.Cleanup(func() {+ resetSessionStoreForTests()+ resetCSRFStoreForTests()+ sessionStoreMu.Lock()+ sessionStore, sessionStoreDataPath = previousSessionStore, previousSessionPath+ sessionStoreMu.Unlock()+ csrfStoreMu.Lock()+ csrfStore, csrfStoreDataPath = previousCSRFStore, previousCSRFPath+ csrfStoreMu.Unlock()+ })+}++// samlTestUnsignedResponse removes the Response's own signature, leaving only+// its Assertion signed, as many IdPs send it.+func samlTestUnsignedResponse(t *testing.T, signed []byte) []byte {+ t.Helper()+ unsigned := regexp.MustCompile(`(?s)(<samlp:Response[^>]*>.*?</saml:Issuer>)<ds:Signature.*?</ds:Signature>`).ReplaceAll(signed, []byte("$1"))+ if bytes.Equal(unsigned, signed) {+ t.Fatalf("could not strip the Response signature from %s", signed)+ }+ return unsigned+}++const samlACSTestProvider = "okta"++// newSAMLACSTestRouter returns a router whose "okta" SAML provider trusts idp+// through its metadata, at default settings unless allowIDPInitiated is set,+// with fresh session and CSRF stores.+func newSAMLACSTestRouter(t *testing.T, idp *samlManualCertTestIdP, allowIDPInitiated bool) (*Router, *SAMLService) {+ t.Helper()+ useSAMLTestAuthStores(t)++ cfg := &config.SAMLProviderConfig{IDPMetadataXML: idp.metadataXML(), AllowIDPInitiated: allowIDPInitiated}+ service, err := NewSAMLService(context.Background(), samlACSTestProvider, cfg, "https://pulse.example.com")+ if err != nil {+ t.Fatalf("NewSAMLService: %v", err)+ }+ router := &Router{+ samlManager: NewSAMLServiceManager("https://pulse.example.com"),+ ssoConfig: &config.SSOConfig{Providers: []config.SSOProvider{{+ ID: samlACSTestProvider, Name: "Test SAML", Type: config.SSOProviderTypeSAML, Enabled: true, SAML: cfg,+ }}},+ }+ router.samlManager.services[samlACSTestProvider] = service+ return router, service+}++// startSAMLTestLogin starts SP-initiated login in a browser holding loginToken+// ("" for a browser that has none yet) and returns the ID of the AuthnRequest+// sent to the IdP and the login token the browser holds afterwards.+func startSAMLTestLogin(t *testing.T, router *Router, loginToken, returnTo string) (requestID, heldToken string) {+ t.Helper()+ target := "/api/saml/okta/login"+ if returnTo != "" {+ target += "?returnTo=" + url.QueryEscape(returnTo)+ }+ req := httptest.NewRequest(http.MethodGet, target, nil)+ if loginToken != "" {+ req.AddCookie(&http.Cookie{Name: cookieNameSAMLLogin, Value: loginToken})+ }+ rec := httptest.NewRecorder()+ router.handleSAMLLogin(rec, req)+ if rec.Code != http.StatusFound {+ t.Fatalf("login: expected status %d, got %d body=%q", http.StatusFound, rec.Code, rec.Body.String())+ }+ heldToken = loginToken+ for _, cookie := range rec.Result().Cookies() {+ if cookie.Name == cookieNameSAMLLogin {+ if !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode || cookie.MaxAge <= 0 || cookie.Path != "/" {+ t.Fatalf("login cookie must be an HttpOnly SameSite=Lax cookie that expires, got %+v", cookie)+ }+ heldToken = cookie.Value+ }+ }+ if heldToken == "" {+ t.Fatal("login set no login cookie")+ }+ return samlTestAuthnRequestID(t, rec.Header().Get("Location")), heldToken+}++// postSAMLTestACS delivers an ACS form from a browser holding loginToken (""+// for none). A cross-site HTTP-POST from the IdP carries no SameSite=Lax+// cookie, so pass "" to model the IdP's own delivery.+func postSAMLTestACS(router *Router, form url.Values, loginToken string) *httptest.ResponseRecorder {+ req := httptest.NewRequest(http.MethodPost, "/api/saml/okta/acs", strings.NewReader(form.Encode()))+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ if loginToken != "" {+ req.AddCookie(&http.Cookie{Name: cookieNameSAMLLogin, Value: loginToken})+ }+ rec := httptest.NewRecorder()+ router.handleSAMLACS(rec, req)+ return rec+}++// samlTestRepostForm returns the hidden fields of the ACS repost page.+func samlTestRepostForm(t *testing.T, rec *httptest.ResponseRecorder) url.Values {+ t.Helper()+ if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/html") {+ t.Fatalf("expected the ACS repost page, got status %d type %q body=%q", rec.Code, rec.Header().Get("Content-Type"), rec.Body.String())+ }+ form := url.Values{}+ for _, match := range regexp.MustCompile(`<input type="hidden" name="([^"]+)" value="([^"]*)">`).FindAllStringSubmatch(rec.Body.String(), -1) {+ form.Add(match[1], html.UnescapeString(match[2]))+ }+ return form+}++// deliverSAMLTestResponse delivers a Response the way the browser that holds+// loginToken receives it: the IdP's cross-site POST, which carries no login+// cookie and gets the repost page, then the page's same-origin repost.+func deliverSAMLTestResponse(t *testing.T, router *Router, form url.Values, loginToken string) *httptest.ResponseRecorder {+ t.Helper()+ return postSAMLTestACS(router, samlTestRepostForm(t, postSAMLTestACS(router, form, "")), loginToken)+}++func assertSAMLLoginSucceeded(t *testing.T, rec *httptest.ResponseRecorder, wantLocation, label string) {+ t.Helper()+ if rec.Code != http.StatusFound || rec.Header().Get("Location") != wantLocation {+ t.Fatalf("%s: expected redirect to %q, got status %d location %q body=%q", label, wantLocation, rec.Code, rec.Header().Get("Location"), rec.Body.String())+ }+ for _, cookie := range rec.Result().Cookies() {+ if cookie.Name == cookieNameSession && cookie.Value != "" && ValidateSession(cookie.Value) {+ return+ }+ }+ t.Fatalf("%s: login established no session, cookies %v", label, rec.Result().Cookies())+}++func assertSAMLLoginRefused(t *testing.T, rec *httptest.ResponseRecorder, label string) {+ t.Helper()+ if rec.Code != http.StatusFound || !strings.Contains(rec.Header().Get("Location"), "saml_error=saml_validation_failed") {+ t.Fatalf("%s: expected the validation-failed redirect, got status %d location %q body=%q", label, rec.Code, rec.Header().Get("Location"), rec.Body.String())+ }+ for _, cookie := range rec.Result().Cookies() {+ if cookie.Name == cookieNameSession || cookie.Name == cookieNameSessionSecure {+ t.Fatalf("%s: refused login wrote session cookie %+v", label, cookie)+ }+ }+}++// At default settings, with IdP-initiated logins off, SP-initiated login+// completes: the IdP's cross-site POST of its signed answer gets the repost+// page, whose same-origin repost carries the login cookie, and the login+// returns to the recorded returnTo whatever RelayState the IdP posts.+func TestHandleSAMLACS_CompletesLoginStartedInThisBrowser(t *testing.T) {+ idp := newSAMLManualCertTestIdP(t)+ router, service := newSAMLACSTestRouter(t, idp, false)++ requestID, token := startSAMLTestLogin(t, router, "", "/alerts?tab=history&range=7d")+ form := url.Values{+ "SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, requestID))},+ "RelayState": {"/settings"},+ }+ repost := postSAMLTestACS(router, form, "")+ fields := samlTestRepostForm(t, repost)+ if fields.Get("SAMLResponse") != form.Get("SAMLResponse") || fields.Get("RelayState") != "/settings" || fields.Get(samlACSRepostField) != "1" {+ t.Fatalf("repost page must carry the posted fields and the repost marker, got %v", fields)+ }+ if cookies := repost.Result().Cookies(); len(cookies) != 0 {+ t.Fatalf("repost page must not write cookies, got %v", cookies)+ }+ if body := repost.Body.String(); strings.Contains(body, " action=") || !strings.Contains(body, "document.forms[0].submit()") {+ t.Fatalf("repost page must submit itself back to the URL the IdP posted to, got %q", body)+ }++ assertSAMLLoginSucceeded(t, postSAMLTestACS(router, fields, token), "/alerts?range=7d&saml=success&tab=history", "repost with login cookie")+}++// Each AuthnRequest is answered once, and only in the browser that started it.+// A Response answering another browser's request, an unknown request or none+// is refused, and refusing another browser leaves that browser's login intact.+func TestHandleSAMLACS_RefusesResponsesNotAnsweringThisBrowsersLogin(t *testing.T) {+ idp := newSAMLManualCertTestIdP(t)+ router, service := newSAMLACSTestRouter(t, idp, false)++ victimRequestID, victimToken := startSAMLTestLogin(t, router, "", "/")+ attackerRequestID, attackerToken := startSAMLTestLogin(t, router, "", "/")+ attackerForm := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, attackerRequestID))}}++ assertSAMLLoginRefused(t, deliverSAMLTestResponse(t, router, attackerForm, victimToken), "another browser's Response")+ for _, requestID := range []string{"", "id-never-issued-by-this-sp"} {+ form := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, requestID))}}+ assertSAMLLoginRefused(t, deliverSAMLTestResponse(t, router, form, victimToken), "InResponseTo="+requestID)+ }+ assertSAMLLoginRefused(t, postSAMLTestACS(router, url.Values{+ "SAMLResponse": attackerForm["SAMLResponse"],+ samlACSRepostField: {"1"},+ }, ""), "repost without a login cookie")++ assertSAMLLoginSucceeded(t, deliverSAMLTestResponse(t, router, attackerForm, attackerToken), "/?saml=success", "the Response's own browser")+ assertSAMLLoginRefused(t, deliverSAMLTestResponse(t, router, attackerForm, attackerToken), "replay in the same browser")++ victimForm := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, victimRequestID))}}+ assertSAMLLoginSucceeded(t, deliverSAMLTestResponse(t, router, victimForm, victimToken), "/?saml=success", "the victim's own login after the refusals")+}++// encoding/xml fills an un-namespaced attribute field from a namespace+// declaration with the same local name, and exclusive canonicalization leaves+// an unused declaration out of the signed form. Declaring xmlns:InResponseTo+// on a signed Response or Assertion must not rebind the attacker's answer to+// the victim's outstanding AuthnRequest, whether the Response itself is signed+// or only its Assertion is.+func TestHandleSAMLACS_InResponseToIgnoresNamespaceDeclarations(t *testing.T) {+ idp := newSAMLManualCertTestIdP(t)+ router, service := newSAMLACSTestRouter(t, idp, false)++ victimRequestID, victimToken := startSAMLTestLogin(t, router, "", "/")+ attackerRequestID, _ := startSAMLTestLogin(t, router, "", "/")+ signed := idp.responseXML(t, service, attackerRequestID)++ spoofed := samlTestXMLAttr(t, signed, "Response", "xmlns:InResponseTo", victimRequestID)+ spoofed = samlTestXMLAttr(t, spoofed, "SubjectConfirmationData", "xmlns:InResponseTo", victimRequestID)+ assertSAMLLoginRefused(t, deliverSAMLTestResponse(t, router, url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(spoofed)}}, victimToken), "signed Response")++ // Without its own signature the Response's attributes are the attacker's+ // to write; only the signed Assertion says which request it answers.+ assertionOnly := bytes.Replace(samlTestUnsignedResponse(t, signed), []byte(`InResponseTo="`+attackerRequestID+`"`), []byte(`InResponseTo="`+victimRequestID+`"`), 1)+ assertionOnly = samlTestXMLAttr(t, assertionOnly, "SubjectConfirmationData", "xmlns:InResponseTo", victimRequestID)+ assertSAMLLoginRefused(t, deliverSAMLTestResponse(t, router, url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(assertionOnly)}}, victimToken), "assertion-only signature")++ victimForm := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, victimRequestID))}}+ assertSAMLLoginSucceeded(t, deliverSAMLTestResponse(t, router, victimForm, victimToken), "/?saml=success", "the victim's own login after the spoofs")+}++// Many IdPs sign only the Assertion. Its signed SubjectConfirmationData then+// names the request, and the login completes. A signed assertion that confirms+// no request cannot ride along with one that does: an IdP-signed assertion for+// another user without a SubjectConfirmation, placed ahead of the victim's own+// in an unsigned Response, is the assertion crewjam would return, and the+// victim's request must not vouch for it.+func TestHandleSAMLACS_BindsTheAssertionItReturns(t *testing.T) {+ idp := newSAMLManualCertTestIdP(t)+ router, service := newSAMLACSTestRouter(t, idp, false)++ victimRequestID, victimToken := startSAMLTestLogin(t, router, "", "/")+ victimResponse := samlTestUnsignedResponse(t, idp.responseXML(t, service, victimRequestID))++ unconfirmed := idp.signedResponseXML(t, service, "", "mallory", func(assertion *saml.Assertion) {+ assertion.Subject.SubjectConfirmations = nil+ })+ unconfirmedAssertion := regexp.MustCompile(`(?s)<saml:Assertion .*?</saml:Assertion>`).Find(unconfirmed)+ at := bytes.Index(victimResponse, []byte("<saml:Assertion "))+ if unconfirmedAssertion == nil || at < 0 {+ t.Fatalf("could not splice assertions: %s / %s", unconfirmed, victimResponse)+ }+ spliced := append(append(append([]byte{}, victimResponse[:at]...), unconfirmedAssertion...), victimResponse[at:]...)+ assertSAMLLoginRefused(t, deliverSAMLTestResponse(t, router, url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(spliced)}}, victimToken), "unconfirmed assertion ahead of the victim's")++ assertSAMLLoginSucceeded(t, deliverSAMLTestResponse(t, router, url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(victimResponse)}}, victimToken), "/?saml=success", "assertion-only signature")+}++// Logins started in several tabs of one browser share its login cookie, and+// each completes with its own Response, in any order, returning to its own+// path.+func TestHandleSAMLACS_CompletesLoginsFromSeveralTabs(t *testing.T) {+ idp := newSAMLManualCertTestIdP(t)+ router, service := newSAMLACSTestRouter(t, idp, false)++ firstRequestID, token := startSAMLTestLogin(t, router, "", "/infrastructure")+ secondRequestID, secondToken := startSAMLTestLogin(t, router, token, "/alerts")+ if secondToken != token {+ t.Fatalf("a second login must keep the browser's login token, got %q then %q", token, secondToken)+ }++ second := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, secondRequestID))}}+ assertSAMLLoginSucceeded(t, deliverSAMLTestResponse(t, router, second, token), "/alerts?saml=success", "second tab")+ first := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(idp.responseXML(t, service, firstRequestID))}}+ assertSAMLLoginSucceeded(t, deliverSAMLTestResponse(t, router, first, token), "/infrastructure?saml=success", "first tab")+}++// With IdP-initiated logins allowed, an unsolicited Response still completes+// without a login cookie or a repost, as before request binding. But a stale+// signed Response stays stale: namespace declarations named like the+// attributes crewjam checks for age cannot override them.+func TestHandleSAMLACS_IDPInitiatedResponsesCannotOverrideTheirAge(t *testing.T) {+ idp := newSAMLManualCertTestIdP(t)+ router, service := newSAMLACSTestRouter(t, idp, true)++ signed := idp.responseXML(t, service, "")+ form := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(signed)}, "RelayState": {"/settings"}}+ assertSAMLLoginSucceeded(t, postSAMLTestACS(router, form, ""), "/settings?saml=success", "fresh unsolicited Response")++ realNow := saml.TimeNow+ t.Cleanup(func() { saml.TimeNow = realNow })+ saml.TimeNow = func() time.Time { return realNow().Add(2 * time.Hour) }+ assertSAMLLoginRefused(t, postSAMLTestACS(router, form, ""), "stale unsolicited Response")++ future := realNow().Add(3 * time.Hour).UTC().Format(time.RFC3339)+ spoofed := samlTestXMLAttr(t, signed, "Response", "xmlns:IssueInstant", future)+ spoofed = samlTestXMLAttr(t, spoofed, "Assertion", "xmlns:IssueInstant", future)+ spoofed = samlTestXMLAttr(t, spoofed, "SubjectConfirmationData", "xmlns:NotOnOrAfter", future)+ spoofed = samlTestXMLAttr(t, spoofed, "Conditions", "xmlns:NotOnOrAfter", future)+ assertSAMLLoginRefused(t, postSAMLTestACS(router, url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(spoofed)}}, ""), "stale Response with spoofed age")+}++// The repost page is the IdP's form replayed from Pulse's origin: values are+// HTML-escaped and its script carries the request's CSP nonce.+func TestWriteSAMLACSRepost_EscapesFieldsAndCarriesCSPNonce(t *testing.T) {+ req := httptest.NewRequest(http.MethodPost, "/api/saml/okta/acs", strings.NewReader(url.Values{+ "SAMLResponse": {`"><script>alert(1)</script>`},+ "RelayState": {"/"},+ "Unrelated": {"dropped"},+ }.Encode()))+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ req = req.WithContext(context.WithValue(req.Context(), cspNonceKey{}, "test-nonce"))+ if err := req.ParseForm(); err != nil {+ t.Fatalf("parse form: %v", err)+ }+ rec := httptest.NewRecorder()+ writeSAMLACSRepost(rec, req)++ body := rec.Body.String()+ if strings.Contains(body, "<script>alert(1)") || strings.Contains(body, "Unrelated") {+ t.Fatalf("repost page must escape values and carry only SAML fields, got %q", body)+ }+ if !strings.Contains(body, `<script nonce="test-nonce">`) {+ t.Fatalf("repost script must carry the CSP nonce, got %q", body)+ }+ if got := rec.Header().Get("Cache-Control"); got != "no-store" {+ t.Fatalf("repost page must not be cached, got Cache-Control %q", got)+ }+ if fields := samlTestRepostForm(t, rec); fields.Get("SAMLResponse") != `"><script>alert(1)</script>` {+ t.Fatalf("repost must carry the exact posted value, got %v", fields)+ }+}+// samlRejectionDetail adds crewjam/saml's private reason to a rejected// response, which its public error ("Authentication failed") hides.func samlRejectionDetail(err error) string {diff --git a/internal/api/saml_service.go b/internal/api/saml_service.goindex 962327f139..fae6e23303 100644--- a/internal/api/saml_service.go+++ b/internal/api/saml_service.go@@ -14,14 +14,18 @@ import ("io""net/http""net/url"+ "reflect"+ "sort""strings""sync""time"+ "github.com/beevik/etree""github.com/crewjam/saml""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/securityutil""github.com/rs/zerolog/log"+ dsig "github.com/russellhaering/goxmldsig")// SAMLService manages SAML Service Provider functionality for a single provider@@ -35,16 +39,19 @@ type SAMLService struct {baseURL stringlastRefresh time.Time+ // authnRequests holds the SP-initiated AuthnRequests still waiting for+ // the IdP's Response, each bound to the browser that started the login.+ authnRequests samlRequestStore// logoutRequests holds the SP-initiated LogoutRequests still waiting for// the IdP's LogoutResponse.- logoutRequests samlLogoutRequestStore+ logoutRequests samlRequestStore}const (- // samlLogoutRequestTTL bounds how long the IdP round trip of an- // SP-initiated logout may take, matching the OIDC login state lifetime.- samlLogoutRequestTTL = 10 * time.Minute- maxSAMLLogoutRequestEntries = 1024+ // samlRequestTTL bounds how long the IdP round trip of an SP-initiated+ // login or logout may take, matching the OIDC login state lifetime.+ samlRequestTTL = 10 * time.Minute+ maxSAMLRequestEntries = 1024// samlLogoutResponseMaxBytes matches crewjam/saml's inflate limit for the// HTTP-Redirect binding.samlLogoutResponseMaxBytes = 10 << 20@@ -55,34 +62,46 @@ const (// session.var errSAMLLogoutResponseUnbound = errors.New("logout response does not answer an outstanding logout request for this session")-// samlLogoutRequestStore records the LogoutRequests this SP issued, keyed by-// request ID, with the session each one logged out. crewjam/saml checks a-// LogoutResponse's signature, destination, issuer, status and age but never-// its InResponseTo, so without this record any recent signed response from the-// IdP, including one answering another user's logout, would be accepted.-type samlLogoutRequestStore struct {+// errSAMLResponseUnbound marks an ACS Response that does not answer an+// outstanding AuthnRequest this SP issued to the presenting browser.+var errSAMLResponseUnbound = errors.New("response does not answer an outstanding authentication request from this browser")++// samlRequestStore records the requests this SP issued and is still waiting+// for the IdP to answer, keyed by request ID. Each record carries the key of+// what the request is bound to: the browser that started an SP-initiated+// login, or the session an SP-initiated logout ended.+//+// crewjam/saml checks a LogoutResponse's signature, destination, issuer,+// status and age but never its InResponseTo, so without these records any+// recent signed response from the IdP, including one answering another user's+// logout, would be accepted. For logins crewjam does check InResponseTo, but+// only against the request IDs its caller supplies, and without records there+// were none to supply: every SP-initiated Response was refused.+type samlRequestStore struct {mu sync.Mutex- entries map[string]samlLogoutRequest+ entries map[string]samlRequestRecord}-type samlLogoutRequest struct {- sessionKey string- expiresAt time.Time+type samlRequestRecord struct {+ bindingKey string+ // returnTo is the local path an SP-initiated login returns to.+ returnTo string+ expiresAt time.Time}-func (s *samlLogoutRequestStore) put(requestID, sessionKey string, now time.Time) {+func (s *samlRequestStore) put(requestID string, record samlRequestRecord, now time.Time) {s.mu.Lock()defer s.mu.Unlock()if s.entries == nil {- s.entries = make(map[string]samlLogoutRequest)+ s.entries = make(map[string]samlRequestRecord)}for id, entry := range s.entries {if !now.Before(entry.expiresAt) {delete(s.entries, id)}}- for len(s.entries) >= maxSAMLLogoutRequestEntries {+ for len(s.entries) >= maxSAMLRequestEntries {oldestID := ""var oldestExpiry time.Timefor id, entry := range s.entries {@@ -93,10 +112,8 @@ func (s *samlLogoutRequestStore) put(requestID, sessionKey string, now time.Time}delete(s.entries, oldestID)}- s.entries[requestID] = samlLogoutRequest{- sessionKey: sessionKey,- expiresAt: now.Add(samlLogoutRequestTTL),- }+ record.expiresAt = now.Add(samlRequestTTL)+ s.entries[requestID] = record}// consume spends the outstanding request a verified LogoutResponse answers.@@ -105,7 +122,7 @@ func (s *samlLogoutRequestStore) put(requestID, sessionKey string, now time.Time// it answers an unexpired request and the browser carries either no session// or the session that request logged out. The request is spent on every// verified presentation, so a response is honored at most once.-func (s *samlLogoutRequestStore) consume(requestID, sessionKey string, now time.Time) error {+func (s *samlRequestStore) consume(requestID, sessionKey string, now time.Time) error {s.mu.Lock()defer s.mu.Unlock()@@ -117,12 +134,47 @@ func (s *samlLogoutRequestStore) consume(requestID, sessionKey string, now time.if !now.Before(entry.expiresAt) {return fmt.Errorf("%w: request %q expired", errSAMLLogoutResponseUnbound, requestID)}- if sessionKey != "" && sessionKey != entry.sessionKey {+ if sessionKey != "" && sessionKey != entry.bindingKey {return fmt.Errorf("%w: request %q logged out a different session", errSAMLLogoutResponseUnbound, requestID)}return nil}+// outstanding returns every unexpired request, sorted, and whether any of+// them is bound to bindingKey.+func (s *samlRequestStore) outstanding(bindingKey string, now time.Time) (requestIDs []string, bound bool) {+ s.mu.Lock()+ defer s.mu.Unlock()++ for id, entry := range s.entries {+ if now.Before(entry.expiresAt) {+ requestIDs = append(requestIDs, id)+ bound = bound || (bindingKey != "" && entry.bindingKey == bindingKey)+ }+ }+ sort.Strings(requestIDs)+ return requestIDs, bound+}++// spend removes and returns the unexpired request a verified ACS Response+// answers, provided it is bound to bindingKey, the presenting browser. A+// request bound to another browser is left for that browser, so presenting a+// stolen Response elsewhere does not cost its owner the login.+func (s *samlRequestStore) spend(requestID, bindingKey string, now time.Time) (samlRequestRecord, error) {+ s.mu.Lock()+ defer s.mu.Unlock()++ entry, ok := s.entries[requestID]+ if requestID == "" || bindingKey == "" || !ok || entry.bindingKey != bindingKey {+ return samlRequestRecord{}, fmt.Errorf("%w: no outstanding request from this browser matches InResponseTo %q", errSAMLResponseUnbound, requestID)+ }+ delete(s.entries, requestID)+ if !now.Before(entry.expiresAt) {+ return samlRequestRecord{}, fmt.Errorf("%w: request %q expired", errSAMLResponseUnbound, requestID)+ }+ return entry, nil+}+func normalizeSAMLBaseURL(baseURL string) (string, error) {normalized := strings.TrimRight(strings.TrimSpace(baseURL), "/")if normalized == "" {@@ -544,25 +596,40 @@ func (s *SAMLService) loadSPCredentials() (*x509.Certificate, *rsa.PrivateKey, ereturn cert, key, nil}-// MakeAuthRequest creates a SAML AuthnRequest and returns the redirect URL-func (s *SAMLService) MakeAuthRequest(relayState string) (string, error) {+// MakeAuthRequest creates a SAML AuthnRequest and returns the HTTP-Redirect+// binding URL that sends it to the IdP. It records the request as outstanding+// for browserKey, the login binding key of the browser starting the login,+// together with returnTo, so that ProcessResponse accepts the IdP's answer to+// this request only once, only from that browser, and returns it to returnTo.+func (s *SAMLService) MakeAuthRequest(returnTo, browserKey string) (string, error) {s.mu.RLock()defer s.mu.RUnlock()if s.sp == nil {return "", errors.New("service provider not initialized")}+ if browserKey == "" {+ return "", errors.New("authentication request has no browser to bind")+ }- if relayState == "" {- relayState = "/"+ if returnTo == "" {+ returnTo = "/"}if len(s.idpMetadata.IDPSSODescriptors) == 0 ||len(s.idpMetadata.IDPSSODescriptors[0].SingleSignOnServices) == 0 {return "", errors.New("idp does not support single sign-on")}- // Use the simple redirect method- redirectURL, err := s.sp.MakeRedirectAuthenticationRequest(relayState)+ // This is crewjam's MakeRedirectAuthenticationRequest, unrolled to learn+ // the request's ID.+ authnRequest, err := s.sp.MakeAuthenticationRequest(s.sp.GetSSOBindingLocation(saml.HTTPRedirectBinding), saml.HTTPRedirectBinding, saml.HTTPPostBinding)+ if err != nil {+ return "", fmt.Errorf("failed to create auth request: %w", err)+ }+ // Redirect appends RelayState to the query as given, so escape it: a+ // returnTo with its own query string would otherwise split into stray+ // parameters and come back from the IdP truncated.+ redirectURL, err := authnRequest.Redirect(url.QueryEscape(returnTo), s.sp)if err != nil {return "", fmt.Errorf("failed to create auth request: %w", err)}@@ -576,11 +643,35 @@ func (s *SAMLService) MakeAuthRequest(relayState string) (string, error) {if err != nil {return "", fmt.Errorf("failed to validate auth redirect: %w", err)}+ s.authnRequests.put(authnRequest.ID, samlRequestRecord{bindingKey: browserKey, returnTo: returnTo}, time.Now())return validatedURL, nil}-// ProcessResponse processes a SAML response and extracts user information-func (s *SAMLService) ProcessResponse(r *http.Request) (*SAMLAuthResult, string, error) {+// AllowsIDPInitiated reports whether the provider accepts IdP-initiated+// (unsolicited) Responses, which answer no AuthnRequest and so cannot be bound+// to the browser that receives them.+func (s *SAMLService) AllowsIDPInitiated() bool {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.sp != nil && s.sp.AllowIDPInitiated+}++// ProcessResponse verifies the IdP's Response posted to the ACS and extracts+// the user it authenticates, along with the local path the login returns to.+//+// Unless the provider allows IdP-initiated logins, the Response must answer+// an unexpired AuthnRequest from MakeAuthRequest that is bound to browserKey,+// the login binding key of the presenting browser ("" when it carries none),+// and it spends that request, so each login is completed at most once and only+// in the browser that started it. The request ID is read from what the IdP's+// signatures cover, never from crewjam/saml's parsed fields (see+// samlSignedContent). The returned path is the one recorded with the request,+// not the posted RelayState. Binding failures wrap errSAMLResponseUnbound.+//+// With IdP-initiated logins allowed, crewjam skips InResponseTo entirely, so a+// Response answering any request, or none, is accepted in any browser and+// returns to its posted RelayState, as before request binding existed.+func (s *SAMLService) ProcessResponse(r *http.Request, browserKey string) (*SAMLAuthResult, string, error) {s.mu.RLock()defer s.mu.RUnlock()@@ -595,18 +686,43 @@ func (s *SAMLService) ProcessResponse(r *http.Request) (*SAMLAuthResult, string,relayState := r.FormValue("RelayState")- // Allow IdP-initiated flow- possibleRequestIDs := []string{}- if s.sp.AllowIDPInitiated {- possibleRequestIDs = append(possibleRequestIDs, "")+ // crewjam checks that the Response answers one of possibleRequestIDs,+ // every outstanding AuthnRequest here; spend then decides whether it is+ // this browser's.+ now := time.Now()+ possibleRequestIDs := []string{""}+ if !s.sp.AllowIDPInitiated {+ var bound bool+ possibleRequestIDs, bound = s.authnRequests.outstanding(browserKey, now)+ if !bound {+ return nil, relayState, fmt.Errorf("%w: this browser has no login in progress", errSAMLResponseUnbound)+ }}- // Parse and validate the SAML assertion- assertion, err := s.sp.ParseResponse(r, possibleRequestIDs)+ // Parse and validate the SAML assertion on a copy of the service provider+ // whose signature verifier keeps what each verified signature covers.+ signed := &samlSignedContent{}+ sp := *s.sp+ sp.SignatureVerifier = signed+ assertion, err := sp.ParseResponse(r, possibleRequestIDs)if err != nil {return nil, relayState, fmt.Errorf("failed to validate saml response: %w", err)}+ if !s.sp.AllowIDPInitiated {+ requestID, err := signed.inResponseTo(assertion.ID)+ if err != nil {+ return nil, relayState, fmt.Errorf("%w: %v", errSAMLResponseUnbound, err)+ }+ // Artifact resolution and signature checks take time, so judge+ // the request's expiry now rather than when parsing began.+ request, err := s.authnRequests.spend(requestID, browserKey, time.Now())+ if err != nil {+ return nil, relayState, err+ }+ relayState = request.returnTo+ }+// Extract user information from assertionresult := &SAMLAuthResult{Attributes: make(map[string][]string),@@ -721,7 +837,7 @@ func (s *SAMLService) MakeLogoutRequest(nameID, sessionIdx, sessionKey string) (if err != nil {return "", err}- s.logoutRequests.put(req.ID, sessionKey, time.Now())+ s.logoutRequests.put(req.ID, samlRequestRecord{bindingKey: sessionKey}, time.Now())return validatedURL, nil}@@ -827,6 +943,180 @@ func logoutResponseInResponseTo(raw []byte) (string, error) {}}+// samlSignedContent is the signature verifier ProcessResponse gives crewjam/saml+// for one ACS Response. It verifies each signature exactly as crewjam's default+// verifier does and keeps the content that signature covers: the canonical form+// goxmldsig digested, which holds only what the IdP signed.+//+// crewjam reads a Response's fields by unmarshalling the posted elements with+// encoding/xml, which fills an un-namespaced attribute field from any attribute+// with that local name, whatever its prefix, the last one winning. That+// includes a namespace declaration such as xmlns:IssueInstant, and exclusive+// canonicalization leaves a declaration nothing uses out of the signed form,+// so one can be appended to a signed element without breaking its signature+// and override what crewjam checks: InResponseTo, IssueInstant, NotOnOrAfter,+// Recipient, Destination. VerifySignature therefore refuses signed content+// carrying any prefixed attribute or declaration named like an un-namespaced+// attribute crewjam reads, so crewjam's fields match what was signed, and the+// binding decision still reads InResponseTo from the kept canonical content+// rather than from crewjam's fields.+type samlSignedContent struct {+ elements []*etree.Element+}++func (c *samlSignedContent) VerifySignature(validationContext *dsig.ValidationContext, el *etree.Element) error {+ if shadow := samlShadowingAttribute(el); shadow != "" {+ return fmt.Errorf("cannot validate signature on %s: %s shadows a SAML attribute", el.Tag, shadow)+ }+ signed, err := validationContext.Validate(el)+ if err != nil {+ return fmt.Errorf("cannot validate signature on %s: %v", el.Tag, err)+ }+ c.elements = append(c.elements, signed)+ return nil+}++// inResponseTo returns the AuthnRequest ID that the signature covering the+// assertion crewjam returned, identified by its ID, says it answers.+//+// When the Response, or an ArtifactResponse carrying it, is signed, the IdP+// signed the whole message, the returned assertion included, and the signed+// Response's InResponseTo names the request. Otherwise crewjam verified the+// returned assertion's own signature, and the request is named by that+// assertion's SubjectConfirmationData: every SubjectConfirmation of its+// Subject must carry the same one, and at least one must exist, because+// crewjam accepts a Subject without any. Other signed assertions in the same+// Response, and assertions in Advice, do not take part.+func (c *samlSignedContent) inResponseTo(assertionID string) (string, error) {+ for _, el := range c.elements {+ response := el+ if el.Tag == "ArtifactResponse" {+ response = samlChildElement(el, "Response")+ }+ if response == nil || response.Tag != "Response" {+ continue+ }+ if requestID := samlUnprefixedAttr(response, "InResponseTo"); requestID != "" {+ return requestID, nil+ }+ return "", errors.New("the signed Response answers no request")+ }+ var assertion *etree.Element+ for _, el := range c.elements {+ if el.Tag != "Assertion" || samlUnprefixedAttr(el, "ID") != assertionID {+ continue+ }+ if assertion != nil {+ return "", fmt.Errorf("several signed assertions carry ID %q", assertionID)+ }+ assertion = el+ }+ if assertion == nil {+ return "", errors.New("no signature covers the returned assertion")+ }+ requestID := ""+ if subject := samlChildElement(assertion, "Subject"); subject != nil {+ for _, confirmation := range subject.ChildElements() {+ if confirmation.Tag != "SubjectConfirmation" {+ continue+ }+ // crewjam keeps the last SubjectConfirmationData of each+ // confirmation, so every one must agree.+ named := false+ for _, data := range confirmation.ChildElements() {+ if data.Tag != "SubjectConfirmationData" {+ continue+ }+ value := samlUnprefixedAttr(data, "InResponseTo")+ if value == "" || (requestID != "" && value != requestID) {+ return "", errors.New("the signed assertion's subject confirmations do not name one request")+ }+ requestID, named = value, true+ }+ if !named {+ return "", errors.New("a signed subject confirmation names no request")+ }+ }+ }+ if requestID == "" {+ return "", errors.New("the signed assertion has no subject confirmation naming a request")+ }+ return requestID, nil+}++// samlChildElement returns el's first child element with local name tag.+func samlChildElement(el *etree.Element, tag string) *etree.Element {+ for _, child := range el.ChildElements() {+ if child.Tag == tag {+ return child+ }+ }+ return nil+}++// samlUnprefixedAttr returns el's attribute key written without a prefix, the+// one a signature over el covers, or "" when it has none.+func samlUnprefixedAttr(el *etree.Element, key string) string {+ for _, attr := range el.Attr {+ if attr.Space == "" && attr.Key == key {+ return attr.Value+ }+ }+ return ""+}++// samlBoundAttributeNames holds the name of every un-namespaced XML attribute+// crewjam/saml unmarshals from a Response or an Assertion. Namespaced ones such+// as xsi:type only match their own namespace.+var samlBoundAttributeNames = func() map[string]bool {+ names := make(map[string]bool)+ seen := make(map[reflect.Type]bool)+ var collect func(t reflect.Type)+ collect = func(t reflect.Type) {+ for t.Kind() == reflect.Pointer || t.Kind() == reflect.Slice || t.Kind() == reflect.Array {+ t = t.Elem()+ }+ if t.Kind() != reflect.Struct || seen[t] {+ return+ }+ seen[t] = true+ for i := 0; i < t.NumField(); i++ {+ field := t.Field(i)+ name, options, _ := strings.Cut(field.Tag.Get("xml"), ",")+ if strings.Contains(","+options+",", ",attr,") {+ if name == "" {+ name = field.Name+ }+ if !strings.Contains(name, " ") {+ names[name] = true+ }+ }+ collect(field.Type)+ }+ }+ collect(reflect.TypeOf(saml.Response{}))+ collect(reflect.TypeOf(saml.Assertion{}))+ return names+}()++// samlShadowingAttribute returns the first prefixed attribute or namespace+// declaration in el or its descendants whose local name is also an+// un-namespaced attribute crewjam/saml reads, as written, or "" when there is+// none.+func samlShadowingAttribute(el *etree.Element) string {+ for _, attr := range el.Attr {+ if attr.Space != "" && samlBoundAttributeNames[attr.Key] {+ return attr.Space + ":" + attr.Key+ }+ }+ for _, child := range el.ChildElements() {+ if shadow := samlShadowingAttribute(child); shadow != "" {+ return shadow+ }+ }+ return ""+}+func validateSAMLRedirectTarget(rawURL string, allowedEndpoints []saml.Endpoint) (string, error) {validatedURL, err := securityutil.NormalizeAbsoluteHTTPURL(rawURL)if err != nil {diff --git a/internal/api/saml_service_additional_test.go b/internal/api/saml_service_additional_test.goindex 4ce28c052d..3674b1d2ff 100644--- a/internal/api/saml_service_additional_test.go+++ b/internal/api/saml_service_additional_test.go@@ -46,7 +46,7 @@ func TestProcessResponse_InvalidResponse(t *testing.T) {req := httptest.NewRequest(http.MethodPost, "/acs", body)req.Header.Set("Content-Type", "application/x-www-form-urlencoded")- _, relay, err := service.ProcessResponse(req)+ _, relay, err := service.ProcessResponse(req, "")if err == nil {t.Fatal("expected error for invalid response")}diff --git a/internal/api/saml_service_test.go b/internal/api/saml_service_test.goindex fe15ffa417..36f85490fb 100644--- a/internal/api/saml_service_test.go+++ b/internal/api/saml_service_test.go@@ -17,6 +17,7 @@ import ("testing""time"+ "github.com/beevik/etree""github.com/crewjam/saml""github.com/rcourtman/pulse-go-rewrite/internal/config")@@ -187,7 +188,7 @@ func TestSAMLServiceBasicFlows(t *testing.T) {t.Fatalf("new service: %v", err)}- url, err := service.MakeAuthRequest("")+ url, err := service.MakeAuthRequest("", sessionHash("login-token"))if err != nil || !strings.Contains(url, "SAMLRequest") {t.Fatalf("unexpected auth url: %v %s", err, url)}@@ -202,7 +203,7 @@ func TestSAMLServiceBasicFlows(t *testing.T) {}service = &SAMLService{config: &config.SAMLProviderConfig{}}- if _, err := service.MakeAuthRequest(""); err == nil {+ if _, err := service.MakeAuthRequest("", sessionHash("login-token")); err == nil {t.Fatal("expected error when sp missing")}if _, err := service.GetMetadata(); err == nil {@@ -216,36 +217,175 @@ func TestSAMLServiceBasicFlows(t *testing.T) {}}-// Outstanding SLO requests expire after samlLogoutRequestTTL, and the store-// keeps at most maxSAMLLogoutRequestEntries by dropping the oldest.+// Outstanding SLO requests expire after samlRequestTTL, and the store keeps+// at most maxSAMLRequestEntries by dropping the oldest.func TestSAMLLogoutRequestStoreExpiresAndEvictsOldest(t *testing.T) {- var store samlLogoutRequestStore+ var store samlRequestStorenow := time.Now()key := sessionHash("session-token")+ record := samlRequestRecord{bindingKey: key}- store.put("id-expired", key, now)- if err := store.consume("id-expired", key, now.Add(samlLogoutRequestTTL)); !errors.Is(err, errSAMLLogoutResponseUnbound) {+ store.put("id-expired", record, now)+ if err := store.consume("id-expired", key, now.Add(samlRequestTTL)); !errors.Is(err, errSAMLLogoutResponseUnbound) {t.Fatalf("expected an expired request to be refused, got %v", err)}- store.put("id-live", key, now)- if err := store.consume("id-live", "", now.Add(samlLogoutRequestTTL-time.Second)); err != nil {+ store.put("id-live", record, now)+ if err := store.consume("id-live", "", now.Add(samlRequestTTL-time.Second)); err != nil {t.Fatalf("expected a live request to be accepted, got %v", err)}- for i := 0; i <= maxSAMLLogoutRequestEntries; i++ {- store.put(fmt.Sprintf("id-%04d", i), key, now.Add(time.Duration(i)*time.Millisecond))+ for i := 0; i <= maxSAMLRequestEntries; i++ {+ store.put(fmt.Sprintf("id-%04d", i), record, now.Add(time.Duration(i)*time.Millisecond))}- if len(store.entries) != maxSAMLLogoutRequestEntries {- t.Fatalf("expected %d outstanding requests, got %d", maxSAMLLogoutRequestEntries, len(store.entries))+ if len(store.entries) != maxSAMLRequestEntries {+ t.Fatalf("expected %d outstanding requests, got %d", maxSAMLRequestEntries, len(store.entries))}if err := store.consume("id-0000", key, now); !errors.Is(err, errSAMLLogoutResponseUnbound) {t.Fatalf("expected the oldest request to be evicted, got %v", err)}- if err := store.consume(fmt.Sprintf("id-%04d", maxSAMLLogoutRequestEntries), key, now); err != nil {+ if err := store.consume(fmt.Sprintf("id-%04d", maxSAMLRequestEntries), key, now); err != nil {t.Fatalf("expected the newest request to be kept, got %v", err)}}+// Outstanding AuthnRequests are spent only by the browser they are bound to. A+// request presented by another browser stays outstanding for its owner, and+// each request is spent once and only before it expires.+func TestSAMLAuthnRequestStoreSpendsOnlyForItsBrowser(t *testing.T) {+ var store samlRequestStore+ now := time.Now()+ alice, bob := sessionHash("alice-login"), sessionHash("bob-login")++ store.put("id-alice-2", samlRequestRecord{bindingKey: alice, returnTo: "/alerts"}, now)+ store.put("id-alice-1", samlRequestRecord{bindingKey: alice, returnTo: "/"}, now)+ store.put("id-bob", samlRequestRecord{bindingKey: bob, returnTo: "/"}, now)++ if got, bound := store.outstanding(alice, now); strings.Join(got, ",") != "id-alice-1,id-alice-2,id-bob" || !bound {+ t.Fatalf("outstanding(alice) = %v, %v; want every request, bound", got, bound)+ }+ if _, bound := store.outstanding("", now); bound {+ t.Fatal("a browser without a login token has no request bound to it")+ }+ if _, err := store.spend("id-bob", alice, now); !errors.Is(err, errSAMLResponseUnbound) {+ t.Fatalf("expected another browser's request to be refused, got %v", err)+ }+ if _, err := store.spend("id-bob", "", now); !errors.Is(err, errSAMLResponseUnbound) {+ t.Fatalf("expected a browser without a login token to be refused, got %v", err)+ }+ if record, err := store.spend("id-bob", bob, now); err != nil || record.returnTo != "/" {+ t.Fatalf("refusing other browsers must leave the request for its owner, got %+v %v", record, err)+ }+ record, err := store.spend("id-alice-2", alice, now)+ if err != nil || record.returnTo != "/alerts" {+ t.Fatalf("spend(id-alice-2) = %+v %v, want its recorded returnTo", record, err)+ }+ if _, err := store.spend("id-alice-2", alice, now); !errors.Is(err, errSAMLResponseUnbound) {+ t.Fatalf("expected a spent request to be refused, got %v", err)+ }+ if got, bound := store.outstanding(alice, now.Add(samlRequestTTL)); len(got) != 0 || bound {+ t.Fatalf("expired requests must not be outstanding, got %v, %v", got, bound)+ }+ if _, err := store.spend("id-alice-1", alice, now.Add(samlRequestTTL)); !errors.Is(err, errSAMLResponseUnbound) {+ t.Fatalf("expected an expired request to be refused, got %v", err)+ }+}++// The binding decision reads InResponseTo from the canonical content of the+// signature that covers the assertion crewjam returned, taking only the+// attribute written without a prefix: the signed Response's when the message+// is signed, otherwise the returned assertion's own subject confirmations.+func TestSAMLSignedContentInResponseTo(t *testing.T) {+ parse := func(doc string) *etree.Element {+ t.Helper()+ parsed := etree.NewDocument()+ if err := parsed.ReadFromString(doc); err != nil {+ t.Fatalf("parse %s: %v", doc, err)+ }+ return parsed.Root()+ }+ assertion := func(id, subject, advice string) string {+ return `<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="` + id + `"><saml:Subject>` + subject + `</saml:Subject>` + advice + `</saml:Assertion>`+ }+ confirmation := func(attrs string) string {+ return `<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><saml:SubjectConfirmationData ` + attrs + `/></saml:SubjectConfirmation>`+ }+ response := func(attrs, body string) string {+ return `<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ` + attrs + `>` + body + `</samlp:Response>`+ }+ own, other := `InResponseTo="id-own"`, `InResponseTo="id-other"`+ advice := `<saml:Advice>` + assertion("a9", confirmation(other), "") + `</saml:Advice>`++ for _, tc := range []struct {+ name string+ signed []string+ want string+ }{+ {name: "signed Response", signed: []string{response(`xmlns:InResponseTo="id-other" `+own, assertion("a1", confirmation(other), ""))}, want: "id-own"},+ {name: "signed Response with encrypted Assertion", signed: []string{response(own, `<saml:EncryptedAssertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"/>`)}, want: "id-own"},+ {name: "signed ArtifactResponse", signed: []string{`<samlp:ArtifactResponse xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" InResponseTo="id-artifact">` + response(own, "") + `</samlp:ArtifactResponse>`}, want: "id-own"},+ {name: "signed Assertion", signed: []string{assertion("a1", confirmation(`xmlns:InResponseTo="id-other" `+own), advice)}, want: "id-own"},+ {name: "signed Response answering no request", signed: []string{response(`xmlns:InResponseTo="id-own"`, assertion("a1", confirmation(own), ""))}},+ {name: "subject confirmations disagree", signed: []string{assertion("a1", confirmation(own)+confirmation(other), "")}},+ {name: "subject confirmation naming no request", signed: []string{assertion("a1", confirmation(own)+confirmation(`Recipient="x"`), "")}},+ {name: "subject confirmation without data", signed: []string{assertion("a1", confirmation(own)+`<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"/>`, "")}},+ {name: "one subject confirmation with conflicting data", signed: []string{assertion("a1", `<saml:SubjectConfirmation><saml:SubjectConfirmationData `+own+`/><saml:SubjectConfirmationData `+other+`/></saml:SubjectConfirmation>`, "")}},+ {name: "assertion without subject confirmation", signed: []string{assertion("a1", "", advice)}},+ {name: "another signed assertion names the request", signed: []string{assertion("a1", "", ""), assertion("a2", confirmation(own), "")}},+ {name: "returned assertion not signed", signed: []string{assertion("a2", confirmation(own), "")}},+ {name: "two signed assertions share the returned ID", signed: []string{assertion("a1", confirmation(own), ""), assertion("a1", confirmation(own), "")}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ content := &samlSignedContent{}+ for _, doc := range tc.signed {+ content.elements = append(content.elements, parse(doc))+ }+ got, err := content.inResponseTo("a1")+ if tc.want == "" {+ if err == nil {+ t.Fatalf("expected a refusal, got %q", got)+ }+ return+ }+ if err != nil || got != tc.want {+ t.Fatalf("inResponseTo() = %q, %v; want %q", got, err, tc.want)+ }+ })+ }+}++// Signed content may not carry a prefixed attribute or namespace declaration+// named like an un-namespaced attribute crewjam/saml reads; the declarations+// and namespaced attributes real IdPs write are untouched.+func TestSAMLShadowingAttribute(t *testing.T) {+ for _, name := range []string{"ID", "InResponseTo", "IssueInstant", "Destination", "NotBefore", "NotOnOrAfter", "Recipient", "SessionIndex"} {+ if !samlBoundAttributeNames[name] {+ t.Fatalf("expected %s among the attributes crewjam/saml reads, got %v", name, samlBoundAttributeNames)+ }+ }+ for _, prefix := range []string{"saml", "samlp", "saml2", "saml2p", "ds", "dsig", "xs", "xsd", "xsi", "xenc", "ec", "md", "type"} {+ if samlBoundAttributeNames[prefix] {+ t.Fatalf("%q, a namespace prefix or namespaced attribute real IdPs write, is refused", prefix)+ }+ }++ const ns = `xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ext="urn:example"`+ for _, tc := range []struct {+ doc, want string+ }{+ {doc: `<saml:Assertion ` + ns + ` ID="a1"><saml:Conditions xmlns:NotOnOrAfter="2999-01-01T00:00:00Z"/></saml:Assertion>`, want: "xmlns:NotOnOrAfter"},+ {doc: `<saml:Assertion ` + ns + ` ID="a1" ext:ID="a2"/>`, want: "ext:ID"},+ {doc: `<saml:Assertion ` + ns + ` ID="a1"><saml:AttributeStatement><saml:Attribute Name="mail"><saml:AttributeValue xsi:type="xs:string">[email protected]</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion>`},+ } {+ doc := etree.NewDocument()+ if err := doc.ReadFromString(tc.doc); err != nil {+ t.Fatalf("parse %s: %v", tc.doc, err)+ }+ if got := samlShadowingAttribute(doc.Root()); got != tc.want {+ t.Fatalf("samlShadowingAttribute(%s) = %q, want %q", tc.doc, got, tc.want)+ }+ }+}+func TestValidateSAMLRedirectTarget(t *testing.T) {allowed := []saml.Endpoint{{Location: "https://idp.example.com/sso"},