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

artifact binding support #46

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
98 changes: 98 additions & 0 deletions artifact.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package saml2

import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"strings"

"github.com/beevik/etree"
"github.com/russellhaering/gosaml2/uuid"
)

func (sp *SAMLServiceProvider) ResolveArtifact(artifact string) (*AssertionInfo, error) {
if sp.HTTPClient == nil {
return nil, errors.New("HTTPClient must be set for artifact binding")
}
request, err := sp.buildResolveRequest(artifact)
if err != nil {
return nil, err
}
post, err := http.NewRequest("POST", sp.IdentityProviderArtifactResolutionServiceURL, request)
if err != nil {
return nil, err
}
post.Header.Add("Content-Type", "text/xml")
post.Header.Add("SOAPAction", "http://www.oasis-open.org/committees/security")
resp, err := sp.HTTPClient.Do(post)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code from artifact resolve request %d", resp.StatusCode)
}
// Buffer the response and base64 encode it.
// It's not ideal, but existing parsing methods expect it to be encoded.
// Attempting to minimize change for now.
doc := etree.NewDocument()
doc.ReadFrom(resp.Body)
el := doc.FindElement("./Envelope/Body/ArtifactResponse/Response")
doc = etree.NewDocument()
doc.SetRoot(el)
var buffer bytes.Buffer
encoder := base64.NewEncoder(base64.StdEncoding, &buffer)
doc.WriteTo(encoder)
encoder.Close()
return sp.RetrieveAssertionInfo(buffer.String())
}

func (sp *SAMLServiceProvider) buildResolveRequest(artifact string) (io.Reader, error) {
envelope := &etree.Element{
Space: "soap-env",
Tag: "Envelope",
}
envelope.CreateAttr("xmlns:soap-env", "http://schemas.xmlsoap.org/soap/envelope/")
body := envelope.CreateElement("soap-env:Body")
artifactResolve := &etree.Element{
Space: "samlp",
Tag: "ArtifactResolve",
}
artifactResolve.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol")
artifactResolve.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion")

arID := uuid.NewV4()
artifactResolve.CreateAttr("ID", "_"+arID.String())
artifactResolve.CreateAttr("Version", "2.0")
artifactResolve.CreateAttr("IssueInstant", sp.Clock.Now().UTC().Format(issueInstantFormat))

// NOTE(russell_h): In earlier versions we mistakenly sent the IdentityProviderIssuer
// in the AuthnRequest. For backwards compatibility we will fall back to that
// behavior when ServiceProviderIssuer isn't set.
if sp.ServiceProviderIssuer != "" {
artifactResolve.CreateElement("saml:Issuer").SetText(sp.ServiceProviderIssuer)
} else {
artifactResolve.CreateElement("saml:Issuer").SetText(sp.IdentityProviderIssuer)
}

artifactResolve.CreateElement("samlp:Artifact").SetText(artifact)

// TODO should really change this method name
signed, err := sp.SignAuthnRequest(artifactResolve)
if err != nil {
return nil, err
}

body.AddChild(signed)
doc := etree.NewDocument()
doc.SetRoot(envelope)
message, err := doc.WriteToString()
if err != nil {
return nil, err
}

return strings.NewReader(message), nil
}
41 changes: 41 additions & 0 deletions artifact_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package saml2

import (
"io"
"os"
"testing"

"github.com/beevik/etree"
dsig "github.com/russellhaering/goxmldsig"
"github.com/stretchr/testify/require"
)

func TestArtifact(t *testing.T) {
spURL := "https://sp.test"
randomKeyStore := dsig.RandomKeyStoreForTest()
sp := SAMLServiceProvider{
AssertionConsumerServiceURL: spURL,
AudienceURI: spURL,
ServiceProviderIssuer: spURL,
IdentityProviderSSOURL: "https://idp.test/saml/sso",
SignAuthnRequests: true,
SPKeyStore: randomKeyStore,
}
req, err := sp.buildResolveRequest("1234567")
if err != nil {
t.Fatal(err)
}

doc := etree.NewDocument()
_, err = doc.ReadFrom(req)
require.NoError(t, err)

// Make sure request is signed
el := doc.FindElement("./Envelope/Body/ArtifactResolve/Signature")
require.NotNil(t, el)
// Make sure artifact is set
el = doc.FindElement("./Envelope/Body/ArtifactResolve/Artifact")
require.NotNil(t, el)
require.Equal(t, "1234567", el.Text())
io.Copy(os.Stdout, req)
}
11 changes: 9 additions & 2 deletions build_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,14 @@ func (sp *SAMLServiceProvider) buildAuthnRequest(includeSig bool) (*etree.Docume

authnRequest.CreateAttr("ID", "_"+arId.String())
authnRequest.CreateAttr("Version", "2.0")
authnRequest.CreateAttr("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")
switch sp.RequestedBinding {
case "", BindingHttpPost:
authnRequest.CreateAttr("ProtocolBinding", BindingHttpPost)
case BindingHttpArtifact:
authnRequest.CreateAttr("ProtocolBinding", BindingHttpArtifact)
default:
return nil, fmt.Errorf("invalid RequestedBinding, %s", sp.RequestedBinding)
}
authnRequest.CreateAttr("AssertionConsumerServiceURL", sp.AssertionConsumerServiceURL)
authnRequest.CreateAttr("IssueInstant", sp.Clock.Now().UTC().Format(issueInstantFormat))
authnRequest.CreateAttr("Destination", sp.IdentityProviderSSOURL)
Expand Down Expand Up @@ -179,7 +186,7 @@ func (sp *SAMLServiceProvider) BuildAuthURL(relayState string) (string, error) {
if err != nil {
return "", err
}
return sp.BuildAuthURLFromDocument(relayState, doc)
return sp.BuildAuthURLRedirect(relayState, doc)
}

// AuthRedirect takes a ResponseWriter and Request from an http interaction and
Expand Down
12 changes: 10 additions & 2 deletions saml.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package saml2

import (
"encoding/base64"
"net/http"
"sync"
"time"

Expand All @@ -23,15 +24,17 @@ func (serr ErrSaml) Error() string {
}

type SAMLServiceProvider struct {
IdentityProviderSSOURL string
IdentityProviderIssuer string
IdentityProviderSSOURL string
IdentityProviderIssuer string
IdentityProviderArtifactResolutionServiceURL string

AssertionConsumerServiceURL string
ServiceProviderIssuer string

SignAuthnRequests bool
SignAuthnRequestsAlgorithm string
SignAuthnRequestsCanonicalizer dsig.Canonicalizer
RequestedBinding string

// RequestedAuthnContext allows service providers to require that the identity
// provider use specific authentication mechanisms. Leaving this unset will
Expand All @@ -42,6 +45,7 @@ type SAMLServiceProvider struct {
IDPCertificateStore dsig.X509CertificateStore
SPKeyStore dsig.X509KeyStore // Required encryption key, default signing key
SPSigningKeyStore dsig.X509KeyStore // Optional signing key
HTTPClient *http.Client // Optional client for artifact resolution
NameIdFormat string
ValidateEncryptionCert bool
SkipSignatureValidation bool
Expand Down Expand Up @@ -114,6 +118,10 @@ func (sp *SAMLServiceProvider) Metadata() (*types.EntityDescriptor, error) {
Binding: BindingHttpPost,
Location: sp.AssertionConsumerServiceURL,
Index: 1,
}, {
Binding: BindingHttpArtifact,
Location: sp.AssertionConsumerServiceURL,
Index: 2,
}},
},
}, nil
Expand Down
13 changes: 7 additions & 6 deletions types/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,13 @@ type SPSSODescriptor struct {
}

type IDPSSODescriptor struct {
XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:metadata IDPSSODescriptor"`
WantAuthnRequestsSigned bool `xml:"WantAuthnRequestsSigned,attr"`
KeyDescriptors []KeyDescriptor `xml:"KeyDescriptor"`
NameIDFormats []NameIDFormat `xml:"NameIDFormat"`
SingleSignOnServices []SingleSignOnService `xml:"SingleSignOnService"`
Attributes []Attribute `xml:"Attribute"`
XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:metadata IDPSSODescriptor"`
WantAuthnRequestsSigned bool `xml:"WantAuthnRequestsSigned,attr"`
KeyDescriptors []KeyDescriptor `xml:"KeyDescriptor"`
ArtifactResolutionService IndexedEndpoint
NameIDFormats []NameIDFormat `xml:"NameIDFormat"`
SingleSignOnServices []SingleSignOnService `xml:"SingleSignOnService"`
Attributes []Attribute `xml:"Attribute"`
}

type KeyDescriptor struct {
Expand Down
1 change: 1 addition & 0 deletions xml_constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const (

BindingHttpPost = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
BindingHttpRedirect = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
BindingHttpArtifact = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
)

const (
Expand Down