Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for POST on a wrapped request #534

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
53 changes: 45 additions & 8 deletions samlsp/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package samlsp
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"net/http"

"github.com/crewjam/saml"
Expand Down Expand Up @@ -193,33 +195,68 @@ func (m *Middleware) HandleStartAuthFlow(w http.ResponseWriter, r *http.Request)

// CreateSessionFromAssertion is invoked by ServeHTTP when we have a new, valid SAML assertion.
func (m *Middleware) CreateSessionFromAssertion(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion, redirectURI string) {
var err error

trackedRequest := &TrackedRequest{
Method: "GET",
URI: redirectURI,
}

if trackedRequestIndex := r.Form.Get("RelayState"); trackedRequestIndex != "" {
trackedRequest, err := m.RequestTracker.GetTrackedRequest(r, trackedRequestIndex)
trackedRequest, err = m.RequestTracker.GetTrackedRequest(r, trackedRequestIndex)
if err != nil {
if err == http.ErrNoCookie && m.ServiceProvider.AllowIDPInitiated {
if uri := r.Form.Get("RelayState"); uri != "" {
redirectURI = uri
if errors.Is(err, http.ErrNoCookie) && m.ServiceProvider.AllowIDPInitiated {
// We don't need to re-read RelayState from the form and check it for nil. The test above did that
trackedRequest = &TrackedRequest{
Method: "GET",
URI: trackedRequestIndex,
}
} else {
m.OnError(w, r, err)
return
}
} else {
if err := m.RequestTracker.StopTrackingRequest(w, r, trackedRequestIndex); err != nil {
if err = m.RequestTracker.StopTrackingRequest(w, r, trackedRequestIndex); err != nil {
m.OnError(w, r, err)
return
}

redirectURI = trackedRequest.URI
}
}

if err := m.Session.CreateSession(w, r, assertion); err != nil {
m.OnError(w, r, err)
return
}
m.HandleRedirectAfterAssertion(w, r, trackedRequest)
}

// HandleRedirectAfterAssertion is called after we've handled receiving a SAML assertion and created a session with the
// browser. Most normal cases are just a redirect, but if the original request was a POST, it's a little more tricky.
func (m *Middleware) HandleRedirectAfterAssertion(w http.ResponseWriter, r *http.Request, trackedRequest *TrackedRequest) {
switch trackedRequest.Method {
case "POST":
text := fmt.Sprintf(`<html>`+
`<form method="post" action="%s" id="SAMLAfterAssertionRedirectForm">`, trackedRequest.URI)
for key, values := range trackedRequest.PostData {
for _, value := range values {
text = fmt.Sprintf(`%s<input type="hidden" name="%s" value="%s" />`, text, key, value)
}
}
text += `<input id="SAMLAfterAssertionRedirectSubmitButton" type="submit" value="Continue" />` +
`</form>` +
`<script>document.getElementById('SAMLAfterAssertionRedirectSubmitButton').style.visibility='hidden';</script>` +
`<script>document.getElementById('SAMLAfterAssertionRedirectForm').submit();</script>` +
`</html>`
Comment on lines +238 to +249
Copy link

@patricsss patricsss Oct 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be great to live in a template and then be rendered with the placeholders.

https://pkg.go.dev/text/template

That would also let you abstract this away into another file either as a constant-string-literal or as an actual text file that can be embedded and read from something like an embed.FS. I would strongly recommend the string literal though if you opt for this approach.

The template package supports the nested looping you're doing here "out of the box".

This would also make it considerably easier to write tests to ensure the form generated is as expected as the templating could be more easily tested than this method which has farm more state in it.


http.Redirect(w, r, redirectURI, http.StatusFound)
if _, err := w.Write([]byte(text)); err != nil {
m.OnError(w, r, err)
return
}
return
// TODO: Handle HEAD, DELETE, etc.
default:
http.Redirect(w, r, trackedRequest.URI, http.StatusFound)
}
}

// RequireAttribute returns a middleware function that requires that the
Expand Down
1 change: 1 addition & 0 deletions samlsp/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func (test *MiddlewareTest) makeTrackedRequest(id string) string {
Index: "KCosLjAyNDY4Ojw-QEJERkhKTE5QUlRWWFpcXmBiZGZoamxucHJ0dnh6",
SAMLRequestID: id,
URI: "/frob",
Method: "GET",
})
if err != nil {
panic(err)
Expand Down
9 changes: 6 additions & 3 deletions samlsp/request_tracker.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package samlsp

import (
"net/http"
"net/url"
)

// RequestTracker tracks pending authentication requests.
Expand Down Expand Up @@ -31,9 +32,11 @@ type RequestTracker interface {

// TrackedRequest holds the data we store for each pending request.
type TrackedRequest struct {
Index string `json:"-"`
SAMLRequestID string `json:"id"`
URI string `json:"uri"`
Index string `json:"-"`
SAMLRequestID string `json:"id"`
URI string `json:"uri"`
Method string `json:"method"`
PostData url.Values `json:"post_data"`
}

// TrackedRequestCodec handles encoding and decoding of a TrackedRequest.
Expand Down
7 changes: 7 additions & 0 deletions samlsp/request_tracker_cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,17 @@ type CookieRequestTracker struct {
// TrackRequest starts tracking the SAML request with the given ID. It returns an
// `index` that should be used as the RelayState in the SAMl request flow.
func (t CookieRequestTracker) TrackRequest(w http.ResponseWriter, r *http.Request, samlRequestID string) (string, error) {
if r.Method == "POST" {
if err := r.ParseForm(); err != nil {
return "", err
}
}
trackedRequest := TrackedRequest{
Index: base64.RawURLEncoding.EncodeToString(randomBytes(42)),
SAMLRequestID: samlRequestID,
URI: r.URL.String(),
Method: r.Method,
PostData: r.PostForm,
}

if t.RelayStateFunc != nil {
Expand Down