// Package auth provides accounts, sessions, API keys and role-based access // control for streamd. Password hashing uses crypto/pbkdf2 from the standard // library, so no third-party crypto dependency is needed. package auth import ( "crypto/pbkdf2" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/hex" "fmt" "strconv" "strings" ) // Role is an access level. Roles are ordered: viewer < operator < admin. type Role string const ( RoleViewer Role = "viewer" RoleOperator Role = "operator" RoleAdmin Role = "admin" ) var roleRank = map[Role]int{ RoleViewer: 1, RoleOperator: 2, RoleAdmin: 3, } // ParseRole validates a role name, defaulting to viewer for anything unknown. func ParseRole(s string) (Role, error) { r := Role(strings.ToLower(strings.TrimSpace(s))) if _, ok := roleRank[r]; !ok { return RoleViewer, fmt.Errorf("unknown role %q (want viewer, operator or admin)", s) } return r, nil } // AtLeast reports whether r grants everything min does. func (r Role) AtLeast(min Role) bool { return roleRank[r] >= roleRank[min] } func (r Role) Valid() bool { _, ok := roleRank[r] return ok } // ActorKind distinguishes a logged-in human from a machine credential. type ActorKind string const ( ActorUser ActorKind = "user" ActorAPIKey ActorKind = "apikey" ActorSystem ActorKind = "system" ) // Principal is the authenticated identity behind a request. type Principal struct { Kind ActorKind Role Role // Name is the username or the API key's label, used for audit rows. Name string // UserID is set for session principals only. UserID int64 // AgentID is the X-Agent-ID a machine caller volunteered, if any. AgentID string // SessionID is the raw session id for session principals (needed to // resolve the CSRF token); empty for bearer principals. SessionID string // CSRFToken is the token a cookie-authenticated caller must echo back. CSRFToken string } // Actor is the audit-log label for this principal. func (p *Principal) Actor() string { if p == nil { return "anonymous" } if p.AgentID != "" && p.Kind == ActorAPIKey { return p.Name + "@" + p.AgentID } return p.Name } // NeedsCSRF is true for ambient (cookie) credentials only. A bearer token is // never sent automatically by a browser, so it carries no CSRF risk. func (p *Principal) NeedsCSRF() bool { return p != nil && p.Kind == ActorUser && p.SessionID != "" } const ( pbkdf2Iterations = 600_000 pbkdf2KeyLen = 32 saltLen = 16 tokenLen = 32 ) // HashPassword returns an encoded PBKDF2-HMAC-SHA256 hash: // // pbkdf2-sha256$$$ func HashPassword(password string) (string, error) { if len(password) < 8 { return "", fmt.Errorf("password must be at least 8 characters") } salt := make([]byte, saltLen) if _, err := rand.Read(salt); err != nil { return "", err } return hashWithSalt(password, salt, pbkdf2Iterations) } func hashWithSalt(password string, salt []byte, iters int) (string, error) { dk, err := pbkdf2.Key(sha256.New, password, salt, iters, pbkdf2KeyLen) if err != nil { return "", err } return fmt.Sprintf("pbkdf2-sha256$%d$%s$%s", iters, base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(dk), ), nil } // VerifyPassword checks a password against an encoded hash in constant time. // A malformed or empty hash always fails, and never panics. func VerifyPassword(encoded, password string) bool { parts := strings.Split(encoded, "$") if len(parts) != 4 || parts[0] != "pbkdf2-sha256" { return false } iters, err := strconv.Atoi(parts[1]) if err != nil || iters <= 0 { return false } salt, err := base64.RawStdEncoding.DecodeString(parts[2]) if err != nil { return false } want, err := base64.RawStdEncoding.DecodeString(parts[3]) if err != nil || len(want) == 0 { return false } got, err := pbkdf2.Key(sha256.New, password, salt, iters, len(want)) if err != nil { return false } return subtle.ConstantTimeCompare(got, want) == 1 } // NewToken returns a URL-safe random secret and its storage hash. Only the // hash is ever persisted, so a database leak does not yield usable credentials. func NewToken() (secret, hash string, err error) { b := make([]byte, tokenLen) if _, err := rand.Read(b); err != nil { return "", "", err } secret = base64.RawURLEncoding.EncodeToString(b) return secret, HashToken(secret), nil } // HashToken is the storage form of a session id or API key. func HashToken(secret string) string { sum := sha256.Sum256([]byte(secret)) return hex.EncodeToString(sum[:]) } // SecretEqual compares two secrets in constant time. func SecretEqual(a, b string) bool { return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 }