ntfy/auth/auth_sqlite.go

493 lines
14 KiB
Go
Raw Normal View History

2022-01-23 05:02:16 +00:00
package auth
2022-01-23 04:01:20 +00:00
import (
"database/sql"
2022-12-08 02:26:18 +00:00
"encoding/json"
"errors"
"fmt"
2022-01-26 02:57:28 +00:00
_ "github.com/mattn/go-sqlite3" // SQLite driver
2022-01-23 04:01:20 +00:00
"golang.org/x/crypto/bcrypt"
2022-12-03 20:20:59 +00:00
"heckel.io/ntfy/util"
2022-01-31 16:44:58 +00:00
"strings"
2022-01-23 04:01:20 +00:00
)
2022-01-26 02:57:28 +00:00
const (
2022-12-03 20:20:59 +00:00
tokenLength = 32
2022-02-08 03:09:31 +00:00
bcryptCost = 10
intentionalSlowDownHash = "$2a$10$YFCQvqQDwIIwnJM1xkAYOeih0dg17UVGanaTStnrSzC8NCWxcLDwy" // Cost should match bcryptCost
2022-01-26 02:57:28 +00:00
)
2022-01-23 04:01:20 +00:00
2022-01-23 05:54:18 +00:00
// Auther-related queries
2022-01-23 04:01:20 +00:00
const (
createAuthTablesQueries = `
BEGIN;
2022-12-02 20:37:48 +00:00
CREATE TABLE IF NOT EXISTS plan (
id INT NOT NULL,
name TEXT NOT NULL,
limit_messages INT,
PRIMARY KEY (id)
);
2022-01-23 04:01:20 +00:00
CREATE TABLE IF NOT EXISTS user (
2022-12-02 20:37:48 +00:00
id INTEGER PRIMARY KEY AUTOINCREMENT,
plan_id INT,
user TEXT NOT NULL,
2022-01-23 04:01:20 +00:00
pass TEXT NOT NULL,
2022-12-02 20:37:48 +00:00
role TEXT NOT NULL,
2022-12-08 02:26:18 +00:00
settings JSON,
2022-12-02 20:37:48 +00:00
FOREIGN KEY (plan_id) REFERENCES plan (id)
2022-01-23 04:01:20 +00:00
);
2022-12-02 20:37:48 +00:00
CREATE UNIQUE INDEX idx_user ON user (user);
CREATE TABLE IF NOT EXISTS user_access (
user_id INT NOT NULL,
2022-01-23 04:01:20 +00:00
topic TEXT NOT NULL,
read INT NOT NULL,
write INT NOT NULL,
2022-12-02 20:37:48 +00:00
PRIMARY KEY (user_id, topic),
FOREIGN KEY (user_id) REFERENCES user (id)
2022-12-08 02:26:18 +00:00
);
2022-12-02 20:37:48 +00:00
CREATE TABLE IF NOT EXISTS user_token (
user_id INT NOT NULL,
2022-12-05 01:33:17 +00:00
token TEXT NOT NULL,
2022-12-02 20:37:48 +00:00
expires INT NOT NULL,
2022-12-05 01:33:17 +00:00
PRIMARY KEY (user_id, token)
2022-12-02 20:37:48 +00:00
);
CREATE TABLE IF NOT EXISTS schemaVersion (
2022-01-23 04:01:20 +00:00
id INT PRIMARY KEY,
version INT NOT NULL
);
2022-12-02 20:37:48 +00:00
INSERT INTO plan (id, name) VALUES (1, 'Admin') ON CONFLICT (id) DO NOTHING;
INSERT INTO user (id, user, pass, role) VALUES (1, '*', '', 'anonymous') ON CONFLICT (id) DO NOTHING;
2022-01-23 04:01:20 +00:00
COMMIT;
`
2022-12-03 20:20:59 +00:00
selectUserByNameQuery = `
2022-12-08 02:26:18 +00:00
SELECT user, pass, role, settings
2022-12-03 20:20:59 +00:00
FROM user
WHERE user = ?
`
selectUserByTokenQuery = `
2022-12-08 02:26:18 +00:00
SELECT user, pass, role, settings
2022-12-03 20:20:59 +00:00
FROM user
JOIN user_token on user.id = user_token.user_id
WHERE token = ?
`
2022-01-23 04:01:20 +00:00
selectTopicPermsQuery = `
SELECT read, write
2022-12-02 20:37:48 +00:00
FROM user_access
JOIN user ON user.user = '*' OR user.user = ?
WHERE ? LIKE user_access.topic
ORDER BY user.user DESC
2022-01-23 04:01:20 +00:00
`
)
2022-01-23 05:54:18 +00:00
// Manager-related queries
const (
2022-01-24 05:54:28 +00: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 = ?`
2022-12-02 20:37:48 +00:00
upsertUserAccessQuery = `INSERT INTO user_access (user_id, topic, read, write) VALUES ((SELECT id FROM user WHERE user = ?), ?, ?, ?)`
selectUserAccessQuery = `SELECT topic, read, write FROM user_access WHERE user_id = (SELECT id FROM user WHERE user = ?)`
deleteAllAccessQuery = `DELETE FROM user_access`
deleteUserAccessQuery = `DELETE FROM user_access WHERE user_id = (SELECT id FROM user WHERE user = ?)`
deleteTopicAccessQuery = `DELETE FROM user_access WHERE user_id = (SELECT id FROM user WHERE user = ?) AND topic = ?`
2022-12-03 20:20:59 +00:00
2022-12-08 02:26:18 +00:00
insertTokenQuery = `INSERT INTO user_token (user_id, token, expires) VALUES ((SELECT id FROM user WHERE user = ?), ?, ?)`
deleteTokenQuery = `DELETE FROM user_token WHERE user_id = (SELECT id FROM user WHERE user = ?) AND token = ?`
updateUserSettingsQuery = `UPDATE user SET settings = ? WHERE user = ?`
2022-01-23 05:54:18 +00:00
)
// Schema management queries
const (
currentSchemaVersion = 1
insertSchemaVersion = `INSERT INTO schemaVersion VALUES (1, ?)`
selectSchemaVersionQuery = `SELECT version FROM schemaVersion WHERE id = 1`
)
2022-01-26 03:30:53 +00:00
// SQLiteAuth is an implementation of Auther and Manager. It stores users and access control list
// in a SQLite database.
2022-01-23 05:02:16 +00:00
type SQLiteAuth struct {
2022-01-23 04:01:20 +00:00
db *sql.DB
defaultRead bool
defaultWrite bool
}
2022-01-23 05:54:18 +00:00
var _ Auther = (*SQLiteAuth)(nil)
var _ Manager = (*SQLiteAuth)(nil)
2022-01-23 04:01:20 +00:00
2022-01-26 03:30:53 +00:00
// NewSQLiteAuth creates a new SQLiteAuth instance
2022-01-23 05:02:16 +00:00
func NewSQLiteAuth(filename string, defaultRead, defaultWrite bool) (*SQLiteAuth, error) {
2022-01-23 04:01:20 +00:00
db, err := sql.Open("sqlite3", filename)
if err != nil {
return nil, err
}
if err := setupAuthDB(db); err != nil {
2022-01-23 04:01:20 +00:00
return nil, err
}
2022-01-23 05:02:16 +00:00
return &SQLiteAuth{
2022-01-23 04:01:20 +00:00
db: db,
defaultRead: defaultRead,
defaultWrite: defaultWrite,
}, nil
}
2022-12-08 01:44:20 +00:00
// Authenticate checks username and password and returns a user if correct. The method
2022-01-26 03:30:53 +00:00
// returns in constant-ish time, regardless of whether the user exists or the password is
// correct or incorrect.
2022-01-23 05:02:16 +00:00
func (a *SQLiteAuth) Authenticate(username, password string) (*User, error) {
2022-01-24 05:54:28 +00:00
if username == Everyone {
2022-01-26 02:57:28 +00:00
return nil, ErrUnauthenticated
2022-01-24 05:54:28 +00:00
}
2022-01-26 02:57:28 +00:00
user, err := a.User(username)
2022-01-23 04:01:20 +00:00
if err != nil {
bcrypt.CompareHashAndPassword([]byte(intentionalSlowDownHash),
2022-01-26 02:57:28 +00:00
[]byte("intentional slow-down to avoid timing attacks"))
return nil, ErrUnauthenticated
2022-01-23 04:01:20 +00:00
}
2022-01-26 02:57:28 +00:00
if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password)); err != nil {
return nil, ErrUnauthenticated
2022-01-23 04:01:20 +00:00
}
2022-01-26 02:57:28 +00:00
return user, nil
2022-01-23 04:01:20 +00:00
}
2022-12-03 20:20:59 +00:00
func (a *SQLiteAuth) AuthenticateToken(token string) (*User, error) {
user, err := a.userByToken(token)
if err != nil {
return nil, ErrUnauthenticated
}
2022-12-08 01:44:20 +00:00
user.Token = token
2022-12-03 20:20:59 +00:00
return user, nil
}
2022-12-08 01:44:20 +00:00
func (a *SQLiteAuth) CreateToken(user *User) (string, error) {
2022-12-03 20:20:59 +00:00
token := util.RandomString(tokenLength)
expires := 1 // FIXME
if _, err := a.db.Exec(insertTokenQuery, user.Name, token, expires); err != nil {
return "", err
}
return token, nil
}
2022-12-08 01:44:20 +00:00
func (a *SQLiteAuth) RemoveToken(user *User) error {
if user.Token == "" {
return ErrUnauthorized
}
if _, err := a.db.Exec(deleteTokenQuery, user.Name, user.Token); err != nil {
return err
}
return nil
}
2022-12-08 02:26:18 +00:00
func (a *SQLiteAuth) ChangeSettings(user *User) error {
settings, err := json.Marshal(user.Prefs)
if err != nil {
return err
}
if _, err := a.db.Exec(updateUserSettingsQuery, string(settings), user.Name); err != nil {
return err
}
return nil
}
2022-01-26 03:30:53 +00:00
// Authorize returns nil if the given user has access to the given topic using the desired
// permission. The user param may be nil to signal an anonymous user.
2022-01-23 05:02:16 +00:00
func (a *SQLiteAuth) Authorize(user *User, topic string, perm Permission) error {
2022-01-24 04:02:39 +00:00
if user != nil && user.Role == RoleAdmin {
2022-01-23 04:01:20 +00:00
return nil // Admin can do everything
}
2022-01-24 05:54:28 +00:00
username := Everyone
2022-01-24 04:02:39 +00:00
if user != nil {
username = user.Name
}
2022-01-26 03:30:53 +00:00
// 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 04:02:39 +00:00
rows, err := a.db.Query(selectTopicPermsQuery, username, topic)
2022-01-23 04:01:20 +00: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 05:02:16 +00:00
func (a *SQLiteAuth) resolvePerms(read, write bool, perm Permission) error {
if perm == PermissionRead && read {
2022-01-23 04:01:20 +00:00
return nil
2022-01-23 05:02:16 +00:00
} else if perm == PermissionWrite && write {
2022-01-23 04:01:20 +00:00
return nil
}
2022-01-23 05:02:16 +00:00
return ErrUnauthorized
2022-01-23 04:01:20 +00:00
}
2022-01-23 05:54:18 +00:00
2022-01-26 03:30:53 +00:00
// AddUser adds a user with the given username, password and role. The password should be hashed
// before it is stored in a persistence layer.
2022-01-23 05:54:18 +00:00
func (a *SQLiteAuth) AddUser(username, password string, role Role) error {
2022-01-31 16:44:58 +00:00
if !AllowedUsername(username) || !AllowedRole(role) {
2022-01-26 02:57:28 +00:00
return ErrInvalidArgument
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
2022-01-23 05:54:18 +00:00
if err != nil {
return err
}
2022-01-24 04:02:39 +00:00
if _, err = a.db.Exec(insertUserQuery, username, hash, role); err != nil {
2022-01-23 05:54:18 +00:00
return err
}
return nil
}
2022-01-26 03:30:53 +00:00
// RemoveUser deletes the user with the given username. The function returns nil on success, even
// if the user did not exist in the first place.
2022-01-23 05:54:18 +00:00
func (a *SQLiteAuth) RemoveUser(username string) error {
2022-01-31 16:44:58 +00:00
if !AllowedUsername(username) {
2022-01-26 02:57:28 +00:00
return ErrInvalidArgument
}
2022-01-24 04:02:39 +00:00
if _, err := a.db.Exec(deleteUserQuery, username); err != nil {
2022-01-23 05:54:18 +00:00
return err
}
2022-01-24 05:54:28 +00:00
if _, err := a.db.Exec(deleteUserAccessQuery, username); err != nil {
2022-01-23 05:54:18 +00:00
return err
}
return nil
}
2022-01-26 03:30:53 +00:00
// Users returns a list of users. It always also returns the Everyone user ("*").
2022-01-24 04:02:39 +00: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 05:54:28 +00:00
everyone, err := a.everyoneUser()
if err != nil {
return nil, err
}
users = append(users, everyone)
2022-01-24 04:02:39 +00:00
return users, nil
}
2022-01-26 03:30:53 +00:00
// User returns the user with the given username if it exists, or ErrNotFound otherwise.
// You may also pass Everyone to retrieve the anonymous user and its Grant list.
2022-01-24 04:02:39 +00:00
func (a *SQLiteAuth) User(username string) (*User, error) {
2022-01-24 05:54:28 +00:00
if username == Everyone {
return a.everyoneUser()
}
2022-12-03 20:20:59 +00:00
rows, err := a.db.Query(selectUserByNameQuery, username)
2022-01-24 04:02:39 +00:00
if err != nil {
return nil, err
}
2022-12-03 20:20:59 +00:00
return a.readUser(rows)
}
func (a *SQLiteAuth) userByToken(token string) (*User, error) {
rows, err := a.db.Query(selectUserByTokenQuery, token)
if err != nil {
return nil, err
}
return a.readUser(rows)
}
func (a *SQLiteAuth) readUser(rows *sql.Rows) (*User, error) {
2022-01-26 02:57:28 +00:00
defer rows.Close()
2022-12-03 20:20:59 +00:00
var username, hash, role string
2022-12-08 02:26:18 +00:00
var prefs sql.NullString
2022-01-26 02:57:28 +00:00
if !rows.Next() {
2022-01-24 04:02:39 +00:00
return nil, ErrNotFound
}
2022-12-08 02:26:18 +00:00
if err := rows.Scan(&username, &hash, &role, &prefs); err != nil {
2022-01-24 04:02:39 +00:00
return nil, err
2022-01-26 02:57:28 +00:00
} else if err := rows.Err(); err != nil {
2022-01-24 04:02:39 +00:00
return nil, err
}
2022-01-24 05:54:28 +00:00
grants, err := a.readGrants(username)
if err != nil {
return nil, err
}
2022-12-08 02:26:18 +00:00
user := &User{
Name: username,
Hash: hash,
Role: Role(role),
Grants: grants,
}
if prefs.Valid {
user.Prefs = &UserPrefs{}
if err := json.Unmarshal([]byte(prefs.String), user.Prefs); err != nil {
return nil, err
}
}
return user, nil
2022-01-24 05:54:28 +00:00
}
func (a *SQLiteAuth) everyoneUser() (*User, error) {
grants, err := a.readGrants(Everyone)
if err != nil {
return nil, err
}
return &User{
Name: Everyone,
2022-01-26 02:57:28 +00:00
Hash: "",
2022-01-24 05:54:28 +00:00
Role: RoleAnonymous,
Grants: grants,
}, nil
}
func (a *SQLiteAuth) readGrants(username string) ([]Grant, error) {
rows, err := a.db.Query(selectUserAccessQuery, username)
2022-01-24 04:02:39 +00:00
if err != nil {
return nil, err
}
2022-01-24 05:54:28 +00:00
defer rows.Close()
2022-01-24 04:02:39 +00:00
grants := make([]Grant, 0)
2022-01-24 05:54:28 +00:00
for rows.Next() {
2022-01-24 04:02:39 +00:00
var topic string
var read, write bool
2022-01-24 05:54:28 +00:00
if err := rows.Scan(&topic, &read, &write); err != nil {
2022-01-24 04:02:39 +00:00
return nil, err
2022-01-24 05:54:28 +00:00
} else if err := rows.Err(); err != nil {
2022-01-24 04:02:39 +00:00
return nil, err
}
grants = append(grants, Grant{
2022-01-31 16:47:30 +00:00
TopicPattern: fromSQLWildcard(topic),
AllowRead: read,
AllowWrite: write,
2022-01-24 04:02:39 +00:00
})
}
2022-01-24 05:54:28 +00:00
return grants, nil
2022-01-24 04:02:39 +00:00
}
2022-01-26 03:30:53 +00:00
// ChangePassword changes a user's password
2022-01-23 05:54:18 +00:00
func (a *SQLiteAuth) ChangePassword(username, password string) error {
2022-01-26 02:57:28 +00:00
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
2022-01-23 05:54:18 +00:00
if err != nil {
return err
}
2022-01-24 04:02:39 +00:00
if _, err := a.db.Exec(updateUserPassQuery, hash, username); err != nil {
2022-01-23 05:54:18 +00:00
return err
}
return nil
}
2022-01-23 20:30:30 +00:00
2022-01-26 03:30:53 +00:00
// ChangeRole changes a user's role. When a role is changed from RoleUser to RoleAdmin,
// all existing access control entries (Grant) are removed, since they are no longer needed.
2022-01-23 20:30:30 +00:00
func (a *SQLiteAuth) ChangeRole(username string, role Role) error {
2022-01-31 16:44:58 +00:00
if !AllowedUsername(username) || !AllowedRole(role) {
2022-01-26 02:57:28 +00:00
return ErrInvalidArgument
}
2022-01-24 04:02:39 +00:00
if _, err := a.db.Exec(updateUserRoleQuery, string(role), username); err != nil {
2022-01-23 20:30:30 +00:00
return err
}
2022-01-24 04:02:39 +00:00
if role == RoleAdmin {
2022-01-24 05:54:28 +00:00
if _, err := a.db.Exec(deleteUserAccessQuery, username); err != nil {
2022-01-24 04:02:39 +00:00
return err
}
}
2022-01-23 20:30:30 +00:00
return nil
}
2022-01-26 03:30:53 +00:00
// AllowAccess adds or updates an entry in th access control list for a specific user. It controls
2022-01-31 16:44:58 +00:00
// read/write access to a topic. The parameter topicPattern may include wildcards (*).
func (a *SQLiteAuth) AllowAccess(username string, topicPattern string, read bool, write bool) error {
if (!AllowedUsername(username) && username != Everyone) || !AllowedTopicPattern(topicPattern) {
return ErrInvalidArgument
}
if _, err := a.db.Exec(upsertUserAccessQuery, username, toSQLWildcard(topicPattern), read, write); err != nil {
2022-01-23 20:30:30 +00:00
return err
}
return nil
}
2022-01-26 03:30:53 +00:00
// ResetAccess removes an access control list entry for a specific username/topic, or (if topic is
2022-01-31 16:44:58 +00:00
// empty) for an entire user. The parameter topicPattern may include wildcards (*).
func (a *SQLiteAuth) ResetAccess(username string, topicPattern string) error {
2022-02-01 17:23:11 +00:00
if !AllowedUsername(username) && username != Everyone && username != "" {
return ErrInvalidArgument
} else if !AllowedTopicPattern(topicPattern) && topicPattern != "" {
2022-01-31 16:44:58 +00:00
return ErrInvalidArgument
}
if username == "" && topicPattern == "" {
2022-01-24 05:54:28 +00:00
_, err := a.db.Exec(deleteAllAccessQuery, username)
return err
2022-01-31 16:44:58 +00:00
} else if topicPattern == "" {
2022-01-24 05:54:28 +00:00
_, err := a.db.Exec(deleteUserAccessQuery, username)
return err
2022-01-23 20:30:30 +00:00
}
2022-01-31 16:44:58 +00:00
_, err := a.db.Exec(deleteTopicAccessQuery, username, toSQLWildcard(topicPattern))
2022-01-24 05:54:28 +00:00
return err
2022-01-23 20:30:30 +00:00
}
2022-01-26 03:30:53 +00:00
// DefaultAccess returns the default read/write access if no access control entry matches
func (a *SQLiteAuth) DefaultAccess() (read bool, write bool) {
return a.defaultRead, a.defaultWrite
}
2022-01-31 16:44:58 +00:00
func toSQLWildcard(s string) string {
return strings.ReplaceAll(s, "*", "%")
}
func fromSQLWildcard(s string) string {
return strings.ReplaceAll(s, "%", "*")
}
func setupAuthDB(db *sql.DB) error {
// If 'schemaVersion' table does not exist, this must be a new database
rowsSV, err := db.Query(selectSchemaVersionQuery)
if err != nil {
return setupNewAuthDB(db)
}
defer rowsSV.Close()
// If 'schemaVersion' table exists, read version and potentially upgrade
schemaVersion := 0
if !rowsSV.Next() {
return errors.New("cannot determine schema version: database file may be corrupt")
}
if err := rowsSV.Scan(&schemaVersion); err != nil {
return err
}
rowsSV.Close()
// Do migrations
if schemaVersion == currentSchemaVersion {
return nil
}
return fmt.Errorf("unexpected schema version found: %d", schemaVersion)
}
func setupNewAuthDB(db *sql.DB) error {
if _, err := db.Exec(createAuthTablesQueries); err != nil {
return err
}
if _, err := db.Exec(insertSchemaVersion, currentSchemaVersion); err != nil {
return err
}
return nil
}