Add SAML support

Signed-off-by: Bryan Frimin <bryan@getprobo.com>
This commit is contained in:
Bryan Frimin
2025-10-29 18:42:12 +01:00
parent 3018a3e691
commit 2766f8e423
97 changed files with 14824 additions and 2812 deletions

113
pkg/auth/saml_cleanup.go Normal file
View File

@@ -0,0 +1,113 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"context"
"time"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
)
const (
DefaultCleanupInterval = 1 * time.Hour
)
type (
Cleaner struct {
pg *pg.Client
interval time.Duration
logger *log.Logger
}
)
func NewCleaner(
pg *pg.Client,
interval time.Duration,
logger *log.Logger,
) *Cleaner {
if interval == 0 {
interval = DefaultCleanupInterval
}
return &Cleaner{
pg: pg,
interval: interval,
logger: logger.Named("saml.cleaner"),
}
}
func (c *Cleaner) Run(ctx context.Context) error {
c.logger.InfoCtx(ctx, "SAML cleaner starting", log.Duration("interval", c.interval))
if err := c.cleanup(ctx); err != nil {
c.logger.ErrorCtx(ctx, "initial cleanup failed", log.Error(err))
}
ticker := time.NewTicker(c.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
c.logger.InfoCtx(ctx, "SAML cleaner shutting down")
return ctx.Err()
case <-ticker.C:
if err := c.cleanup(ctx); err != nil {
c.logger.ErrorCtx(ctx, "periodic cleanup failed", log.Error(err))
}
}
}
}
func (c *Cleaner) cleanup(ctx context.Context) error {
var assertionsDeleted, requestsDeleted, relayStatesDeleted int64
err := c.pg.WithConn(ctx, func(conn pg.Conn) error {
count, err := CleanupExpiredAssertions(ctx, conn)
if err != nil {
return err
}
assertionsDeleted = count
count, err = CleanupExpiredRequests(ctx, conn)
if err != nil {
return err
}
requestsDeleted = count
count, err = CleanupExpiredRelayStates(ctx, conn)
if err != nil {
return err
}
relayStatesDeleted = count
return nil
})
if err != nil {
return err
}
if assertionsDeleted > 0 || requestsDeleted > 0 || relayStatesDeleted > 0 {
c.logger.InfoCtx(ctx, "cleaned up expired SAML data",
log.Int64("assertions", assertionsDeleted),
log.Int64("requests", requestsDeleted),
log.Int64("relay_states", relayStatesDeleted))
}
return nil
}

View File

@@ -0,0 +1,127 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"crypto/x509"
"encoding/pem"
"fmt"
"net/url"
)
type ValidationError struct {
Field string
Message string
}
func (e ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Message)
}
// ValidateIdPConfiguration validates only the IdP (Identity Provider) configuration.
// This validates user-provided data from the IdP.
// SP (Service Provider) configuration is generated by the application and doesn't need validation.
func ValidateIdPConfiguration(
idpEntityID string,
idpSsoURL string,
idpCertificate string,
) []ValidationError {
var errors []ValidationError
// Validate IdP Entity ID
if idpEntityID == "" {
errors = append(errors, ValidationError{
Field: "idp_entity_id",
Message: "IdP Entity ID cannot be empty",
})
}
// Validate IdP SSO URL - accept both HTTP and HTTPS
if err := validateURL(idpSsoURL, "idp_sso_url"); err != nil {
errors = append(errors, *err)
}
// Validate IdP certificate
if err := validateCertificate(idpCertificate); err != nil {
errors = append(errors, ValidationError{
Field: "idp_certificate",
Message: err.Error(),
})
}
return errors
}
func validateURL(urlStr string, fieldName string) *ValidationError {
if urlStr == "" {
return &ValidationError{
Field: fieldName,
Message: "URL cannot be empty",
}
}
parsedURL, err := url.Parse(urlStr)
if err != nil {
return &ValidationError{
Field: fieldName,
Message: fmt.Sprintf("invalid URL format: %v", err),
}
}
if parsedURL.Scheme == "" {
return &ValidationError{
Field: fieldName,
Message: "URL must have a scheme (http or https)",
}
}
if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
return &ValidationError{
Field: fieldName,
Message: "URL scheme must be http or https (found: " + parsedURL.Scheme + ")",
}
}
if parsedURL.Host == "" {
return &ValidationError{
Field: fieldName,
Message: "URL must have a host",
}
}
return nil
}
func validateCertificate(certPEM string) error {
if certPEM == "" {
return fmt.Errorf("certificate cannot be empty")
}
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return fmt.Errorf("failed to parse certificate PEM")
}
if block.Type != "CERTIFICATE" {
return fmt.Errorf("PEM block type must be CERTIFICATE (found: %s)", block.Type)
}
_, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse X.509 certificate: %w", err)
}
return nil
}

View File

@@ -0,0 +1,304 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"context"
"fmt"
"strings"
"time"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"go.gearno.de/kit/pg"
)
type (
CreateSAMLConfigurationRequest struct {
OrganizationID gid.GID
EmailDomain string
EnforcementPolicy coredata.SAMLEnforcementPolicy
IdPEntityID string
IdPSsoURL string
IdPCertificate string
IdPMetadataURL *string
AttributeEmail string
AttributeFirstname string
AttributeLastname string
AttributeRole string
DefaultRole string
AutoSignupEnabled bool
}
UpdateSAMLConfigurationRequest struct {
ID gid.GID
Enabled *bool
EnforcementPolicy *coredata.SAMLEnforcementPolicy
IdPEntityID *string
IdPSsoURL *string
IdPCertificate *string
IdPMetadataURL *string
AttributeEmail *string
AttributeFirstname *string
AttributeLastname *string
AttributeRole *string
DefaultRole *string
AutoSignupEnabled *bool
}
)
func (s TenantAuthService) CreateSAMLConfiguration(
ctx context.Context,
req CreateSAMLConfigurationRequest,
) (*coredata.SAMLConfiguration, error) {
// Validate only the IdP configuration (user-provided data)
validationErrors := ValidateIdPConfiguration(
req.IdPEntityID,
req.IdPSsoURL,
req.IdPCertificate,
)
if len(validationErrors) > 0 {
var errMsgs []string
for _, err := range validationErrors {
errMsgs = append(errMsgs, err.Error())
}
return nil, fmt.Errorf("SAML configuration validation failed: %s", strings.Join(errMsgs, "; "))
}
var config *coredata.SAMLConfiguration
err := s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
now := time.Now()
tenantID := s.scope.GetTenantID()
var org coredata.Organization
if err := org.LoadByID(ctx, tx, s.scope, req.OrganizationID); err != nil {
return fmt.Errorf("organization not found: %w", err)
}
config = &coredata.SAMLConfiguration{
ID: gid.New(tenantID, coredata.SAMLConfigurationEntityType),
OrganizationID: org.ID,
EmailDomain: req.EmailDomain,
EnforcementPolicy: req.EnforcementPolicy,
Enabled: false,
IdPEntityID: req.IdPEntityID,
IdPSsoURL: req.IdPSsoURL,
IdPCertificate: req.IdPCertificate,
IdPMetadataURL: req.IdPMetadataURL,
AttributeEmail: req.AttributeEmail,
AttributeFirstname: req.AttributeFirstname,
AttributeLastname: req.AttributeLastname,
AttributeRole: req.AttributeRole,
DefaultRole: req.DefaultRole,
AutoSignupEnabled: req.AutoSignupEnabled,
CreatedAt: now,
UpdatedAt: now,
}
if err := config.Insert(ctx, tx, s.scope); err != nil {
return fmt.Errorf("cannot insert saml configuration: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return config, nil
}
func (s TenantAuthService) UpdateSAMLConfiguration(
ctx context.Context,
req UpdateSAMLConfigurationRequest,
) (*coredata.SAMLConfiguration, error) {
var config *coredata.SAMLConfiguration
err := s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
var cfg coredata.SAMLConfiguration
if err := cfg.LoadByID(ctx, tx, s.scope, req.ID); err != nil {
return fmt.Errorf("cannot load saml configuration: %w", err)
}
if req.Enabled != nil {
cfg.Enabled = *req.Enabled
}
if req.EnforcementPolicy != nil {
cfg.EnforcementPolicy = *req.EnforcementPolicy
}
if req.IdPEntityID != nil {
cfg.IdPEntityID = *req.IdPEntityID
}
if req.IdPSsoURL != nil {
cfg.IdPSsoURL = *req.IdPSsoURL
}
if req.IdPCertificate != nil {
cfg.IdPCertificate = *req.IdPCertificate
}
if req.IdPMetadataURL != nil {
cfg.IdPMetadataURL = req.IdPMetadataURL
}
if req.AttributeEmail != nil {
cfg.AttributeEmail = *req.AttributeEmail
}
if req.AttributeFirstname != nil {
cfg.AttributeFirstname = *req.AttributeFirstname
}
if req.AttributeLastname != nil {
cfg.AttributeLastname = *req.AttributeLastname
}
if req.AttributeRole != nil {
cfg.AttributeRole = *req.AttributeRole
}
if req.DefaultRole != nil {
cfg.DefaultRole = *req.DefaultRole
}
if req.AutoSignupEnabled != nil {
cfg.AutoSignupEnabled = *req.AutoSignupEnabled
}
cfg.UpdatedAt = time.Now()
if err := cfg.Update(ctx, tx, s.scope); err != nil {
return fmt.Errorf("cannot update saml configuration: %w", err)
}
config = &cfg
return nil
},
)
if err != nil {
return nil, err
}
return config, nil
}
func (s TenantAuthService) DeleteSAMLConfiguration(
ctx context.Context,
configID gid.GID,
) error {
return s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
var config coredata.SAMLConfiguration
if err := config.LoadByID(ctx, tx, s.scope, configID); err != nil {
return fmt.Errorf("cannot load saml configuration: %w", err)
}
if err := config.Delete(ctx, tx, s.scope); err != nil {
return fmt.Errorf("cannot delete saml configuration: %w", err)
}
return nil
},
)
}
func (s TenantAuthService) EnableSAMLConfiguration(
ctx context.Context,
configID gid.GID,
) (*coredata.SAMLConfiguration, error) {
enabled := true
return s.UpdateSAMLConfiguration(ctx, UpdateSAMLConfigurationRequest{
ID: configID,
Enabled: &enabled,
})
}
func (s TenantAuthService) DisableSAMLConfiguration(
ctx context.Context,
configID gid.GID,
) (*coredata.SAMLConfiguration, error) {
disabled := false
return s.UpdateSAMLConfiguration(ctx, UpdateSAMLConfigurationRequest{
ID: configID,
Enabled: &disabled,
})
}
func (s TenantAuthService) GetSAMLConfigurationByID(
ctx context.Context,
configID gid.GID,
) (*coredata.SAMLConfiguration, error) {
var config coredata.SAMLConfiguration
err := s.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return config.LoadByID(ctx, conn, s.scope, configID)
},
)
if err != nil {
return nil, fmt.Errorf("cannot load saml configuration: %w", err)
}
return &config, nil
}
func (s TenantAuthService) GetSAMLConfigurationsByOrganizationID(
ctx context.Context,
organizationID gid.GID,
) ([]*coredata.SAMLConfiguration, error) {
var configs []*coredata.SAMLConfiguration
err := s.pg.WithConn(
ctx,
func(conn pg.Conn) error {
var err error
configs, err = coredata.LoadSAMLConfigurationsByOrganizationID(ctx, conn, s.scope, organizationID)
return err
},
)
if err != nil {
return nil, fmt.Errorf("cannot load saml configurations: %w", err)
}
return configs, nil
}
func (s Service) CheckSSOAvailabilityByEmail(
ctx context.Context,
email string,
) ([]*coredata.SAMLConfiguration, error) {
// Extract domain from email
parts := strings.Split(email, "@")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid email format")
}
domain := parts[1]
var configs []*coredata.SAMLConfiguration
err := s.pg.WithConn(
ctx,
func(conn pg.Conn) error {
var err error
configs, err = coredata.LoadAllEnabledSAMLConfigurationsByEmailDomain(ctx, conn, domain)
return err
},
)
if err != nil {
return nil, fmt.Errorf("cannot load saml configurations: %w", err)
}
return configs, nil
}

147
pkg/auth/saml_mapper.go Normal file
View File

@@ -0,0 +1,147 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"fmt"
"strings"
"github.com/crewjam/saml"
)
func ExtractAttributeValue(assertion *saml.Assertion, attributeName string) (string, error) {
if len(assertion.AttributeStatements) == 0 {
return "", fmt.Errorf("no attribute statement in assertion")
}
for _, attr := range assertion.AttributeStatements[0].Attributes {
if attr.Name == attributeName {
if len(attr.Values) == 0 {
return "", fmt.Errorf("attribute %q has no values", attributeName)
}
return attr.Values[0].Value, nil
}
}
return "", fmt.Errorf("attribute %q not found in assertion", attributeName)
}
func ExtractEmailFromAssertion(assertion *saml.Assertion) (string, error) {
commonEmailAttributes := []string{
"email",
"Email",
"emailAddress",
"mail",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
"http://schemas.xmlsoap.org/claims/EmailAddress",
}
for _, attrName := range commonEmailAttributes {
email, err := ExtractAttributeValue(assertion, attrName)
if err == nil && email != "" {
return email, nil
}
}
if assertion.Subject != nil && assertion.Subject.NameID != nil && assertion.Subject.NameID.Value != "" {
return assertion.Subject.NameID.Value, nil
}
return "", fmt.Errorf("could not extract email from assertion")
}
func ExtractEmailDomain(email string) (string, error) {
parts := strings.Split(email, "@")
if len(parts) != 2 {
return "", fmt.Errorf("invalid email address: %s", email)
}
domain := strings.ToLower(strings.TrimSpace(parts[1]))
if domain == "" {
return "", fmt.Errorf("empty domain in email address: %s", email)
}
return domain, nil
}
func MapSAMLRoleToSystemRole(samlRole string, defaultRole string) (string, error) {
if samlRole != "" && isValidRole(samlRole) {
return samlRole, nil
}
if !isValidRole(defaultRole) {
return "", fmt.Errorf("invalid default role %q", defaultRole)
}
return defaultRole, nil
}
func isValidRole(role string) bool {
switch role {
case "OWNER", "ADMIN", "MEMBER", "VIEWER":
return true
default:
return false
}
}
func ExtractUserAttributes(
assertion *saml.Assertion,
attributeEmail, attributeFirstname, attributeLastname, attributeRole string,
) (email, fullname, role string, err error) {
if len(assertion.AttributeStatements) == 0 {
if assertion.Subject != nil && assertion.Subject.NameID != nil {
email = assertion.Subject.NameID.Value
fullname = email
role = ""
return email, fullname, role, nil
}
return "", "", "", fmt.Errorf("no attribute statement and no NameID in assertion")
}
email, err = ExtractAttributeValue(assertion, attributeEmail)
if err != nil {
if assertion.Subject != nil && assertion.Subject.NameID != nil {
email = assertion.Subject.NameID.Value
} else {
return "", "", "", fmt.Errorf("failed to extract email: %w", err)
}
}
firstname, err := ExtractAttributeValue(assertion, attributeFirstname)
if err != nil {
firstname = ""
}
lastname, err := ExtractAttributeValue(assertion, attributeLastname)
if err != nil {
lastname = ""
}
if firstname != "" && lastname != "" {
fullname = strings.TrimSpace(firstname + " " + lastname)
} else if firstname != "" {
fullname = firstname
} else if lastname != "" {
fullname = lastname
} else {
fullname = email
}
role, err = ExtractAttributeValue(assertion, attributeRole)
if err != nil {
role = ""
}
return email, fullname, role, nil
}

204
pkg/auth/saml_metadata.go Normal file
View File

@@ -0,0 +1,204 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"fmt"
"math/big"
"time"
"github.com/crewjam/saml"
)
func GenerateServiceProviderMetadata(
entityID string,
acsURL string,
spCert *x509.Certificate,
) ([]byte, error) {
certData := base64.StdEncoding.EncodeToString(spCert.Raw)
trueVal := true
metadata := &saml.EntityDescriptor{
EntityID: entityID,
SPSSODescriptors: []saml.SPSSODescriptor{
{
SSODescriptor: saml.SSODescriptor{
RoleDescriptor: saml.RoleDescriptor{
ProtocolSupportEnumeration: "urn:oasis:names:tc:SAML:2.0:protocol",
KeyDescriptors: []saml.KeyDescriptor{
{
Use: "signing",
KeyInfo: saml.KeyInfo{
X509Data: saml.X509Data{
X509Certificates: []saml.X509Certificate{
{Data: certData},
},
},
},
},
{
Use: "encryption",
KeyInfo: saml.KeyInfo{
X509Data: saml.X509Data{
X509Certificates: []saml.X509Certificate{
{Data: certData},
},
},
},
},
},
},
},
AuthnRequestsSigned: &trueVal,
WantAssertionsSigned: &trueVal,
AssertionConsumerServices: []saml.IndexedEndpoint{
{
Binding: saml.HTTPPostBinding,
Location: acsURL,
Index: 0,
},
},
},
},
}
xmlBytes, err := xml.MarshalIndent(metadata, "", " ")
if err != nil {
return nil, fmt.Errorf("failed to marshal SP metadata to XML: %w", err)
}
return xmlBytes, nil
}
func ParseIdPCertificate(certPEM string) (*x509.Certificate, error) {
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return nil, fmt.Errorf("failed to decode PEM block from IdP certificate")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse X.509 certificate: %w", err)
}
return cert, nil
}
type IdPMetadata struct {
EntityID string
SsoURL string
Certificate string
MetadataURL *string
}
func ParseIdPMetadata(metadataXML string) (*IdPMetadata, error) {
var entityDescriptor saml.EntityDescriptor
if err := xml.Unmarshal([]byte(metadataXML), &entityDescriptor); err != nil {
return nil, fmt.Errorf("failed to parse IdP metadata XML: %w", err)
}
if len(entityDescriptor.IDPSSODescriptors) == 0 {
return nil, fmt.Errorf("no IDPSSODescriptor found in metadata")
}
idpDescriptor := entityDescriptor.IDPSSODescriptors[0]
var ssoURL string
for _, sso := range idpDescriptor.SingleSignOnServices {
if sso.Binding == saml.HTTPPostBinding || sso.Binding == saml.HTTPRedirectBinding {
ssoURL = sso.Location
break
}
}
if ssoURL == "" && len(idpDescriptor.SingleSignOnServices) > 0 {
ssoURL = idpDescriptor.SingleSignOnServices[0].Location
}
if ssoURL == "" {
return nil, fmt.Errorf("no SingleSignOnService found in metadata")
}
var certPEM string
for _, keyDescriptor := range idpDescriptor.KeyDescriptors {
if keyDescriptor.Use == "signing" || keyDescriptor.Use == "" {
if len(keyDescriptor.KeyInfo.X509Data.X509Certificates) > 0 {
certData := keyDescriptor.KeyInfo.X509Data.X509Certificates[0].Data
certDER, err := base64.StdEncoding.DecodeString(certData)
if err != nil {
return nil, fmt.Errorf("failed to decode certificate: %w", err)
}
certPEM = string(pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certDER,
}))
break
}
}
}
if certPEM == "" {
return nil, fmt.Errorf("no signing certificate found in metadata")
}
return &IdPMetadata{
EntityID: entityDescriptor.EntityID,
SsoURL: ssoURL,
Certificate: certPEM,
}, nil
}
func GenerateSelfSignedCertificate(entityID string) (*x509.Certificate, *rsa.PrivateKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate RSA private key: %w", err)
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate serial number: %w", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: entityID,
Organization: []string{"Probo"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to create certificate: %w", err)
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse created certificate: %w", err)
}
return cert, privateKey, nil
}

585
pkg/auth/saml_service.go Normal file
View File

@@ -0,0 +1,585 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"fmt"
"net/http"
"net/url"
"time"
"github.com/crewjam/saml"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/crypto/cipher"
"github.com/getprobo/probo/pkg/gid"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
)
type (
SAMLService struct {
pg *pg.Client
encryptionKey cipher.EncryptionKey
baseURL string
sessionDuration time.Duration
cookieName string
cookieSecret string
certificate *x509.Certificate
privateKey *rsa.PrivateKey
logger *log.Logger
}
ErrSPCertificateNotConfigured struct{}
ErrSAMLConfigurationNotFound struct {
OrganizationID gid.GID
}
ErrSAMLDisabled struct {
OrganizationID gid.GID
}
ErrInvalidIdPCertificate struct {
Err error
}
ErrInvalidURL struct {
Field string
URL string
Err error
}
ErrCannotCreateServiceProvider struct {
Err error
}
ErrCannotCreateAuthRequest struct {
Err error
}
ErrCannotGenerateRedirectURL struct {
Err error
}
ErrCannotParseSAMLResponse struct {
Err error
}
ErrCannotValidateAssertion struct {
Err error
}
ErrCannotExtractUserAttributes struct {
Err error
}
ErrCannotMapRole struct {
Err error
}
ErrReplayAttackDetected struct {
AssertionID string
Err error
}
)
func (e ErrSPCertificateNotConfigured) Error() string {
return "SP certificate and private key are not configured"
}
func (e ErrSAMLConfigurationNotFound) Error() string {
return fmt.Sprintf("SAML configuration not found for organization %s", e.OrganizationID)
}
func (e ErrSAMLDisabled) Error() string {
return fmt.Sprintf("SAML is disabled for organization %s", e.OrganizationID)
}
func (e ErrInvalidIdPCertificate) Error() string {
return fmt.Sprintf("cannot parse IdP certificate: %v", e.Err)
}
func (e ErrInvalidURL) Error() string {
return fmt.Sprintf("cannot parse %s URL %q: %v", e.Field, e.URL, e.Err)
}
func (e ErrCannotCreateServiceProvider) Error() string {
return fmt.Sprintf("cannot create service provider: %v", e.Err)
}
func (e ErrCannotCreateAuthRequest) Error() string {
return fmt.Sprintf("cannot create AuthnRequest: %v", e.Err)
}
func (e ErrCannotGenerateRedirectURL) Error() string {
return fmt.Sprintf("cannot generate redirect URL: %v", e.Err)
}
func (e ErrCannotParseSAMLResponse) Error() string {
return fmt.Sprintf("cannot parse SAML response: %v", e.Err)
}
func (e ErrCannotValidateAssertion) Error() string {
return fmt.Sprintf("cannot validate assertion: %v", e.Err)
}
func (e ErrCannotExtractUserAttributes) Error() string {
return fmt.Sprintf("cannot extract user attributes: %v", e.Err)
}
func (e ErrCannotMapRole) Error() string {
return fmt.Sprintf("cannot map role: %v", e.Err)
}
func (e ErrReplayAttackDetected) Error() string {
return fmt.Sprintf("replay attack detected for assertion %s: %v", e.AssertionID, e.Err)
}
func NewSAMLService(
pg *pg.Client,
encryptionKey cipher.EncryptionKey,
baseURL string,
sessionDuration time.Duration,
cookieName string,
cookieSecret string,
certificatePEM string,
privateKeyPEM string,
logger *log.Logger,
) (*SAMLService, error) {
var certificate *x509.Certificate
var privateKey *rsa.PrivateKey
if certificatePEM != "" {
block, _ := pem.Decode([]byte(certificatePEM))
if block == nil || block.Type != "CERTIFICATE" {
return nil, fmt.Errorf("invalid certificate PEM format")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("cannot parse certificate: %w", err)
}
certificate = cert
}
if privateKeyPEM != "" {
block, _ := pem.Decode([]byte(privateKeyPEM))
if block == nil {
return nil, fmt.Errorf("invalid private key PEM format")
}
var key *rsa.PrivateKey
var err error
switch block.Type {
case "RSA PRIVATE KEY":
key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("cannot parse PKCS1 private key: %w", err)
}
case "PRIVATE KEY":
parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("cannot parse PKCS8 private key: %w", err)
}
var ok bool
key, ok = parsedKey.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("private key is not RSA")
}
default:
return nil, fmt.Errorf("unsupported private key type: %s", block.Type)
}
privateKey = key
}
return &SAMLService{
pg: pg,
encryptionKey: encryptionKey,
baseURL: baseURL,
sessionDuration: sessionDuration,
cookieName: cookieName,
cookieSecret: cookieSecret,
certificate: certificate,
privateKey: privateKey,
logger: logger,
}, nil
}
func (s *SAMLService) GetEntityID() string {
return fmt.Sprintf("%s/auth/saml/metadata", s.baseURL)
}
func (s *SAMLService) GetAcsURL() string {
return fmt.Sprintf("%s/auth/saml/consume", s.baseURL)
}
func parseRawSAMLResponse(encodedResponse string) (*saml.Assertion, error) {
rawResponseBuf, err := base64.StdEncoding.DecodeString(encodedResponse)
if err != nil {
return nil, fmt.Errorf("cannot decode base64: %w", err)
}
var response saml.Response
if err := xml.Unmarshal(rawResponseBuf, &response); err != nil {
return nil, fmt.Errorf("cannot unmarshal response: %w", err)
}
if response.Assertion == nil {
if response.EncryptedAssertion != nil {
return nil, fmt.Errorf("response contains encrypted assertion which cannot be parsed without SP private key")
}
return nil, fmt.Errorf("response contains no assertion")
}
return response.Assertion, nil
}
func (s *SAMLService) GetServiceProvider(
ctx context.Context,
config *coredata.SAMLConfiguration,
) (*saml.ServiceProvider, error) {
if s.certificate == nil || s.privateKey == nil {
return nil, ErrSPCertificateNotConfigured{}
}
idpCert, err := ParseIdPCertificate(config.IdPCertificate)
if err != nil {
return nil, ErrInvalidIdPCertificate{Err: err}
}
acsURL, err := url.Parse(s.GetAcsURL())
if err != nil {
return nil, ErrInvalidURL{Field: "ACS", URL: s.GetAcsURL(), Err: err}
}
idpSSOURL, err := url.Parse(config.IdPSsoURL)
if err != nil {
return nil, ErrInvalidURL{Field: "IdP SSO", URL: config.IdPSsoURL, Err: err}
}
sp := &saml.ServiceProvider{
EntityID: s.GetEntityID(),
Key: s.privateKey,
Certificate: s.certificate,
MetadataURL: *acsURL,
AcsURL: *acsURL,
SloURL: *acsURL,
IDPMetadata: &saml.EntityDescriptor{
EntityID: config.IdPEntityID,
IDPSSODescriptors: []saml.IDPSSODescriptor{
{
SSODescriptor: saml.SSODescriptor{
RoleDescriptor: saml.RoleDescriptor{
ProtocolSupportEnumeration: "urn:oasis:names:tc:SAML:2.0:protocol",
KeyDescriptors: []saml.KeyDescriptor{
{
Use: "signing",
KeyInfo: saml.KeyInfo{
X509Data: saml.X509Data{
X509Certificates: []saml.X509Certificate{
{Data: base64.StdEncoding.EncodeToString(idpCert.Raw)},
},
},
},
},
},
},
},
SingleSignOnServices: []saml.Endpoint{
{
Binding: saml.HTTPRedirectBinding,
Location: idpSSOURL.String(),
},
},
},
},
},
}
return sp, nil
}
func (s *SAMLService) InitiateSAMLLogin(
ctx context.Context,
organizationID gid.GID,
tenantID gid.TenantID,
emailDomain string,
) (string, error) {
var config coredata.SAMLConfiguration
scope := coredata.NewScope(tenantID)
err := s.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return config.LoadByOrganizationIDAndEmailDomain(ctx, conn, scope, organizationID, emailDomain)
},
)
if err != nil {
return "", ErrSAMLConfigurationNotFound{OrganizationID: organizationID}
}
if !config.Enabled {
return "", ErrSAMLDisabled{OrganizationID: organizationID}
}
sp, err := s.GetServiceProvider(ctx, &config)
if err != nil {
return "", ErrCannotCreateServiceProvider{Err: err}
}
authReq, err := sp.MakeAuthenticationRequest(
config.IdPSsoURL,
saml.HTTPRedirectBinding,
saml.HTTPPostBinding,
)
if err != nil {
return "", ErrCannotCreateAuthRequest{Err: err}
}
relayStateToken, err := coredata.GenerateSecureToken()
if err != nil {
return "", fmt.Errorf("cannot generate relay state token: %w", err)
}
now := time.Now()
requestExpiry := now.Add(10 * time.Minute)
relayStateExpiry := now.Add(15 * time.Minute)
err = s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
samlRequest := coredata.SAMLRequest{
ID: authReq.ID,
OrganizationID: organizationID,
CreatedAt: now,
ExpiresAt: requestExpiry,
}
if err := samlRequest.Insert(ctx, tx, scope); err != nil {
return fmt.Errorf("cannot store SAML request: %w", err)
}
relayState := coredata.SAMLRelayState{
Token: relayStateToken,
OrganizationID: organizationID,
SAMLConfigID: config.ID,
RequestID: authReq.ID,
CreatedAt: now,
ExpiresAt: relayStateExpiry,
}
if err := relayState.Insert(ctx, tx, scope); err != nil {
return fmt.Errorf("cannot store relay state: %w", err)
}
return nil
},
)
if err != nil {
return "", err
}
redirectURL, err := authReq.Redirect(relayStateToken, sp)
if err != nil {
return "", ErrCannotGenerateRedirectURL{Err: err}
}
return redirectURL.String(), nil
}
type SAMLUserInfo struct {
Email string
FullName string
Role string
SAMLSubject string
OrganizationID gid.GID
TenantID gid.TenantID
SAMLConfigID gid.GID
}
func (s *SAMLService) HandleSAMLAssertion(
ctx context.Context,
req *http.Request,
) (*SAMLUserInfo, error) {
relayStateToken := req.FormValue("RelayState")
if relayStateToken == "" {
return nil, fmt.Errorf("missing RelayState in SAML response")
}
var relayState coredata.SAMLRelayState
var samlRequest coredata.SAMLRequest
var config coredata.SAMLConfiguration
var org coredata.Organization
now := time.Now()
err := s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
if err := relayState.Load(ctx, tx, relayStateToken); err != nil {
return fmt.Errorf("invalid relay state: %w", err)
}
if relayState.IsExpired(now) {
return coredata.ErrRelayStateExpired{Token: relayStateToken, ExpiresAt: relayState.ExpiresAt}
}
if err := samlRequest.Load(ctx, tx, relayState.RequestID, relayState.OrganizationID); err != nil {
return fmt.Errorf("invalid SAML request: %w", err)
}
if samlRequest.IsExpired(now) {
return coredata.ErrSAMLRequestExpired{RequestID: relayState.RequestID, ExpiresAt: samlRequest.ExpiresAt}
}
if err := org.LoadByID(ctx, tx, coredata.NewNoScope(), relayState.OrganizationID); err != nil {
return fmt.Errorf("organization not found: %w", err)
}
if err := relayState.Delete(ctx, tx); err != nil {
return fmt.Errorf("cannot delete relay state: %w", err)
}
if err := samlRequest.Delete(ctx, tx); err != nil {
return fmt.Errorf("cannot delete SAML request: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
samlResponseEncoded := req.FormValue("SAMLResponse")
if samlResponseEncoded == "" {
return nil, fmt.Errorf("missing SAMLResponse in request")
}
scope := coredata.NewScope(org.TenantID)
err = s.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return config.LoadByID(ctx, conn, scope, relayState.SAMLConfigID)
},
)
if err != nil {
return nil, ErrSAMLConfigurationNotFound{OrganizationID: relayState.OrganizationID}
}
if !config.Enabled {
return nil, ErrSAMLDisabled{OrganizationID: relayState.OrganizationID}
}
sp, err := s.GetServiceProvider(ctx, &config)
if err != nil {
return nil, ErrCannotCreateServiceProvider{Err: err}
}
if req.URL.Scheme == "" {
req.URL.Scheme = "https"
}
if req.URL.Host == "" {
req.URL.Host = req.Host
}
possibleRequestIDs := []string{samlRequest.ID}
assertion, err := sp.ParseResponse(req, possibleRequestIDs)
if err != nil {
return nil, fmt.Errorf("cannot parse SAML response (SP EntityID: %s, IdP EntityID: %s): %w",
s.GetEntityID(), config.IdPEntityID, err)
}
if err := ValidateAssertion(assertion, s.GetEntityID(), now); err != nil {
return nil, ErrCannotValidateAssertion{Err: err}
}
if assertion.ID != "" {
var expiresAt time.Time
if assertion.Conditions != nil && !assertion.Conditions.NotOnOrAfter.IsZero() {
expiresAt = assertion.Conditions.NotOnOrAfter
} else {
expiresAt = now.Add(24 * time.Hour)
}
scope := coredata.NewScope(org.TenantID)
err = s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
return PreventReplayAttack(ctx, tx, scope, assertion.ID, relayState.OrganizationID, expiresAt)
},
)
if err != nil {
return nil, ErrReplayAttackDetected{AssertionID: assertion.ID, Err: err}
}
}
email, fullname, samlRole, err := ExtractUserAttributes(
assertion,
config.AttributeEmail,
config.AttributeFirstname,
config.AttributeLastname,
config.AttributeRole,
)
if err != nil {
return nil, ErrCannotExtractUserAttributes{Err: err}
}
actualEmailDomain, err := ExtractEmailDomain(email)
if err != nil {
return nil, ErrCannotExtractUserAttributes{Err: fmt.Errorf("cannot extract domain from email: %w", err)}
}
if actualEmailDomain != config.EmailDomain {
return nil, fmt.Errorf("email domain mismatch: assertion contains email with domain %s but SAML config is for domain %s", actualEmailDomain, config.EmailDomain)
}
systemRole, err := MapSAMLRoleToSystemRole(samlRole, config.DefaultRole)
if err != nil {
return nil, ErrCannotMapRole{Err: err}
}
samlSubject := ""
if assertion.Subject != nil && assertion.Subject.NameID != nil {
samlSubject = assertion.Subject.NameID.Value
}
return &SAMLUserInfo{
Email: email,
FullName: fullname,
Role: systemRole,
SAMLSubject: samlSubject,
OrganizationID: relayState.OrganizationID,
TenantID: org.TenantID,
SAMLConfigID: relayState.SAMLConfigID,
}, nil
}
func (s *SAMLService) GetMetadataURL(organizationID gid.GID) string {
return fmt.Sprintf("%s/auth/saml/metadata/%s", s.baseURL, organizationID)
}
func (s *SAMLService) GenerateMetadata() ([]byte, error) {
if s.certificate == nil {
return nil, ErrSPCertificateNotConfigured{}
}
return GenerateServiceProviderMetadata(
s.GetEntityID(),
s.GetAcsURL(),
s.certificate,
)
}

110
pkg/auth/saml_validator.go Normal file
View File

@@ -0,0 +1,110 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"context"
"fmt"
"time"
"github.com/crewjam/saml"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"go.gearno.de/kit/pg"
)
func PreventReplayAttack(
ctx context.Context,
conn pg.Conn,
scope coredata.Scoper,
assertionID string,
organizationID gid.GID,
expiresAt time.Time,
) error {
var assertion coredata.SAMLAssertion
exists, err := assertion.CheckExists(ctx, conn, assertionID)
if err != nil {
return fmt.Errorf("failed to check assertion ID: %w", err)
}
if exists {
return coredata.ErrAssertionAlreadyUsed{AssertionID: assertionID}
}
now := time.Now()
assertion = coredata.SAMLAssertion{
ID: assertionID,
OrganizationID: organizationID,
UsedAt: now,
ExpiresAt: expiresAt,
}
if err := assertion.Insert(ctx, conn, scope); err != nil {
return fmt.Errorf("failed to store assertion ID: %w", err)
}
return nil
}
func ValidateAssertion(
assertion *saml.Assertion,
expectedAudience string,
now time.Time,
) error {
const clockSkewTolerance = 5 * time.Minute
if assertion.Conditions != nil && !assertion.Conditions.NotBefore.IsZero() {
if now.Add(clockSkewTolerance).Before(assertion.Conditions.NotBefore) {
return fmt.Errorf("assertion not yet valid (NotBefore: %v, now: %v, tolerance: %v)",
assertion.Conditions.NotBefore, now, clockSkewTolerance)
}
}
if assertion.Conditions != nil && !assertion.Conditions.NotOnOrAfter.IsZero() {
if now.Add(-clockSkewTolerance).After(assertion.Conditions.NotOnOrAfter) ||
now.Add(-clockSkewTolerance).Equal(assertion.Conditions.NotOnOrAfter) {
return fmt.Errorf("assertion expired (NotOnOrAfter: %v, now: %v, tolerance: %v)",
assertion.Conditions.NotOnOrAfter, now, clockSkewTolerance)
}
}
if assertion.Conditions != nil && len(assertion.Conditions.AudienceRestrictions) > 0 {
audienceValid := false
for _, restriction := range assertion.Conditions.AudienceRestrictions {
if restriction.Audience.Value == expectedAudience {
audienceValid = true
break
}
}
if !audienceValid {
return fmt.Errorf("assertion audience restriction does not match expected audience %q", expectedAudience)
}
}
return nil
}
func CleanupExpiredAssertions(ctx context.Context, conn pg.Conn) (int64, error) {
return coredata.DeleteExpiredSAMLAssertions(ctx, conn, time.Now())
}
func CleanupExpiredRequests(ctx context.Context, conn pg.Conn) (int64, error) {
return coredata.DeleteExpiredSAMLRequests(ctx, conn, time.Now())
}
func CleanupExpiredRelayStates(ctx context.Context, conn pg.Conn) (int64, error) {
return coredata.DeleteExpiredSAMLRelayStates(ctx, conn, time.Now())
}

View File

@@ -16,17 +16,22 @@ package auth
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"net"
"net/mail"
"net/url"
"time"
"github.com/getprobo/probo/packages/emails"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/crypto/cipher"
"github.com/getprobo/probo/pkg/crypto/passwdhash"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/statelesstoken"
"github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg"
)
@@ -35,13 +40,26 @@ type (
// No organization-related logic - that belongs to authz service
Service struct {
pg *pg.Client
encryptionKey cipher.EncryptionKey
hp *passwdhash.Profile
hostname string
baseURL string
tokenSecret string
disableSignup bool
invitationTokenValidity time.Duration
}
// TenantAuthService handles tenant-scoped authentication operations
TenantAuthService struct {
pg *pg.Client
encryptionKey cipher.EncryptionKey
hp *passwdhash.Profile
hostname string
baseURL string
tokenSecret string
scope coredata.Scoper
}
ErrInvalidCredentials struct {
message string
}
@@ -137,22 +155,38 @@ func (e ErrSignupDisabled) Error() string {
func NewService(
ctx context.Context,
pgClient *pg.Client,
encryptionKey cipher.EncryptionKey,
hp *passwdhash.Profile,
tokenSecret string,
hostname string,
baseURL string,
disableSignup bool,
invitationTokenValidity time.Duration,
) (*Service, error) {
return &Service{
pg: pgClient,
encryptionKey: encryptionKey,
hp: hp,
hostname: hostname,
baseURL: baseURL,
tokenSecret: tokenSecret,
disableSignup: disableSignup,
invitationTokenValidity: invitationTokenValidity,
}, nil
}
func (s *Service) WithTenant(tenantID gid.TenantID) *TenantAuthService {
return &TenantAuthService{
pg: s.pg,
encryptionKey: s.encryptionKey,
hp: s.hp,
hostname: s.hostname,
baseURL: s.baseURL,
tokenSecret: s.tokenSecret,
scope: coredata.NewScope(tenantID),
}
}
func (s Service) ForgetPassword(
ctx context.Context,
email string,
@@ -265,7 +299,7 @@ func (s Service) SignUp(
err = s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
if err := user.Insert(ctx, tx); err != nil {
if err := user.Insert(ctx, tx, coredata.NewNoScope()); err != nil {
var errUserAlreadyExists *coredata.ErrUserAlreadyExists
if errors.As(err, &errUserAlreadyExists) {
return &ErrUserAlreadyExists{errUserAlreadyExists.Error()}
@@ -328,6 +362,116 @@ func (s Service) SignUp(
return user, session, nil
}
func (s Service) CreateOrGetSAMLUser(
ctx context.Context,
emailAddress string,
fullName string,
samlSubject string,
) (*coredata.User, error) {
if _, err := mail.ParseAddress(emailAddress); err != nil {
return nil, &ErrInvalidEmail{emailAddress}
}
if fullName == "" {
return nil, &ErrInvalidFullName{fullName}
}
if samlSubject == "" {
return nil, fmt.Errorf("SAML subject cannot be empty")
}
var user coredata.User
now := time.Now()
err := s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
// Try to load existing user by email
if err := user.LoadByEmail(ctx, tx, emailAddress); err == nil {
// User exists - update SAML subject and full name if needed
needsUpdate := false
if user.SAMLSubject == nil || *user.SAMLSubject != samlSubject {
user.SAMLSubject = &samlSubject
needsUpdate = true
}
if user.FullName != fullName {
user.FullName = fullName
needsUpdate = true
}
if !user.EmailAddressVerified {
user.EmailAddressVerified = true
needsUpdate = true
}
if needsUpdate {
user.UpdatedAt = now
if err := user.Update(ctx, tx); err != nil {
return fmt.Errorf("cannot update user: %w", err)
}
}
return nil
}
// No existing user, create new user (all users are global now)
user = coredata.User{
ID: gid.New(gid.NilTenant, coredata.UserEntityType),
EmailAddress: emailAddress,
HashedPassword: nil, // SAML users don't have passwords initially
EmailAddressVerified: true, // SAML users are verified by IdP
FullName: fullName,
SAMLSubject: &samlSubject,
CreatedAt: now,
UpdatedAt: now,
}
if err := user.Insert(ctx, tx, coredata.NewNoScope()); err != nil {
return fmt.Errorf("cannot insert SAML user: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return &user, nil
}
func (s Service) CreateSessionForUser(
ctx context.Context,
userID gid.GID,
sessionDuration time.Duration,
) (*coredata.Session, error) {
now := time.Now()
session := &coredata.Session{
ID: gid.New(gid.NilTenant, coredata.SessionEntityType),
UserID: userID,
Data: coredata.SessionData{},
ExpiredAt: now.Add(sessionDuration),
CreatedAt: now,
UpdatedAt: now,
}
err := s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
if err := session.Insert(ctx, tx); err != nil {
return fmt.Errorf("cannot insert session: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return session, nil
}
func (s Service) SignIn(
ctx context.Context,
emailAddress string,
@@ -340,6 +484,69 @@ func (s Service) SignIn(
user := &coredata.User{}
session := &coredata.Session{}
err := s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
// Load user by email (all users are global now)
if err := user.LoadByEmail(ctx, tx, emailAddress); err != nil {
var errUserNotFound *coredata.ErrUserNotFound
if errors.As(err, &errUserNotFound) {
return &ErrInvalidCredentials{"invalid email or password"}
}
return fmt.Errorf("cannot load user by email: %w", err)
}
// Verify password
match, err := s.hp.ComparePasswordAndHash([]byte(password), user.HashedPassword)
if err != nil {
return fmt.Errorf("cannot verify password: %w", err)
}
if !match {
return &ErrInvalidCredentials{"invalid email or password"}
}
// Create new session with password authentication flag set
now := time.Now()
session = &coredata.Session{
ID: gid.New(gid.NilTenant, coredata.SessionEntityType),
UserID: user.ID,
Data: coredata.SessionData{
PasswordAuthenticated: true,
SAMLAuthenticatedOrgs: make(map[string]coredata.SAMLAuthInfo),
},
ExpiredAt: now.Add(24 * time.Hour * 7), // 7 days
CreatedAt: now,
UpdatedAt: now,
}
if err := session.Insert(ctx, tx); err != nil {
return fmt.Errorf("cannot insert session: %w", err)
}
return nil
},
)
if err != nil {
return nil, nil, err
}
return session, user, nil
}
func (s Service) SignInWithExistingSession(
ctx context.Context,
emailAddress string,
password string,
existingSession *coredata.Session,
) (*coredata.Session, *coredata.User, error) {
if _, err := mail.ParseAddress(emailAddress); err != nil {
return nil, nil, &ErrInvalidCredentials{"invalid email or password"}
}
user := &coredata.User{}
session := &coredata.Session{}
err := s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
@@ -359,18 +566,38 @@ func (s Service) SignIn(
return &ErrInvalidCredentials{"invalid email or password"}
}
now := time.Now()
session = &coredata.Session{
ID: gid.New(gid.NilTenant, coredata.SessionEntityType),
UserID: user.ID,
Data: coredata.SessionData{},
ExpiredAt: now.Add(24 * time.Hour * 7), // 7 days
CreatedAt: now,
UpdatedAt: now,
}
if existingSession != nil && existingSession.UserID == user.ID {
session = &coredata.Session{}
if err := session.LoadByID(ctx, tx, existingSession.ID); err != nil {
return fmt.Errorf("cannot load session: %w", err)
}
if err := session.Insert(ctx, tx); err != nil {
return fmt.Errorf("cannot insert session: %w", err)
session.Data.PasswordAuthenticated = true
if session.Data.SAMLAuthenticatedOrgs == nil {
session.Data.SAMLAuthenticatedOrgs = make(map[string]coredata.SAMLAuthInfo)
}
session.UpdatedAt = time.Now()
if err := session.Update(ctx, tx); err != nil {
return fmt.Errorf("cannot update session: %w", err)
}
} else {
now := time.Now()
session = &coredata.Session{
ID: gid.New(gid.NilTenant, coredata.SessionEntityType),
UserID: user.ID,
Data: coredata.SessionData{
PasswordAuthenticated: true,
SAMLAuthenticatedOrgs: make(map[string]coredata.SAMLAuthInfo),
},
ExpiredAt: now.Add(24 * time.Hour * 7),
CreatedAt: now,
UpdatedAt: now,
}
if err := session.Insert(ctx, tx); err != nil {
return fmt.Errorf("cannot insert session: %w", err)
}
}
return nil
@@ -510,6 +737,30 @@ func (s Service) UpdateSession(ctx context.Context, sessionID gid.GID) (*coredat
return session, nil
}
func (s Service) UpdateSessionData(ctx context.Context, sessionID gid.GID, data coredata.SessionData) error {
return s.pg.WithTx(
ctx,
func(tx pg.Conn) error {
session := &coredata.Session{}
if err := session.LoadByID(ctx, tx, sessionID); err != nil {
return &ErrSessionNotFound{"session not found"}
}
if time.Now().After(session.ExpiredAt) {
return &ErrSessionExpired{"session expired"}
}
session.Data = data
session.UpdatedAt = time.Now()
if err := session.Update(ctx, tx); err != nil {
return fmt.Errorf("cannot update session: %w", err)
}
return nil
},
)
}
func (s Service) ConfirmEmail(ctx context.Context, tokenString string) error {
payload, err := statelesstoken.ValidateToken[EmailConfirmationData](
s.tokenSecret,
@@ -655,7 +906,7 @@ func (s Service) SignupFromInvitation(
UpdatedAt: now,
}
if err := user.Insert(ctx, tx); err != nil {
if err := user.Insert(ctx, tx, coredata.NewNoScope()); err != nil {
var errUserAlreadyExists *coredata.ErrUserAlreadyExists
if errors.As(err, &errUserAlreadyExists) {
return &ErrUserAlreadyExists{errUserAlreadyExists.Error()}
@@ -686,3 +937,342 @@ func (s Service) SignupFromInvitation(
return user, session, nil
}
// IsTenantUser removed - all users are now global (no tenant distinction)
func (s Service) GetUserAuthMethod(
ctx context.Context,
scope coredata.Scoper,
userID gid.GID,
organizationID gid.GID,
session *coredata.Session,
) (coredata.UserAuthMethod, error) {
// Load the user to check their email and SAML subject
user := &coredata.User{}
err := s.pg.WithConn(ctx, func(conn pg.Conn) error {
return user.LoadByID(ctx, conn, userID)
})
if err != nil {
return "", fmt.Errorf("cannot load user: %w", err)
}
// If user doesn't have a SAML subject, they only use password auth
if user.SAMLSubject == nil || *user.SAMLSubject == "" {
return coredata.UserAuthMethodPassword, nil
}
// User has SAML subject - check if there's SAML config for this org + user's domain
// Extract domain from user email
emailParts := []byte(user.EmailAddress)
atIndex := -1
for i, b := range emailParts {
if b == '@' {
atIndex = i
break
}
}
if atIndex == -1 {
return coredata.UserAuthMethodPassword, nil
}
domain := string(emailParts[atIndex+1:])
// Check if SAML is configured for this org + domain
var samlConfig coredata.SAMLConfiguration
orgScope := coredata.NewScope(organizationID.TenantID())
err = s.pg.WithConn(ctx, func(conn pg.Conn) error {
err := samlConfig.LoadByOrganizationIDAndEmailDomain(ctx, conn, orgScope, organizationID, domain)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil // No SAML config for this org+domain
}
return err
}
return nil
})
if err != nil {
return "", fmt.Errorf("cannot check SAML configuration: %w", err)
}
// If SAML config exists for this org+domain, user enrolled via SAML
if samlConfig.ID != (gid.GID{}) {
return coredata.UserAuthMethodSAML, nil
}
// No SAML config for this org, user uses password
return coredata.UserAuthMethodPassword, nil
}
// Organization Access Control
type (
// ErrSAMLAuthRequired indicates user must authenticate via SAML to access org
ErrSAMLAuthRequired struct {
ConfigID gid.GID
OrganizationID gid.GID
RedirectURL string // SAML IdP login URL
}
// ErrPasswordAuthRequired indicates user must authenticate with password to access org
ErrPasswordAuthRequired struct {
OrganizationID gid.GID
RedirectURL string // Password login page URL
}
)
func (e ErrSAMLAuthRequired) Error() string {
return "SAML authentication required for this organization"
}
func (e ErrPasswordAuthRequired) Error() string {
return "password authentication required for this organization"
}
// CheckOrganizationAccess determines if a user can access an organization
// based on SAML configuration and session authentication state
func (s Service) CheckOrganizationAccess(
ctx context.Context,
user *coredata.User,
organizationID gid.GID,
session *coredata.Session,
) error {
// Extract domain from user email
emailParts := []byte(user.EmailAddress)
atIndex := -1
for i, b := range emailParts {
if b == '@' {
atIndex = i
break
}
}
if atIndex == -1 {
return fmt.Errorf("invalid email address format")
}
domain := string(emailParts[atIndex+1:])
// Find SAML configuration for this organization and domain
var samlConfig coredata.SAMLConfiguration
scope := coredata.NewScope(organizationID.TenantID())
err := s.pg.WithConn(ctx, func(conn pg.Conn) error {
err := samlConfig.LoadByOrganizationIDAndEmailDomain(ctx, conn, scope, organizationID, domain)
if err != nil {
// If no SAML config found for this organization and domain, that's okay - not an error
// Just means this organization doesn't have SAML configured for this domain
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
return err
}
return nil
})
if err != nil {
return fmt.Errorf("cannot check SAML configuration: %w", err)
}
// Check if SAML is configured and enabled for this domain and organization
if samlConfig.ID != (gid.GID{}) && samlConfig.Enabled && samlConfig.DomainVerified {
// SAML config exists for this org - check enforcement policy
if samlConfig.EnforcementPolicy == coredata.SAMLEnforcementPolicyRequired {
// SAML is REQUIRED - check if user has SAML-authenticated for this org
authInfo, hasSAMLAuth := session.Data.SAMLAuthenticatedOrgs[organizationID.String()]
if !hasSAMLAuth {
// Build SAML login URL
samlLoginURL := fmt.Sprintf("%s/auth/saml/login/%s", s.baseURL, samlConfig.ID)
return ErrSAMLAuthRequired{
ConfigID: samlConfig.ID,
OrganizationID: organizationID,
RedirectURL: samlLoginURL,
}
}
// Optional: Check if SAML auth is still recent (not too old)
// For now, we trust the session lifetime
_ = authInfo
} else {
// SAML is OPTIONAL or OFF - allow either password OR SAML auth for this specific org
hasSAMLAuth := false
if _, ok := session.Data.SAMLAuthenticatedOrgs[organizationID.String()]; ok {
hasSAMLAuth = true
}
if !session.Data.PasswordAuthenticated && !hasSAMLAuth {
// User needs to authenticate - offer SAML as option
samlLoginURL := fmt.Sprintf("%s/auth/saml/login/%s", s.baseURL, samlConfig.ID)
return ErrSAMLAuthRequired{
ConfigID: samlConfig.ID,
OrganizationID: organizationID,
RedirectURL: samlLoginURL,
}
}
}
} else {
// No SAML configuration for this org+domain combination
// Require password authentication for password-only organizations
if !session.Data.PasswordAuthenticated {
// User hasn't authenticated with password - require password authentication
loginURL := fmt.Sprintf("%s/authentication/login?method=password", s.baseURL)
return ErrPasswordAuthRequired{
OrganizationID: organizationID,
RedirectURL: loginURL,
}
}
}
return nil // Access granted
}
// InitiateDomainVerification creates a SAML configuration with unverified domain and generates verification token
func (s Service) InitiateDomainVerification(
ctx context.Context,
tenantID gid.TenantID,
organizationID gid.GID,
emailDomain string,
) (*coredata.SAMLConfiguration, error) {
token, err := GenerateDomainVerificationToken()
if err != nil {
return nil, fmt.Errorf("cannot generate verification token: %w", err)
}
var config *coredata.SAMLConfiguration
err = s.pg.WithTx(ctx, func(tx pg.Conn) error {
now := time.Now()
scope := coredata.NewScope(tenantID)
config = &coredata.SAMLConfiguration{
ID: gid.New(tenantID, coredata.SAMLConfigurationEntityType),
OrganizationID: organizationID,
EmailDomain: emailDomain,
Enabled: false,
EnforcementPolicy: coredata.SAMLEnforcementPolicyOff,
DomainVerified: false,
DomainVerificationToken: &token,
// Default IdP values (placeholders until configured)
IdPEntityID: "not-configured",
IdPSsoURL: "not-configured",
IdPCertificate: "not-configured",
// Default attribute mappings
AttributeEmail: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
AttributeFirstname: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname",
AttributeLastname: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname",
AttributeRole: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role",
DefaultRole: "MEMBER",
AutoSignupEnabled: false,
CreatedAt: now,
UpdatedAt: now,
}
if err := config.Insert(ctx, tx, scope); err != nil {
return fmt.Errorf("cannot insert SAML configuration: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
return config, nil
}
// VerifyDomain checks DNS TXT record and marks domain as verified if found
func (s Service) VerifyDomain(
ctx context.Context,
tenantID gid.TenantID,
configID gid.GID,
) (*coredata.SAMLConfiguration, bool, error) {
var config *coredata.SAMLConfiguration
var verified bool
err := s.pg.WithTx(ctx, func(tx pg.Conn) error {
scope := coredata.NewScope(tenantID)
// Load config
config = &coredata.SAMLConfiguration{}
if err := config.LoadByID(ctx, tx, scope, configID); err != nil {
return fmt.Errorf("cannot load SAML configuration: %w", err)
}
if config.DomainVerificationToken == nil {
return fmt.Errorf("no verification token found for this configuration")
}
if config.DomainVerified {
verified = true
return nil // Already verified
}
// Check DNS TXT record
isVerified, err := VerifyDomainOwnership(ctx, config.EmailDomain, *config.DomainVerificationToken)
if err != nil {
return fmt.Errorf("cannot verify domain ownership: %w", err)
}
verified = isVerified
if isVerified {
now := time.Now()
config.DomainVerified = true
config.DomainVerifiedAt = &now
config.UpdatedAt = now
if err := config.Update(ctx, tx, scope); err != nil {
return fmt.Errorf("cannot update SAML configuration: %w", err)
}
}
return nil
})
if err != nil {
return nil, false, err
}
return config, verified, nil
}
// Domain Verification Methods
// GenerateDomainVerificationToken generates a random 32-character hex token for domain verification
func GenerateDomainVerificationToken() (string, error) {
bytes := make([]byte, 16) // 16 bytes = 32 hex characters
if _, err := rand.Read(bytes); err != nil {
return "", fmt.Errorf("cannot generate domain verification token: %w", err)
}
return hex.EncodeToString(bytes), nil
}
// GetDomainVerificationRecord returns the DNS TXT record string that should be added to the domain
func GetDomainVerificationRecord(token string) string {
return fmt.Sprintf("probo-verification=%s", token)
}
// VerifyDomainOwnership performs DNS lookup to verify domain ownership via TXT record
func VerifyDomainOwnership(ctx context.Context, domain, expectedToken string) (bool, error) {
// Use net package for DNS TXT record lookup
var txtRecords []string
var err error
// Create a DNS resolver with timeout from context
resolver := &net.Resolver{
PreferGo: true,
}
txtRecords, err = resolver.LookupTXT(ctx, domain)
if err != nil {
// DNS lookup errors are expected if the domain doesn't exist or has no TXT records
// We return false (not verified) but not an error, as this is a normal case
return false, nil
}
// Check if any TXT record matches our verification token
expectedRecord := GetDomainVerificationRecord(expectedToken)
for _, record := range txtRecords {
if record == expectedRecord {
return true, nil
}
}
// Token not found in DNS records
return false, nil
}