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 caching support to IDPMetadata() #102

Merged
merged 6 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions saml/authn_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ func WithClock(clock clockwork.Clock) Option {
opts.clock = clock
case *parseResponseOptions:
opts.clock = clock
case *idpMetadataOptions:
opts.clock = clock
}
}
}
Expand Down
128 changes: 128 additions & 0 deletions saml/models/metadata/duration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package metadata
remilapeyre marked this conversation as resolved.
Show resolved Hide resolved

import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)

// Duration is a time.Duration that uses the xsd:duration format for text
// marshalling and unmarshalling.
type Duration time.Duration

// MarshalText implements the encoding.TextMarshaler interface.
func (d Duration) MarshalText() ([]byte, error) {
if d == 0 {
return nil, nil
}

out := "PT"
if d < 0 {
d *= -1
out = "-" + out
}

h := time.Duration(d) / time.Hour
m := time.Duration(d) % time.Hour / time.Minute
s := time.Duration(d) % time.Minute / time.Second
ns := time.Duration(d) % time.Second
if h > 0 {
out += fmt.Sprintf("%dH", h)
}
if m > 0 {
out += fmt.Sprintf("%dM", m)
}
if s > 0 || ns > 0 {
out += fmt.Sprintf("%d", s)
if ns > 0 {
out += strings.TrimRight(fmt.Sprintf(".%09d", ns), "0")
}
out += "S"
}

return []byte(out), nil
}

const (
day = 24 * time.Hour
month = 30 * day // Assumed to be 30 days.
year = 365 * day // Assumed to be non-leap year.
)

var (
durationRegexp = regexp.MustCompile(`^(-?)P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(.+))?$`)
durationTimeRegexp = regexp.MustCompile(`^(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?$`)
)

// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (d *Duration) UnmarshalText(text []byte) error {
if text == nil {
*d = 0
return nil
}

var (
out time.Duration
sign time.Duration = 1
)
match := durationRegexp.FindStringSubmatch(string(text))
if match == nil || strings.Join(match[2:6], "") == "" {
return fmt.Errorf("invalid duration (%s)", text)
}
if match[1] == "-" {
sign = -1
}
if match[2] != "" {
y, err := strconv.Atoi(match[2])
if err != nil {
return fmt.Errorf("invalid duration years (%s): %s", text, err)
}
out += time.Duration(y) * year
}
if match[3] != "" {
m, err := strconv.Atoi(match[3])
if err != nil {
return fmt.Errorf("invalid duration months (%s): %s", text, err)
}
out += time.Duration(m) * month
}
if match[4] != "" {
d, err := strconv.Atoi(match[4])
if err != nil {
return fmt.Errorf("invalid duration days (%s): %s", text, err)
}
out += time.Duration(d) * day
}
if match[5] != "" {
match := durationTimeRegexp.FindStringSubmatch(match[5])
if match == nil {
return fmt.Errorf("invalid duration (%s)", text)
}
if match[1] != "" {
h, err := strconv.Atoi(match[1])
if err != nil {
return fmt.Errorf("invalid duration hours (%s): %s", text, err)
}
out += time.Duration(h) * time.Hour
}
if match[2] != "" {
m, err := strconv.Atoi(match[2])
if err != nil {
return fmt.Errorf("invalid duration minutes (%s): %s", text, err)
}
out += time.Duration(m) * time.Minute
}
if match[3] != "" {
s, err := strconv.ParseFloat(match[3], 64)
if err != nil {
return fmt.Errorf("invalid duration seconds (%s): %s", text, err)
}
out += time.Duration(s * float64(time.Second))
}
}

*d = Duration(sign * out)
return nil
}
84 changes: 84 additions & 0 deletions saml/models/metadata/duration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package metadata

import (
"errors"
"strconv"
"testing"
"time"

"github.com/stretchr/testify/require"
)

var durationMarshalTests = []struct {
in time.Duration
expected []byte
}{
{0, nil},
{time.Nanosecond, []byte("PT0.000000001S")},
{time.Millisecond, []byte("PT0.001S")},
{time.Second, []byte("PT1S")},
{time.Minute, []byte("PT1M")},
{time.Hour, []byte("PT1H")},
{-time.Hour, []byte("-PT1H")},
{2*time.Hour + 3*time.Minute + 4*time.Second + 5*time.Nanosecond, []byte("PT2H3M4.000000005S")},
}

func TestDuration(t *testing.T) {
for i, testCase := range durationMarshalTests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
actual, err := Duration(testCase.in).MarshalText()
require.NoError(t, err)
require.Equal(t, testCase.expected, actual)
})
}
}

var durationUnmarshalTests = []struct {
in []byte
expected time.Duration
err error
}{
{nil, 0, nil},
{[]byte("PT0.0000000001S"), 0, nil},
{[]byte("PT0.000000001S"), time.Nanosecond, nil},
{[]byte("PT0.001S"), time.Millisecond, nil},
{[]byte("PT1S"), time.Second, nil},
{[]byte("PT1M"), time.Minute, nil},
{[]byte("PT1H"), time.Hour, nil},
{[]byte("-PT1H"), -time.Hour, nil},
{[]byte("P1D"), 24 * time.Hour, nil},
{[]byte("P1M"), 720 * time.Hour, nil},
{[]byte("P1Y"), 8760 * time.Hour, nil},
{[]byte("P2Y3M4DT5H6M7.000000008S"), 19781*time.Hour + 6*time.Minute + 7*time.Second + 8*time.Nanosecond, nil},
{[]byte("P0Y0M0DT0H0M0S"), 0, nil},
{[]byte("PT0001.0000S"), time.Second, nil},
{[]byte(""), 0, errors.New("invalid duration ()")},
{[]byte("12345"), 0, errors.New("invalid duration (12345)")},
{[]byte("P1D1M1Y"), 0, errors.New("invalid duration (P1D1M1Y)")},
{[]byte("P1H1M1S"), 0, errors.New("invalid duration (P1H1M1S)")},
{[]byte("PT1S1M1H"), 0, errors.New("invalid duration (PT1S1M1H)")},
{[]byte(" P1Y "), 0, errors.New("invalid duration ( P1Y )")},
{[]byte("P"), 0, errors.New("invalid duration (P)")},
{[]byte("-P"), 0, errors.New("invalid duration (-P)")},
{[]byte("PT"), 0, errors.New("invalid duration (PT)")},
{[]byte("P1YMD"), 0, errors.New("invalid duration (P1YMD)")},
{[]byte("P1YT"), 0, errors.New("invalid duration (P1YT)")},
{[]byte("P-1Y"), 0, errors.New("invalid duration (P-1Y)")},
{[]byte("P1.5Y"), 0, errors.New("invalid duration (P1.5Y)")},
{[]byte("PT1.S"), 0, errors.New("invalid duration (PT1.S)")},
}

func TestDurationUnmarshal(t *testing.T) {
for i, testCase := range durationUnmarshalTests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
var actual Duration
err := actual.UnmarshalText(testCase.in)
if testCase.err == nil {
require.NoError(t, err)
} else {
require.ErrorContains(t, err, testCase.err.Error())
}
require.Equal(t, Duration(testCase.expected), actual)
})
}
}
6 changes: 3 additions & 3 deletions saml/models/metadata/entity_descriptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ const (

// DescriptorCommon defines common fields used in Entity- and EntitiesDescriptor.
type DescriptorCommon struct {
ID string `xml:",attr,omitempty"`
ValidUntil *time.Time `xml:"validUntil,attr,omitempty"`
CacheDuration time.Duration `xml:"cacheDuration,attr,omitempty"`
ID string `xml:",attr,omitempty"`
ValidUntil *time.Time `xml:"validUntil,attr,omitempty"`
CacheDuration *Duration `xml:"cacheDuration,attr,omitempty"`
Signature *dsig.Signature
}

Expand Down
104 changes: 101 additions & 3 deletions saml/sp.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ import (
"io"
"net/http"
"net/url"
"sync"
"time"

"github.com/hashicorp/cap/saml/models/core"
"github.com/hashicorp/cap/saml/models/metadata"
"github.com/jonboulle/clockwork"
dsig "github.com/russellhaering/goxmldsig/types"
)

Expand Down Expand Up @@ -82,6 +85,10 @@ func WithAdditionalACSEndpoint(b core.ServiceBinding, location *url.URL) Option

type ServiceProvider struct {
cfg *Config

metadata *metadata.EntityDescriptorIDPSSO
metadataCachedUntil *time.Time
metadataLock sync.Mutex
}

// NewServiceProvider creates a new ServiceProvider.
Expand Down Expand Up @@ -157,21 +164,101 @@ func (sp *ServiceProvider) CreateMetadata(opt ...Option) *metadata.EntityDescrip
return &spsso
}

type idpMetadataOptions struct {
cache bool
useStale bool
clock clockwork.Clock
}

func idpMetadataOptionsDefault() idpMetadataOptions {
return idpMetadataOptions{
cache: true,
useStale: false,
clock: clockwork.NewRealClock(),
}
}

func getIDPMetadataOptions(opt ...Option) idpMetadataOptions {
opts := idpMetadataOptionsDefault()
ApplyOpts(&opts, opt...)
return opts
}

// WithCache control whether we should cache IDP Metadata.
func WithCache(cache bool) Option {
return func(o interface{}) {
if o, ok := o.(*idpMetadataOptions); ok {
o.cache = cache
}
}
}

// WithStale control whether we should use a stale IDP Metadata document if
// refreshing it fails.
func WithStale(stale bool) Option {
return func(o interface{}) {
if o, ok := o.(*idpMetadataOptions); ok {
o.useStale = stale
}
}
}

// IDPMetadata fetches the metadata XML document from the configured identity provider.
func (sp *ServiceProvider) IDPMetadata() (*metadata.EntityDescriptorIDPSSO, error) {
// Options:
// - WithClock
// - WithCache
// - WithStale
func (sp *ServiceProvider) IDPMetadata(opt ...Option) (*metadata.EntityDescriptorIDPSSO, error) {
const op = "saml.ServiceProvider.FetchIDPMetadata"

opts := getIDPMetadataOptions(opt...)

var err error
var ed *metadata.EntityDescriptorIDPSSO

isValid := func(md *metadata.EntityDescriptorIDPSSO) bool {
if md == nil {
return false
}
if md.ValidUntil == nil {
return true
}
return opts.clock.Now().Before(*md.ValidUntil)
}

isAlive := func(md *metadata.EntityDescriptorIDPSSO, expireAt *time.Time) bool {
if md == nil || !opts.cache || expireAt == nil {
return false
}

return opts.clock.Now().Before(*expireAt)
}

if opts.cache {
// We only take the lock when caching is enabled so that requests can be
// done concurrently when it is not
sp.metadataLock.Lock()
defer sp.metadataLock.Unlock()

if !isValid(sp.metadata) {
remilapeyre marked this conversation as resolved.
Show resolved Hide resolved
sp.metadata = nil
sp.metadataCachedUntil = nil
} else if isAlive(sp.metadata, sp.metadataCachedUntil) {
return sp.metadata, nil
}
}

// Order of switch case determines IDP metadata config precedence
switch {
case sp.cfg.MetadataURL != "":
ed, err = fetchIDPMetadata(sp.cfg.MetadataURL)
if err != nil {
if err != nil && opts.useStale && isValid(sp.metadata) {
remilapeyre marked this conversation as resolved.
Show resolved Hide resolved
// An error occured but we have a cached metadata document that
remilapeyre marked this conversation as resolved.
Show resolved Hide resolved
// we can use
return sp.metadata, nil
} else if err != nil {
return nil, fmt.Errorf("%s: %w", op, err)
}
return ed, nil

case sp.cfg.MetadataXML != "":
ed, err = parseIDPMetadata([]byte(sp.cfg.MetadataXML))
Expand All @@ -189,6 +276,17 @@ func (sp *ServiceProvider) IDPMetadata() (*metadata.EntityDescriptorIDPSSO, erro
return nil, fmt.Errorf("%s: no IDP metadata configuration set: %w", op, ErrInvalidParameter)
}

if !isValid(ed) {
return nil, fmt.Errorf("the IDP configuration was only valid until %s", ed.ValidUntil.Format(time.RFC3339))
}

sp.metadata = ed
sp.metadataCachedUntil = nil
if sp.metadata.CacheDuration != nil {
cachedUntil := opts.clock.Now().Add(time.Duration(*sp.metadata.CacheDuration))
sp.metadataCachedUntil = &cachedUntil
}

return ed, err
}

Expand Down
Loading
Loading