All the auth things are working now

pull/114/head
Philipp Heckel 2022-01-22 14:47:27 -05:00
parent 2181227a6e
commit 86b20e8ccd
5 changed files with 194 additions and 20 deletions

7
go.mod
View File

@ -9,11 +9,15 @@ require (
github.com/BurntSushi/toml v0.4.1 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect
github.com/emersion/go-smtp v0.15.0
github.com/gabriel-vasile/mimetype v1.4.0
github.com/gorilla/websocket v1.4.2
github.com/mattn/go-sqlite3 v1.14.9
github.com/olebedev/when v0.0.0-20211212231525-59bd4edcf9d6
github.com/stretchr/testify v1.7.0
github.com/urfave/cli/v2 v2.3.0
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11
google.golang.org/api v0.63.0
gopkg.in/yaml.v2 v2.4.0
@ -30,18 +34,15 @@ require (
github.com/emersion/go-sasl v0.0.0-20200509203442-7bfe0ed36a21 // indirect
github.com/envoyproxy/go-control-plane v0.10.1 // indirect
github.com/envoyproxy/protoc-gen-validate v0.6.2 // indirect
github.com/gabriel-vasile/mimetype v1.4.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/go-cmp v0.5.6 // indirect
github.com/googleapis/gax-go/v2 v2.1.1 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
go.opencensus.io v0.23.0 // indirect
golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect

1
go.sum
View File

@ -255,6 +255,7 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=

View File

@ -1,9 +1,27 @@
package server
import (
"database/sql"
"fmt"
"golang.org/x/crypto/bcrypt"
"log"
)
/*
sqlite> create table user (id int auto increment, user text, password text not null);
sqlite> create table user_topic (user_id int not null, topic text not null, allow_write int, allow_read int);
sqlite> create table topic (topic text primary key, allow_anonymous_write int, allow_anonymous_read int);
SELECT * FROM user;
SELECT * FROM topic;
SELECT * FROM topic_user;
INSERT INTO user VALUES('phil','$2a$06$.4W0LI5mcxzxhpjUvpTaNeu0MhRO0T7B.CYnmAkRnlztIy7PrSODu', 'admin');
INSERT INTO user VALUES('ben','$2a$06$skJK/AecWCUmiCjr69ke.Ow/hFA616RdvJJPxnI221zyohsRlyXL.', 'user');
INSERT INTO user VALUES('marian','$2a$06$N/BcXR0g6XUlmWttMqciWugR6xQKm2lVj31HLid6Mc4cnzpeOMgnq', 'user');
INSERT INTO topic_user VALUES('alerts','ben',1,1);
INSERT INTO topic_user VALUES('alerts','marian',1,0);
INSERT INTO topic VALUES('announcements',1,0);
*/
const (
@ -11,21 +29,169 @@ const (
permWrite = 2
)
const (
roleAdmin = "admin"
roleUser = "user"
roleNone = "none"
)
const (
createAuthTablesQueries = `
BEGIN;
CREATE TABLE IF NOT EXISTS user (
user TEXT NOT NULL PRIMARY KEY,
pass TEXT NOT NULL,
role TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS topic (
topic TEXT NOT NULL PRIMARY KEY,
anon_read INT NOT NULL,
anon_write INT NOT NULL
);
CREATE TABLE IF NOT EXISTS topic_user (
topic TEXT NOT NULL,
user 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 FROM user WHERE user = ?`
selectTopicPermsAnonQuery = `SELECT ?, anon_read, anon_write FROM topic WHERE topic = ?`
selectTopicPermsUserQuery = `
SELECT role, IFNULL(read, 0), IFNULL(write, 0)
FROM user
LEFT JOIN topic_user ON user.user = topic_user.user AND topic_user.topic = ?
WHERE user.user = ?
`
)
type auther interface {
Authenticate(user, pass string) bool
Authorize(user, topic string, perm int) bool
Authenticate(user, pass string) error
Authorize(user, topic string, perm int) error
}
type memAuther struct {
}
func (m memAuther) Authenticate(user, pass string) bool {
return user == "phil" && pass == "phil"
func (m *memAuther) Authenticate(user, pass string) error {
if user == "phil" && pass == "phil" {
return nil
}
return errHTTPUnauthorized
}
func (m memAuther) Authorize(user, topic string, perm int) bool {
func (m *memAuther) Authorize(user, topic string, perm int) error {
if perm == permRead {
return true
return nil
}
return user == "phil" && topic == "mytopic"
if user == "phil" && topic == "mytopic" {
return nil
}
return errHTTPUnauthorized
}
type sqliteAuther struct {
db *sql.DB
defaultRead bool
defaultWrite bool
}
var _ auther = (*sqliteAuther)(nil)
func newSqliteAuther(filename string, defaultRead, defaultWrite bool) (*sqliteAuther, error) {
db, err := sql.Open("sqlite3", filename)
if err != nil {
return nil, err
}
if err := setupNewAuthDB(db); err != nil {
return nil, err
}
return &sqliteAuther{
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
}
func (a *sqliteAuther) Authenticate(user, pass string) error {
rows, err := a.db.Query(selectUserQuery, user)
if err != nil {
return err
}
defer rows.Close()
var hash string
if !rows.Next() {
return fmt.Errorf("user %s not found", user)
}
if err := rows.Scan(&hash); err != nil {
return err
} else if err := rows.Err(); err != nil {
return err
}
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pass))
}
func (a *sqliteAuther) Authorize(user, topic string, perm int) error {
if user == "" {
return a.authorizeAnon(topic, perm)
}
return a.authorizeUser(user, topic, perm)
}
func (a *sqliteAuther) authorizeAnon(topic string, perm int) error {
rows, err := a.db.Query(selectTopicPermsAnonQuery, roleNone, topic)
if err != nil {
return err
}
return a.checkPerms(rows, perm)
}
func (a *sqliteAuther) authorizeUser(user string, topic string, perm int) error {
rows, err := a.db.Query(selectTopicPermsUserQuery, topic, user)
if err != nil {
return err
}
return a.checkPerms(rows, perm)
}
func (a *sqliteAuther) checkPerms(rows *sql.Rows, perm int) error {
defer rows.Close()
if !rows.Next() {
return a.resolvePerms(a.defaultRead, a.defaultWrite, perm)
}
var role string
var read, write bool
if err := rows.Scan(&role, &read, &write); err != nil {
return err
} else if err := rows.Err(); err != nil {
return err
}
log.Printf("%#v, %#v, %#v", role, read, write)
if role == roleAdmin {
return nil // Admin can do everything
}
return a.resolvePerms(read, write, perm)
}
func (a *sqliteAuther) resolvePerms(read, write bool, perm int) error {
if perm == permRead && read {
return nil
} else if perm == permWrite && write {
return nil
}
return errHTTPUnauthorized
}

View File

@ -121,7 +121,7 @@ func newSqliteCache(filename string) (*sqliteCache, error) {
if err != nil {
return nil, err
}
if err := setupDB(db); err != nil {
if err := setupCacheDB(db); err != nil {
return nil, err
}
return &sqliteCache{
@ -340,11 +340,11 @@ func readMessages(rows *sql.Rows) ([]*message, error) {
return messages, nil
}
func setupDB(db *sql.DB) error {
func setupCacheDB(db *sql.DB) error {
// If 'messages' table does not exist, this must be a new database
rowsMC, err := db.Query(selectMessagesCountQuery)
if err != nil {
return setupNewDB(db)
return setupNewCacheDB(db)
}
rowsMC.Close()
@ -377,7 +377,7 @@ func setupDB(db *sql.DB) error {
return fmt.Errorf("unexpected schema version found: %d", schemaVersion)
}
func setupNewDB(db *sql.DB) error {
func setupNewCacheDB(db *sql.DB) error {
if _, err := db.Exec(createMessagesTableQuery); err != nil {
return err
}

View File

@ -141,6 +141,10 @@ func New(conf *Config) (*Server, error) {
return nil, err
}
}
auther, err := newSqliteAuther("user.db", false, false)
if err != nil {
return nil, err
}
return &Server{
config: conf,
cache: cache,
@ -148,7 +152,7 @@ func New(conf *Config) (*Server, error) {
firebase: firebaseSubscriber,
mailer: mailer,
topics: topics,
auther: &memAuther{},
auther: auther,
visitors: make(map[string]*visitor),
}, nil
}
@ -1128,13 +1132,15 @@ func (s *Server) withAuth(next handleFunc, perm int) handleFunc {
}
user, pass, ok := r.BasicAuth()
if ok {
if !s.auther.Authenticate(user, pass) {
if err := s.auther.Authenticate(user, pass); err != nil {
log.Printf("authentication failed: %s", err.Error())
return errHTTPUnauthorized
}
} else {
user = "" // Just in case
}
if !s.auther.Authorize(user, t.ID, perm) {
if err := s.auther.Authorize(user, t.ID, perm); err != nil {
log.Printf("unauthorized: %s", err.Error())
return errHTTPUnauthorized
}
return next(w, r, v)