ntfy/auth/auth_sqlite.go

328 lines
8.0 KiB
Go
Raw Normal View History

2022-01-23 06:02:16 +01:00
package auth
2022-01-23 05:01:20 +01:00
import (
"database/sql"
2022-01-26 03:57:28 +01:00
_ "github.com/mattn/go-sqlite3" // SQLite driver
2022-01-23 05:01:20 +01:00
"golang.org/x/crypto/bcrypt"
2022-01-26 03:57:28 +01:00
"regexp"
2022-01-23 05:01:20 +01:00
)
2022-01-26 03:57:28 +01:00
const (
bcryptCost = 11
)
2022-01-23 05:01:20 +01:00
2022-01-23 06:54:18 +01:00
// Auther-related queries
2022-01-23 05:01:20 +01:00
const (
createAuthTablesQueries = `
BEGIN;
CREATE TABLE IF NOT EXISTS user (
user TEXT NOT NULL PRIMARY KEY,
pass TEXT NOT NULL,
role TEXT NOT NULL
);
2022-01-23 21:30:30 +01:00
CREATE TABLE IF NOT EXISTS access (
2022-01-23 05:01:20 +01:00
user TEXT NOT NULL,
topic TEXT NOT NULL,
read INT NOT NULL,
write INT NOT NULL,
PRIMARY KEY (topic, user)
);
CREATE TABLE IF NOT EXISTS schema_version (
id INT PRIMARY KEY,
version INT NOT NULL
);
COMMIT;
`
selectUserQuery = `SELECT pass, role FROM user WHERE user = ?`
selectTopicPermsQuery = `
SELECT read, write
2022-01-23 21:30:30 +01:00
FROM access
2022-01-24 06:54:28 +01:00
WHERE user IN ('*', ?) AND topic = ?
2022-01-23 05:01:20 +01:00
ORDER BY user DESC
`
)
2022-01-23 06:54:18 +01:00
// Manager-related queries
const (
2022-01-24 06:54:28 +01:00
insertUserQuery = `INSERT INTO user (user, pass, role) VALUES (?, ?, ?)`
selectUsernamesQuery = `SELECT user FROM user ORDER BY role, user`
updateUserPassQuery = `UPDATE user SET pass = ? WHERE user = ?`
updateUserRoleQuery = `UPDATE user SET role = ? WHERE user = ?`
deleteUserQuery = `DELETE FROM user WHERE user = ?`
upsertUserAccessQuery = `
2022-01-23 21:30:30 +01:00
INSERT INTO access (user, topic, read, write)
VALUES (?, ?, ?, ?)
ON CONFLICT (user, topic) DO UPDATE SET read=excluded.read, write=excluded.write
`
2022-01-24 06:54:28 +01:00
selectUserAccessQuery = `SELECT topic, read, write FROM access WHERE user = ?`
deleteAllAccessQuery = `DELETE FROM access`
deleteUserAccessQuery = `DELETE FROM access WHERE user = ?`
deleteTopicAccessQuery = `DELETE FROM access WHERE user = ? AND topic = ?`
2022-01-23 06:54:18 +01:00
)
2022-01-23 06:02:16 +01:00
type SQLiteAuth struct {
2022-01-23 05:01:20 +01:00
db *sql.DB
defaultRead bool
defaultWrite bool
}
2022-01-26 03:57:28 +01:00
var (
allowedUsernameRegex = regexp.MustCompile(`^[-_.@a-zA-Z0-9]+$`)
)
2022-01-23 06:54:18 +01:00
var _ Auther = (*SQLiteAuth)(nil)
var _ Manager = (*SQLiteAuth)(nil)
2022-01-23 05:01:20 +01:00
2022-01-23 06:02:16 +01:00
func NewSQLiteAuth(filename string, defaultRead, defaultWrite bool) (*SQLiteAuth, error) {
2022-01-23 05:01:20 +01:00
db, err := sql.Open("sqlite3", filename)
if err != nil {
return nil, err
}
if err := setupNewAuthDB(db); err != nil {
return nil, err
}
2022-01-23 06:02:16 +01:00
return &SQLiteAuth{
2022-01-23 05:01:20 +01:00
db: db,
defaultRead: defaultRead,
defaultWrite: defaultWrite,
}, nil
}
func setupNewAuthDB(db *sql.DB) error {
if _, err := db.Exec(createAuthTablesQueries); err != nil {
return err
}
// FIXME schema version
return nil
}
2022-01-23 06:02:16 +01:00
func (a *SQLiteAuth) Authenticate(username, password string) (*User, error) {
2022-01-24 06:54:28 +01:00
if username == Everyone {
2022-01-26 03:57:28 +01:00
return nil, ErrUnauthenticated
2022-01-24 06:54:28 +01:00
}
2022-01-26 03:57:28 +01:00
user, err := a.User(username)
2022-01-23 05:01:20 +01:00
if err != nil {
2022-01-26 03:57:28 +01:00
bcrypt.CompareHashAndPassword([]byte("$2a$11$eX15DeF27FwAgXt9wqJF0uAUMz74XywJcGBH3kP93pzKYv6ATk2ka"),
[]byte("intentional slow-down to avoid timing attacks"))
return nil, ErrUnauthenticated
2022-01-23 05:01:20 +01:00
}
2022-01-26 03:57:28 +01:00
if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password)); err != nil {
return nil, ErrUnauthenticated
2022-01-23 05:01:20 +01:00
}
2022-01-26 03:57:28 +01:00
return user, nil
2022-01-23 05:01:20 +01:00
}
2022-01-23 06:02:16 +01:00
func (a *SQLiteAuth) Authorize(user *User, topic string, perm Permission) error {
2022-01-24 05:02:39 +01:00
if user != nil && user.Role == RoleAdmin {
2022-01-23 05:01:20 +01:00
return nil // Admin can do everything
}
// Select the read/write permissions for this user/topic combo. The query may return two
// rows (one for everyone, and one for the user), but prioritizes the user. The value for
// user.Name may be empty (= everyone).
2022-01-24 06:54:28 +01:00
username := Everyone
2022-01-24 05:02:39 +01:00
if user != nil {
username = user.Name
}
rows, err := a.db.Query(selectTopicPermsQuery, username, topic)
2022-01-23 05:01:20 +01:00
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
return a.resolvePerms(a.defaultRead, a.defaultWrite, perm)
}
var read, write bool
if err := rows.Scan(&read, &write); err != nil {
return err
} else if err := rows.Err(); err != nil {
return err
}
return a.resolvePerms(read, write, perm)
}
2022-01-23 06:02:16 +01:00
func (a *SQLiteAuth) resolvePerms(read, write bool, perm Permission) error {
if perm == PermissionRead && read {
2022-01-23 05:01:20 +01:00
return nil
2022-01-23 06:02:16 +01:00
} else if perm == PermissionWrite && write {
2022-01-23 05:01:20 +01:00
return nil
}
2022-01-23 06:02:16 +01:00
return ErrUnauthorized
2022-01-23 05:01:20 +01:00
}
2022-01-23 06:54:18 +01:00
func (a *SQLiteAuth) AddUser(username, password string, role Role) error {
2022-01-26 03:57:28 +01:00
if !allowedUsernameRegex.MatchString(username) || (role != RoleAdmin && role != RoleUser) {
return ErrInvalidArgument
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
2022-01-23 06:54:18 +01:00
if err != nil {
return err
}
2022-01-24 05:02:39 +01:00
if _, err = a.db.Exec(insertUserQuery, username, hash, role); err != nil {
2022-01-23 06:54:18 +01:00
return err
}
return nil
}
func (a *SQLiteAuth) RemoveUser(username string) error {
2022-01-26 03:57:28 +01:00
if !allowedUsernameRegex.MatchString(username) || username == Everyone {
return ErrInvalidArgument
}
2022-01-24 05:02:39 +01:00
if _, err := a.db.Exec(deleteUserQuery, username); err != nil {
2022-01-23 06:54:18 +01:00
return err
}
2022-01-24 06:54:28 +01:00
if _, err := a.db.Exec(deleteUserAccessQuery, username); err != nil {
2022-01-23 06:54:18 +01:00
return err
}
return nil
}
2022-01-24 05:02:39 +01:00
func (a *SQLiteAuth) Users() ([]*User, error) {
rows, err := a.db.Query(selectUsernamesQuery)
if err != nil {
return nil, err
}
defer rows.Close()
usernames := make([]string, 0)
for rows.Next() {
var username string
if err := rows.Scan(&username); err != nil {
return nil, err
} else if err := rows.Err(); err != nil {
return nil, err
}
usernames = append(usernames, username)
}
rows.Close()
users := make([]*User, 0)
for _, username := range usernames {
user, err := a.User(username)
if err != nil {
return nil, err
}
users = append(users, user)
}
2022-01-24 06:54:28 +01:00
everyone, err := a.everyoneUser()
if err != nil {
return nil, err
}
users = append(users, everyone)
2022-01-24 05:02:39 +01:00
return users, nil
}
func (a *SQLiteAuth) User(username string) (*User, error) {
2022-01-24 06:54:28 +01:00
if username == Everyone {
return a.everyoneUser()
}
2022-01-26 03:57:28 +01:00
rows, err := a.db.Query(selectUserQuery, username)
2022-01-24 05:02:39 +01:00
if err != nil {
return nil, err
}
2022-01-26 03:57:28 +01:00
defer rows.Close()
2022-01-24 05:02:39 +01:00
var hash, role string
2022-01-26 03:57:28 +01:00
if !rows.Next() {
2022-01-24 05:02:39 +01:00
return nil, ErrNotFound
}
2022-01-26 03:57:28 +01:00
if err := rows.Scan(&hash, &role); err != nil {
2022-01-24 05:02:39 +01:00
return nil, err
2022-01-26 03:57:28 +01:00
} else if err := rows.Err(); err != nil {
2022-01-24 05:02:39 +01:00
return nil, err
}
2022-01-24 06:54:28 +01:00
grants, err := a.readGrants(username)
if err != nil {
return nil, err
}
return &User{
Name: username,
2022-01-26 03:57:28 +01:00
Hash: hash,
2022-01-24 06:54:28 +01:00
Role: Role(role),
Grants: grants,
}, nil
}
func (a *SQLiteAuth) everyoneUser() (*User, error) {
grants, err := a.readGrants(Everyone)
if err != nil {
return nil, err
}
return &User{
Name: Everyone,
2022-01-26 03:57:28 +01:00
Hash: "",
2022-01-24 06:54:28 +01:00
Role: RoleAnonymous,
Grants: grants,
}, nil
}
func (a *SQLiteAuth) readGrants(username string) ([]Grant, error) {
rows, err := a.db.Query(selectUserAccessQuery, username)
2022-01-24 05:02:39 +01:00
if err != nil {
return nil, err
}
2022-01-24 06:54:28 +01:00
defer rows.Close()
2022-01-24 05:02:39 +01:00
grants := make([]Grant, 0)
2022-01-24 06:54:28 +01:00
for rows.Next() {
2022-01-24 05:02:39 +01:00
var topic string
var read, write bool
2022-01-24 06:54:28 +01:00
if err := rows.Scan(&topic, &read, &write); err != nil {
2022-01-24 05:02:39 +01:00
return nil, err
2022-01-24 06:54:28 +01:00
} else if err := rows.Err(); err != nil {
2022-01-24 05:02:39 +01:00
return nil, err
}
grants = append(grants, Grant{
Topic: topic,
Read: read,
Write: write,
})
}
2022-01-24 06:54:28 +01:00
return grants, nil
2022-01-24 05:02:39 +01:00
}
2022-01-23 06:54:18 +01:00
func (a *SQLiteAuth) ChangePassword(username, password string) error {
2022-01-26 03:57:28 +01:00
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
2022-01-23 06:54:18 +01:00
if err != nil {
return err
}
2022-01-24 05:02:39 +01:00
if _, err := a.db.Exec(updateUserPassQuery, hash, username); err != nil {
2022-01-23 06:54:18 +01:00
return err
}
return nil
}
2022-01-23 21:30:30 +01:00
func (a *SQLiteAuth) ChangeRole(username string, role Role) error {
2022-01-26 03:57:28 +01:00
if !allowedUsernameRegex.MatchString(username) || (role != RoleAdmin && role != RoleUser) {
return ErrInvalidArgument
}
2022-01-24 05:02:39 +01:00
if _, err := a.db.Exec(updateUserRoleQuery, string(role), username); err != nil {
2022-01-23 21:30:30 +01:00
return err
}
2022-01-24 05:02:39 +01:00
if role == RoleAdmin {
2022-01-24 06:54:28 +01:00
if _, err := a.db.Exec(deleteUserAccessQuery, username); err != nil {
2022-01-24 05:02:39 +01:00
return err
}
}
2022-01-23 21:30:30 +01:00
return nil
}
2022-01-24 06:54:28 +01:00
func (a *SQLiteAuth) DefaultAccess() (read bool, write bool) {
return a.defaultRead, a.defaultWrite
}
2022-01-23 21:30:30 +01:00
func (a *SQLiteAuth) AllowAccess(username string, topic string, read bool, write bool) error {
2022-01-24 06:54:28 +01:00
if _, err := a.db.Exec(upsertUserAccessQuery, username, topic, read, write); err != nil {
2022-01-23 21:30:30 +01:00
return err
}
return nil
}
func (a *SQLiteAuth) ResetAccess(username string, topic string) error {
2022-01-24 06:54:28 +01:00
if username == "" && topic == "" {
_, err := a.db.Exec(deleteAllAccessQuery, username)
return err
} else if topic == "" {
_, err := a.db.Exec(deleteUserAccessQuery, username)
return err
2022-01-23 21:30:30 +01:00
}
2022-01-24 06:54:28 +01:00
_, err := a.db.Exec(deleteTopicAccessQuery, username, topic)
return err
2022-01-23 21:30:30 +01:00
}