490 lines
22 KiB
Go
490 lines
22 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/url"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
ldap "github.com/go-ldap/ldap/v3"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type AuthProviderConfig struct {
|
|
UUID string `json:"-"`
|
|
Kind string `json:"kind"`
|
|
Enabled bool `json:"enabled"`
|
|
Issuer string `json:"issuer,omitempty"`
|
|
ClientID string `json:"client_id,omitempty"`
|
|
ClientSecret string `json:"client_secret,omitempty"`
|
|
OIDCMatchBy string `json:"oidc_match_by,omitempty"`
|
|
SMTPAddress string `json:"smtp_address,omitempty"`
|
|
SMTPUsername string `json:"smtp_username,omitempty"`
|
|
SMTPPassword string `json:"smtp_password,omitempty"`
|
|
SMTPFrom string `json:"smtp_from,omitempty"`
|
|
LDAPURL string `json:"ldap_url,omitempty"`
|
|
LDAPBindDN string `json:"ldap_bind_dn,omitempty"`
|
|
LDAPBindPassword string `json:"ldap_bind_password,omitempty"`
|
|
LDAPSearchBase string `json:"ldap_search_base,omitempty"`
|
|
LDAPSearchFilter string `json:"ldap_search_filter,omitempty"`
|
|
LDAPStartTLS bool `json:"ldap_start_tls,omitempty"`
|
|
LDAPSkipTLSVerify bool `json:"ldap_skip_tls_verify,omitempty"`
|
|
LDAPCAPEM string `json:"ldap_ca_pem,omitempty"`
|
|
LDAPUIDAttribute string `json:"ldap_uid_attribute,omitempty"`
|
|
LDAPUsernameAttribute string `json:"ldap_username_attribute,omitempty"`
|
|
LDAPEmailAttribute string `json:"ldap_email_attribute,omitempty"`
|
|
LDAPDisplayAttribute string `json:"ldap_display_attribute,omitempty"`
|
|
LDAPMatchBy string `json:"ldap_match_by,omitempty"`
|
|
LDAPAutoProvision bool `json:"ldap_auto_provision,omitempty"`
|
|
}
|
|
|
|
var ldapAttributePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]*(;[A-Za-z0-9-]+)*$`)
|
|
|
|
func normalizeLDAPProviderConfig(config *AuthProviderConfig) {
|
|
config.LDAPURL = strings.TrimSpace(config.LDAPURL)
|
|
config.LDAPBindDN = strings.TrimSpace(config.LDAPBindDN)
|
|
config.LDAPSearchBase = strings.TrimSpace(config.LDAPSearchBase)
|
|
config.LDAPSearchFilter = strings.TrimSpace(config.LDAPSearchFilter)
|
|
if config.LDAPSearchFilter == "" {
|
|
config.LDAPSearchFilter = "(uid={{username}})"
|
|
}
|
|
defaults := map[*string]string{
|
|
&config.LDAPUIDAttribute: "uid", &config.LDAPUsernameAttribute: "uid",
|
|
&config.LDAPEmailAttribute: "mail", &config.LDAPDisplayAttribute: "displayName",
|
|
}
|
|
for target, fallback := range defaults {
|
|
*target = strings.TrimSpace(*target)
|
|
if *target == "" {
|
|
*target = fallback
|
|
}
|
|
}
|
|
config.LDAPMatchBy = strings.ToLower(strings.TrimSpace(config.LDAPMatchBy))
|
|
if config.LDAPMatchBy == "" {
|
|
config.LDAPMatchBy = "username"
|
|
}
|
|
config.LDAPCAPEM = strings.TrimSpace(config.LDAPCAPEM)
|
|
}
|
|
|
|
// ValidateLDAPProviderConfig checks only administrator-controlled connection
|
|
// metadata. It never opens the configured network endpoint.
|
|
func ValidateLDAPProviderConfig(config AuthProviderConfig) error {
|
|
normalizeLDAPProviderConfig(&config)
|
|
if !config.Enabled && config.LDAPURL == "" {
|
|
return nil
|
|
}
|
|
if len(config.LDAPURL) > 2048 || len(config.LDAPBindDN) > 2048 || len(config.LDAPSearchBase) > 2048 || len(config.LDAPSearchFilter) > 2048 || len(config.LDAPCAPEM) > 64<<10 {
|
|
return errors.New("LDAP setting exceeds its size limit")
|
|
}
|
|
parsed, err := url.Parse(config.LDAPURL)
|
|
if err != nil || (parsed.Scheme != "ldap" && parsed.Scheme != "ldaps") || parsed.Hostname() == "" || parsed.User != nil || (parsed.Path != "" && parsed.Path != "/") || parsed.RawQuery != "" || parsed.Fragment != "" {
|
|
return errors.New("LDAP URL must be ldap://host[:port] or ldaps://host[:port]")
|
|
}
|
|
if parsed.Scheme == "ldaps" && config.LDAPStartTLS {
|
|
return errors.New("StartTLS cannot be combined with an ldaps URL")
|
|
}
|
|
if config.LDAPSearchBase == "" || strings.Count(config.LDAPSearchFilter, "{{username}}") == 0 {
|
|
return errors.New("LDAP search base and a filter containing {{username}} are required")
|
|
}
|
|
if _, err := ldap.ParseDN(config.LDAPSearchBase); err != nil {
|
|
return errors.New("invalid LDAP search base DN")
|
|
}
|
|
if config.LDAPBindDN != "" {
|
|
if _, err := ldap.ParseDN(config.LDAPBindDN); err != nil {
|
|
return errors.New("invalid LDAP service bind DN")
|
|
}
|
|
}
|
|
if _, err := ldap.CompileFilter(strings.ReplaceAll(config.LDAPSearchFilter, "{{username}}", "validation-user")); err != nil {
|
|
return errors.New("invalid LDAP search filter")
|
|
}
|
|
for _, attribute := range []string{config.LDAPUIDAttribute, config.LDAPUsernameAttribute, config.LDAPEmailAttribute, config.LDAPDisplayAttribute} {
|
|
if !ldapAttributePattern.MatchString(attribute) || len(attribute) > 128 {
|
|
return errors.New("invalid LDAP attribute mapping")
|
|
}
|
|
}
|
|
if config.LDAPMatchBy != "username" && config.LDAPMatchBy != "email" {
|
|
return errors.New("unsupported LDAP account matching field")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func externalIdentityPayload(attributes any) (string, error) {
|
|
payload, err := json.Marshal(attributes)
|
|
if err != nil || len(payload) > 64<<10 {
|
|
if err == nil {
|
|
err = errors.New("external identity attributes exceed 64 KiB")
|
|
}
|
|
return "", err
|
|
}
|
|
return string(payload), nil
|
|
}
|
|
|
|
// BindExternalIdentityIfProviderUnbound performs the first-login bootstrap
|
|
// without allowing a recreated external account with the same mutable username
|
|
// or email to replace an identity already bound from this provider.
|
|
func (s *Store) BindExternalIdentityIfProviderUnbound(domainUUID, principalUUID, providerType, providerUUID, issuer, subject string, attributes any) error {
|
|
if domainUUID == "" || principalUUID == "" || providerType == "" || providerUUID == "" || strings.TrimSpace(subject) == "" {
|
|
return ErrAccessDenied
|
|
}
|
|
payload, err := externalIdentityPayload(attributes)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
|
var eligible, alreadyBound bool
|
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active' WHERE p.uuid=`+s.sqlParam(2)+` AND p.state IN ('active','readonly'))`, domainUUID, principalUUID).Scan(&eligible); err != nil || !eligible {
|
|
return ErrAccessDenied
|
|
}
|
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM principal_identities WHERE principal_uuid=`+s.sqlParam(1)+` AND provider_type=`+s.sqlParam(2)+` AND provider_uuid=`+s.sqlParam(3)+`)`, principalUUID, providerType, providerUUID).Scan(&alreadyBound); err != nil || alreadyBound {
|
|
return ErrAccessDenied
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `INSERT INTO principal_identities(uuid,principal_uuid,provider_type,provider_uuid,issuer,subject,attributes_json,created_at_ms) VALUES(`+s.sqlValues(8)+`)`, uuid.NewString(), principalUUID, providerType, providerUUID, issuer, subject, payload, time.Now().UnixMilli()); err != nil {
|
|
return ErrAccessDenied
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// ProvisionExternalAccount creates a normal Domain member with a local
|
|
// username identity but no local password credential, and binds the immutable
|
|
// directory identity in the same transaction.
|
|
func (s *Store) ProvisionExternalAccount(domainUUID, username, displayName, email, providerType, providerUUID, issuer, subject string, attributes any) (*Principal, error) {
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
if !authUsernamePattern.MatchString(username) || domainUUID == "" || providerType == "" || providerUUID == "" || strings.TrimSpace(subject) == "" {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
payload, err := externalIdentityPayload(attributes)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
p := &Principal{UUID: uuid.NewString(), Username: username, DisplayName: strings.TrimSpace(displayName), Email: strings.TrimSpace(email), State: "active"}
|
|
if p.DisplayName == "" {
|
|
p.DisplayName = username
|
|
}
|
|
err = s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
|
if s.sqlBackend == storePostgreSQL {
|
|
var present bool
|
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=$1 AND enabled=1 AND placement='local')`, domainUUID).Scan(&present); err != nil {
|
|
return err
|
|
}
|
|
if !present {
|
|
return sql.ErrNoRows
|
|
}
|
|
}
|
|
roleID := ""
|
|
err = tx.QueryRowContext(ctx, `SELECT uuid FROM auth_roles WHERE domain_uuid=`+s.sqlParam(1)+` AND name='member'`, domainUUID).Scan(&roleID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
roleID = uuid.NewString()
|
|
if _, err = tx.ExecContext(ctx, `INSERT INTO auth_roles(uuid,domain_uuid,name,description,created_at_ms) VALUES(`+s.sqlValues(5)+`)`, roleID, domainUUID, "member", "Domain member", now); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `INSERT INTO auth_capability_grants(uuid,role_uuid,capability,target_type,target_id,created_at_ms) VALUES(`+s.sqlValues(6)+`)`, uuid.NewString(), roleID, "read", "domain", domainUUID, now); err != nil {
|
|
return err
|
|
}
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
membershipID := uuid.NewString()
|
|
for _, item := range []struct {
|
|
query string
|
|
args []any
|
|
}{
|
|
{`INSERT INTO principals(uuid,display_name,email,state,created_at_ms,updated_at_ms) VALUES(` + s.sqlValues(6) + `)`, []any{p.UUID, p.DisplayName, p.Email, p.State, now, now}},
|
|
{`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,subject,created_at_ms) VALUES(` + s.sqlValues(5) + `)`, []any{uuid.NewString(), p.UUID, "password", username, now}},
|
|
{`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,provider_uuid,issuer,subject,attributes_json,created_at_ms) VALUES(` + s.sqlValues(8) + `)`, []any{uuid.NewString(), p.UUID, providerType, providerUUID, issuer, subject, payload, now}},
|
|
{`INSERT INTO domain_memberships(uuid,domain_uuid,principal_uuid,state,created_at_ms) VALUES(` + s.sqlValues(5) + `)`, []any{membershipID, domainUUID, p.UUID, "active", now}},
|
|
{`INSERT INTO auth_role_bindings(membership_uuid,role_uuid,created_at_ms) VALUES(` + s.sqlValues(3) + `)`, []any{membershipID, roleID, now}},
|
|
} {
|
|
if _, err = tx.ExecContext(ctx, item.query, item.args...); err != nil {
|
|
return ErrAccessDenied
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func (s *Store) SetAuthProviderConfig(domainUUID string, config AuthProviderConfig) error {
|
|
config.Kind = strings.ToLower(strings.TrimSpace(config.Kind))
|
|
if config.Kind != "oidc" && config.Kind != "smtp" && config.Kind != "ldap" {
|
|
return errors.New("unsupported authentication provider")
|
|
}
|
|
if config.Kind == "oidc" {
|
|
config.OIDCMatchBy = strings.ToLower(strings.TrimSpace(config.OIDCMatchBy))
|
|
if config.OIDCMatchBy == "" {
|
|
config.OIDCMatchBy = "email"
|
|
}
|
|
if config.OIDCMatchBy != "email" && config.OIDCMatchBy != "display_name" && config.OIDCMatchBy != "preferred_username" {
|
|
return errors.New("unsupported OIDC account matching field")
|
|
}
|
|
}
|
|
if config.Kind == "ldap" {
|
|
normalizeLDAPProviderConfig(&config)
|
|
if err := ValidateLDAPProviderConfig(config); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
secret := config.ClientSecret
|
|
if config.Kind == "smtp" {
|
|
secret = config.SMTPPassword
|
|
} else if config.Kind == "ldap" {
|
|
secret = config.LDAPBindPassword
|
|
}
|
|
config.ClientSecret, config.SMTPPassword, config.LDAPBindPassword = "", "", ""
|
|
payload, err := json.Marshal(config)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
encrypted := ""
|
|
if secret != "" {
|
|
encrypted, err = s.encryptAuthSecret([]byte(secret))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
enabled := 0
|
|
if config.Enabled {
|
|
enabled = 1
|
|
}
|
|
// Preserve the current secret inside the UPSERT, not via a stale pre-read.
|
|
_, err = s.DB.Exec(`INSERT INTO auth_providers(uuid,domain_uuid,kind,config_json,secret_encrypted,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(8)+`) ON CONFLICT(domain_uuid,kind) DO UPDATE SET config_json=excluded.config_json,secret_encrypted=CASE WHEN excluded.secret_encrypted='' THEN auth_providers.secret_encrypted ELSE excluded.secret_encrypted END,enabled=excluded.enabled,updated_at_ms=excluded.updated_at_ms`, uuid.NewString(), domainUUID, config.Kind, string(payload), encrypted, enabled, time.Now().UnixMilli(), time.Now().UnixMilli())
|
|
return s.sqlError("auth provider update", err)
|
|
}
|
|
|
|
func (s *Store) AuthProviderConfig(domainUUID, kind string) (AuthProviderConfig, error) {
|
|
var config AuthProviderConfig
|
|
var payload, encrypted string
|
|
var enabled bool
|
|
err := s.DB.QueryRow(`SELECT uuid,config_json,secret_encrypted,enabled FROM auth_providers WHERE domain_uuid=`+s.sqlParam(1)+` AND kind=`+s.sqlParam(2)+``, domainUUID, kind).Scan(&config.UUID, &payload, &encrypted, &enabled)
|
|
if err != nil {
|
|
return config, s.sqlError("auth provider lookup", err)
|
|
}
|
|
if err := json.Unmarshal([]byte(payload), &config); err != nil {
|
|
return config, err
|
|
}
|
|
config.Enabled = enabled
|
|
if kind == "oidc" {
|
|
config.OIDCMatchBy = strings.ToLower(strings.TrimSpace(config.OIDCMatchBy))
|
|
if config.OIDCMatchBy != "display_name" && config.OIDCMatchBy != "preferred_username" {
|
|
// Missing legacy values and unrecognized values both fail back to the
|
|
// stricter verified-email bootstrap policy.
|
|
config.OIDCMatchBy = "email"
|
|
}
|
|
}
|
|
if kind == "ldap" {
|
|
normalizeLDAPProviderConfig(&config)
|
|
}
|
|
if encrypted != "" {
|
|
secret, err := s.decryptAuthSecret(encrypted)
|
|
if err != nil {
|
|
return config, err
|
|
}
|
|
if kind == "oidc" {
|
|
config.ClientSecret = string(secret)
|
|
} else if kind == "smtp" {
|
|
config.SMTPPassword = string(secret)
|
|
} else if kind == "ldap" {
|
|
config.LDAPBindPassword = string(secret)
|
|
}
|
|
}
|
|
return config, nil
|
|
}
|
|
|
|
// PrincipalByExternalUsername resolves the OIDC preferred_username claim to
|
|
// the local password username while enforcing the same account and Domain
|
|
// membership state checks as the other external-login bootstrap strategies.
|
|
func (s *Store) PrincipalByExternalUsername(domainUUID, username string) (*Principal, error) {
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
if username == "" || domainUUID == "" {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
rows, err := s.DB.Query(`SELECT p.uuid,i.subject,p.display_name,p.email,p.state,length(p.avatar)>0
|
|
FROM principal_identities i JOIN principals p ON p.uuid=i.principal_uuid
|
|
JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active'
|
|
WHERE i.provider_type='password' AND i.subject=`+s.sqlParam(2)+` AND p.state IN ('active','readonly') LIMIT 2`, domainUUID, username)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var found *Principal
|
|
for rows.Next() {
|
|
if found != nil {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
var principal Principal
|
|
if err := rows.Scan(&principal.UUID, &principal.Username, &principal.DisplayName, &principal.Email, &principal.State, &principal.HasAvatar); err != nil {
|
|
return nil, err
|
|
}
|
|
found = &principal
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if found == nil {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
return found, nil
|
|
}
|
|
|
|
func (s *Store) PrincipalByVerifiedEmail(domainUUID, email string) (*Principal, error) {
|
|
email = strings.ToLower(strings.TrimSpace(email))
|
|
if email == "" || domainUUID == "" {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
rows, err := s.DB.Query(`SELECT p.uuid,COALESCE((SELECT subject FROM principal_identities i WHERE i.principal_uuid=p.uuid AND i.provider_type='password' ORDER BY subject,uuid LIMIT 1),p.uuid),p.display_name,p.email,p.state,length(p.avatar)>0 FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active' WHERE lower(p.email)=`+s.sqlParam(2)+` AND p.state IN ('active','readonly') LIMIT 2`, domainUUID, email)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var found *Principal
|
|
for rows.Next() {
|
|
if found != nil {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
var p Principal
|
|
if err := rows.Scan(&p.UUID, &p.Username, &p.DisplayName, &p.Email, &p.State, &p.HasAvatar); err != nil {
|
|
return nil, err
|
|
}
|
|
found = &p
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if found == nil {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
return found, nil
|
|
}
|
|
|
|
// PrincipalByDisplayName deliberately requires an exact, unique match inside
|
|
// the active Domain membership. Display names are mutable and not identifiers;
|
|
// this is only a first-login bootstrap before the provider issuer+sub binding
|
|
// becomes authoritative.
|
|
func (s *Store) PrincipalByDisplayName(domainUUID, displayName string) (*Principal, error) {
|
|
displayName = strings.TrimSpace(displayName)
|
|
if displayName == "" || domainUUID == "" {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
rows, err := s.DB.Query(`SELECT p.uuid,
|
|
COALESCE((SELECT subject FROM principal_identities i WHERE i.principal_uuid=p.uuid AND i.provider_type='password' ORDER BY subject,uuid LIMIT 1),p.uuid),
|
|
p.display_name,p.email,p.state,length(p.avatar)>0
|
|
FROM principals p JOIN domain_memberships m
|
|
ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active'
|
|
WHERE p.display_name=`+s.sqlParam(2)+` AND p.state IN ('active','readonly') LIMIT 2`, domainUUID, displayName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var found *Principal
|
|
for rows.Next() {
|
|
if found != nil {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
var principal Principal
|
|
if err := rows.Scan(&principal.UUID, &principal.Username, &principal.DisplayName, &principal.Email, &principal.State, &principal.HasAvatar); err != nil {
|
|
return nil, err
|
|
}
|
|
found = &principal
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if found == nil {
|
|
return nil, ErrAccessDenied
|
|
}
|
|
return found, nil
|
|
}
|
|
|
|
func (s *Store) BindExternalIdentity(principalUUID, providerType, providerUUID, issuer, subject string, attributes any) error {
|
|
if strings.TrimSpace(subject) == "" || strings.TrimSpace(principalUUID) == "" {
|
|
return ErrAccessDenied
|
|
}
|
|
payload, err := json.Marshal(attributes)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
result, err := s.DB.Exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,provider_uuid,issuer,subject,attributes_json,created_at_ms) VALUES(`+s.sqlValues(8)+`) ON CONFLICT(provider_type,provider_uuid,issuer,subject) DO UPDATE SET attributes_json=excluded.attributes_json WHERE principal_identities.principal_uuid=excluded.principal_uuid`, uuid.NewString(), principalUUID, providerType, providerUUID, issuer, subject, string(payload), now)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
changed, err := result.RowsAffected()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if changed != 1 {
|
|
return ErrAccessDenied
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) PrincipalByExternalIdentity(domainUUID, providerType, providerUUID, issuer, subject string) (*Principal, error) {
|
|
var p Principal
|
|
err := s.DB.QueryRow(`SELECT p.uuid,COALESCE((SELECT subject FROM principal_identities x WHERE x.principal_uuid=p.uuid AND x.provider_type='password' ORDER BY subject,uuid LIMIT 1),p.uuid),p.display_name,p.email,p.state,length(p.avatar)>0 FROM principal_identities i JOIN principals p ON p.uuid=i.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active' WHERE i.provider_type=`+s.sqlParam(2)+` AND i.provider_uuid=`+s.sqlParam(3)+` AND i.issuer=`+s.sqlParam(4)+` AND i.subject=`+s.sqlParam(5)+` AND p.state IN ('active','readonly')`, domainUUID, providerType, providerUUID, issuer, subject).Scan(&p.UUID, &p.Username, &p.DisplayName, &p.Email, &p.State, &p.HasAvatar)
|
|
return &p, err
|
|
}
|
|
|
|
func (s *Store) CreateAuthChallenge(domainUUID, principalUUID, kind string, payload any, lifetime time.Duration) (string, error) {
|
|
token, hash, err := authToken()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
encoded, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
_, err = s.DB.Exec(`INSERT INTO auth_challenges(uuid,domain_uuid,principal_uuid,kind,token_hash,payload_json,expires_at_ms,created_at_ms) VALUES(`+s.sqlValues(8)+`)`, uuid.NewString(), domainUUID, principalUUID, kind, hash, string(encoded), now+lifetime.Milliseconds(), now)
|
|
if err != nil {
|
|
return "", s.sqlError("auth challenge creation", err)
|
|
}
|
|
return token, nil
|
|
}
|
|
|
|
func (s *Store) ConsumeAuthChallenge(domainUUID, kind, token string, payload any) (string, error) {
|
|
hash := hashAuthToken(token)
|
|
var id, principalUUID, encoded string
|
|
var expires int64
|
|
err := s.DB.QueryRow(`SELECT uuid,principal_uuid,payload_json,expires_at_ms FROM auth_challenges WHERE domain_uuid=`+s.sqlParam(1)+` AND kind=`+s.sqlParam(2)+` AND token_hash=`+s.sqlParam(3)+` AND consumed_at_ms=0`, domainUUID, kind, hash).Scan(&id, &principalUUID, &encoded, &expires)
|
|
if err != nil || expires < time.Now().UnixMilli() {
|
|
return "", ErrAccessDenied
|
|
}
|
|
result, err := s.DB.Exec(`UPDATE auth_challenges SET consumed_at_ms=`+s.sqlParam(1)+` WHERE uuid=`+s.sqlParam(2)+` AND consumed_at_ms=0 AND expires_at_ms>`+s.sqlParam(3), time.Now().UnixMilli(), id, time.Now().UnixMilli())
|
|
if err != nil {
|
|
return "", s.sqlError("auth challenge consumption", err)
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed != 1 {
|
|
return "", ErrAccessDenied
|
|
}
|
|
if payload != nil && json.Unmarshal([]byte(encoded), payload) != nil {
|
|
return "", ErrAccessDenied
|
|
}
|
|
return principalUUID, nil
|
|
}
|
|
|
|
// A consumed link does not authorize a changed email address or a disabled
|
|
// membership. Keep the HTTP layer independent of the SQL placeholder dialect.
|
|
func (s *Store) ValidateMagicLinkIdentity(ctx context.Context, domain, principal, email string) (bool, error) {
|
|
if email == "" {
|
|
return false, nil
|
|
}
|
|
var valid bool
|
|
err := s.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` WHERE p.uuid=`+s.sqlParam(2)+` AND p.state IN ('active','readonly') AND m.state='active' AND p.email=`+s.sqlParam(3)+`)`, domain, principal, email).Scan(&valid)
|
|
return err == nil && valid, s.sqlError("magic link identity", err)
|
|
}
|
|
|
|
func hashAuthToken(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return base64.RawURLEncoding.EncodeToString(sum[:])
|
|
}
|