samlsp

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: MPL-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package samlsp owns Hikyo's relying-party policy around SAML parsing and identity material. Cryptographic verification remains the responsibility of the pinned SAML/XML-DSIG libraries; this package makes their policy inputs unambiguous and fail-closed.

Index

Constants

View Source
const (
	SAMLMetadataNamespace = "urn:oasis:names:tc:SAML:2.0:metadata"
	BindingHTTPRedirect   = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
)
View Source
const (
	SAMLProtocolNamespace  = "urn:oasis:names:tc:SAML:2.0:protocol"
	SAMLAssertionNamespace = "urn:oasis:names:tc:SAML:2.0:assertion"
	XMLDSIGNamespace       = "http://www.w3.org/2000/09/xmldsig#"

	SignatureRSASHA256   = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
	SignatureRSASHA384   = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"
	SignatureRSASHA512   = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
	SignatureECDSASHA256 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
	SignatureECDSASHA384 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
	SignatureECDSASHA512 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"

	DigestSHA256 = "http://www.w3.org/2001/04/xmlenc#sha256"
	DigestSHA384 = "http://www.w3.org/2001/04/xmldsig-more#sha384"
	DigestSHA512 = "http://www.w3.org/2001/04/xmlenc#sha512"

	ExclusiveC14N               = "http://www.w3.org/2001/10/xml-exc-c14n#"
	EnvelopedSignatureTransform = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
)
View Source
const (
	DefaultClockSkew   = time.Minute
	DefaultMaxIssueAge = 5 * time.Minute

	SubjectConfirmationBearer = "urn:oasis:names:tc:SAML:2.0:cm:bearer"
)
View Source
const (
	MaxDocumentBytes = 256 << 10
	MaxElementDepth  = 32
	MaxXMLTokens     = 50_000
)

Variables

View Source
var (
	ErrMetadataRoot               = errors.New("samlsp: root is not SAML metadata")
	ErrMetadataEntityCardinality  = errors.New("samlsp: metadata must contain exactly one matching EntityDescriptor")
	ErrMetadataIDPDescriptor      = errors.New("samlsp: metadata must contain exactly one SAML 2.0 IDPSSODescriptor")
	ErrMetadataSSOEndpoint        = errors.New("samlsp: metadata must contain exactly one HTTP-Redirect SSO endpoint")
	ErrMetadataSigningCertificate = errors.New("samlsp: metadata has no usable assertion-signing certificate")
	ErrMetadataValidUntil         = errors.New("samlsp: invalid metadata validUntil")
	ErrMetadataSignature          = errors.New("samlsp: invalid metadata signature")
	ErrMetadataCertificateKey     = errors.New("samlsp: metadata certificate uses a weak or unsupported public key")
)
View Source
var (
	ErrEmptyNameID           = errors.New("samlsp: NameID value is empty")
	ErrNameIDTooLarge        = errors.New("samlsp: NameID value is too large")
	ErrInvalidNameIDEncoding = errors.New("samlsp: invalid encoded NameID")
)
View Source
var (
	ErrInvalidAuthnRequestConfig = errors.New("samlsp: invalid AuthnRequest configuration")
	ErrAuthnRequestSigningKey    = errors.New("samlsp: AuthnRequest signing requires a matching RSA key and certificate")
)
View Source
var (
	ErrResponseRoot              = errors.New("samlsp: root is not a SAML Response")
	ErrAssertionCardinality      = errors.New("samlsp: Response must contain exactly one Assertion")
	ErrAssertionPosition         = errors.New("samlsp: Assertion must be a direct child of Response")
	ErrEncryptedAssertion        = errors.New("samlsp: encrypted assertions are unsupported")
	ErrSignatureStructure        = errors.New("samlsp: invalid signature structure")
	ErrSignatureReference        = errors.New("samlsp: signature Reference does not cover its exact element")
	ErrSignatureAlgorithm        = errors.New("samlsp: disallowed signature algorithm")
	ErrDigestAlgorithm           = errors.New("samlsp: disallowed digest algorithm")
	ErrCanonicalizationAlgorithm = errors.New("samlsp: disallowed canonicalization algorithm")
	ErrTransformAlgorithm        = errors.New("samlsp: disallowed signature transform")
)
View Source
var (
	ErrInvalidExpectations              = errors.New("samlsp: invalid validation expectations")
	ErrNoPinnedCertificate              = errors.New("samlsp: no pinned signing certificate")
	ErrAssertionSignature               = errors.New("samlsp: assertion signature verification failed")
	ErrResponseSignature                = errors.New("samlsp: response signature verification failed")
	ErrResponseStatus                   = errors.New("samlsp: Response status is not success")
	ErrResponseIssuer                   = errors.New("samlsp: invalid Response Issuer")
	ErrAssertionIssuer                  = errors.New("samlsp: invalid Assertion Issuer")
	ErrInResponseTo                     = errors.New("samlsp: invalid InResponseTo")
	ErrDestination                      = errors.New("samlsp: invalid Destination")
	ErrAudience                         = errors.New("samlsp: invalid AudienceRestriction")
	ErrAudienceMissing                  = errors.New("samlsp: AudienceRestriction is missing")
	ErrAudienceMismatch                 = errors.New("samlsp: AudienceRestriction does not contain the SP entityID")
	ErrNameIDCardinality                = errors.New("samlsp: Assertion must contain exactly one NameID")
	ErrSubjectConfirmation              = errors.New("samlsp: invalid bearer SubjectConfirmation")
	ErrSubjectConfirmationMissing       = errors.New("samlsp: bearer SubjectConfirmation is missing or duplicated")
	ErrSubjectConfirmationMethod        = errors.New("samlsp: unsupported SubjectConfirmation method")
	ErrSubjectConfirmationRecipient     = errors.New("samlsp: SubjectConfirmationData Recipient mismatch")
	ErrSubjectConfirmationInResponseTo  = errors.New("samlsp: SubjectConfirmationData InResponseTo mismatch")
	ErrSubjectConfirmationExpiryMissing = errors.New("samlsp: SubjectConfirmationData NotOnOrAfter is missing")
	ErrSubjectConfirmationExpired       = errors.New("samlsp: SubjectConfirmationData has expired")
	ErrConditions                       = errors.New("samlsp: invalid Conditions")
	ErrConditionsMissing                = errors.New("samlsp: Conditions is missing or duplicated")
	ErrConditionsNotBefore              = errors.New("samlsp: Conditions NotBefore is invalid or too early")
	ErrConditionsExpiryMissing          = errors.New("samlsp: Conditions NotOnOrAfter is missing")
	ErrConditionsExpired                = errors.New("samlsp: Conditions has expired")
	ErrIssueInstant                     = errors.New("samlsp: invalid IssueInstant")
	ErrResponseIssueInstant             = errors.New("samlsp: invalid Response IssueInstant")
	ErrAssertionIssueInstant            = errors.New("samlsp: invalid Assertion IssueInstant")
	ErrAuthnStatementCardinality        = errors.New("samlsp: Assertion must contain exactly one AuthnStatement")
	ErrAuthnContextCardinality          = errors.New("samlsp: AuthnStatement must contain at most one AuthnContextClassRef")
	ErrInvalidAuthnInstant              = errors.New("samlsp: invalid AuthnInstant")
)
View Source
var (
	ErrDocumentTooLarge = errors.New("samlsp: XML document exceeds 256 KiB")
	ErrDocumentTooDeep  = errors.New("samlsp: XML element depth exceeds 32")
	ErrTooManyTokens    = errors.New("samlsp: XML token count exceeds 50000")
	ErrDTD              = errors.New("samlsp: DTD declarations are forbidden")
	ErrMalformedXML     = errors.New("samlsp: malformed XML document")
	ErrRoundTrip        = errors.New("samlsp: XML round-trip validation failed")
	ErrDuplicateID      = errors.New("samlsp: duplicate XML ID")
	ErrEmptyID          = errors.New("samlsp: empty XML ID")
)

Functions

func EncodeNameID

func EncodeNameID(id NameID) ([]byte, error)

EncodeNameID returns the injective subject encoding fixed by the SAML ADR. Each field is presence-byte || uint32-big-endian-length || bytes. Value is mandatory and therefore always present; optional attributes retain presence.

Types

type AuthnClaims

type AuthnClaims struct {
	Instant         time.Time
	ContextClassRef *string
}

type AuthnRequest

type AuthnRequest struct {
	URL       string
	RequestID string
}

func BuildAuthnRequest

func BuildAuthnRequest(config AuthnRequestConfig) (AuthnRequest, error)

BuildAuthnRequest builds the profile's HTTP-Redirect AuthnRequest. gosaml2 owns XML construction, DEFLATE encoding, and Redirect-binding signing. The request document is deliberately built without an enveloped XML signature; when requested, gosaml2 signs the exact encoded query values sent on wire.

type AuthnRequestConfig

type AuthnRequestConfig struct {
	IDPSSOURL   string
	SPEntityID  string
	ACSURL      string
	RelayState  string
	ForceAuthn  bool
	Sign        bool
	Signer      crypto.Signer
	Certificate []byte
	Now         time.Time
}

type Claims

type Claims struct {
	ResponseID               string
	AssertionID              string
	ResponseIssuer           string
	AssertionIssuer          string
	InResponseTo             string
	Destination              string
	ResponseIssueInstant     time.Time
	AssertionIssueInstant    time.Time
	NameID                   NameID
	Audiences                []string
	SubjectConfirmation      SubjectConfirmationClaims
	Conditions               ConditionsClaims
	Authn                    AuthnClaims
	ExpiredPinnedCertificate bool
}

Claims contains only fields extracted from the exact assertion node returned by goxmldsig, plus envelope fields from the sole bounded etree document (or the verified Response node when an optional envelope signature is present).

func ValidateResponse

func ValidateResponse(raw []byte, certificates []*x509.Certificate, expected ValidationExpectations) (Claims, error)

ValidateResponse performs the ADR's structural checks, verifies the exact Assertion and optional Response nodes against raw pinned certificates, then extracts and validates policy fields from those same nodes.

type ConditionsClaims

type ConditionsClaims struct {
	NotBefore    *time.Time
	NotOnOrAfter time.Time
}

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document is one bounded XML parse tree. Policy validation and extraction consume this tree so callers never need a second, potentially divergent, parse of attacker-controlled bytes.

func ParseXML

func ParseXML(raw []byte) (*Document, error)

ParseXML applies the ADR's resource bounds and DTD/ID refusals while constructing the one tree used by every later policy check.

type Metadata

type Metadata struct {
	EntityID                string
	SSOURL                  string
	WantAuthnRequestsSigned bool
	SigningCertificates     []*x509.Certificate
	ValidUntil              *time.Time
	Signed                  bool
	SignatureCertificate    *x509.Certificate
}

Metadata is the provider material extracted from one bounded etree. When a metadata signature exists, fields come from the exact descriptor within the subtree returned by goxmldsig. SignatureCertificate is the self-verified key candidate; the caller must compare or explicitly confirm its fingerprint before applying configuration.

func ParseMetadata

func ParseMetadata(raw []byte, entityID string) (Metadata, error)

ParseMetadata selects one exact IdP entity. Signed metadata is cryptographically self-verified and structurally bound to the selected descriptor; this does not establish trust in a first-seen signing key.

type NameID

type NameID struct {
	Value           []byte
	Format          *string
	NameQualifier   *string
	SPNameQualifier *string
}

NameID is the byte-exact identity material extracted from a verified SAML Assertion. Pointers preserve the difference between an absent XML attribute and one explicitly present with an empty value.

func DecodeNameID

func DecodeNameID(encoded []byte) (NameID, error)

DecodeNameID reverses EncodeNameID without normalizing any field. Invalid presence bits, absent fields carrying bytes, truncation and trailing data fail closed, so only the existing injective representation is accepted.

type Response

type Response struct {
	// contains filtered or unexported fields
}

Response is a structurally validated SAML response. It retains the exact Assertion node from Document's sole etree parse for signature verification.

func ParseResponse

func ParseResponse(raw []byte) (*Response, error)

ParseResponse bounds and parses raw once, then applies the complete structural XSW and algorithm-URI policy before cryptographic verification.

type SubjectConfirmationClaims

type SubjectConfirmationClaims struct {
	Method       string
	Recipient    string
	InResponseTo string
	NotOnOrAfter time.Time
}

type ValidationExpectations

type ValidationExpectations struct {
	ProviderEntityID string
	SPEntityID       string
	ACSURL           string
	RequestID        string
	Now              time.Time
	ClockSkew        time.Duration
	MaxIssueAge      time.Duration
}

ValidationExpectations binds a signed assertion to the provider, SP, ACS, and server-side request selected before parsing the response. Now is always supplied by the caller so SAML freshness never shares goxmldsig's synthetic certificate-validity clock.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL