add real logging, more refactoring

trunk
vilmibm 2022-06-14 12:44:03 -05:00
parent e1211c8d6f
commit 0ff1380263
4 changed files with 370 additions and 360 deletions

View File

@ -1,7 +1,11 @@
package api package api
import ( import (
"encoding/json"
"errors"
"fmt" "fmt"
"net/http"
"strings"
"git.tilde.town/tildetown/bbj2/server/cmd/config" "git.tilde.town/tildetown/bbj2/server/cmd/config"
"git.tilde.town/tildetown/bbj2/server/cmd/db" "git.tilde.town/tildetown/bbj2/server/cmd/db"
@ -22,9 +26,77 @@ type BBJResponse struct {
Usermap map[string]db.User `json:"usermap"` Usermap map[string]db.User `json:"usermap"`
} }
type APIHandler func() (*BBJResponse, error)
type API struct { type API struct {
User *db.User User *db.User
Opts config.Options Opts config.Options
Req *http.Request
}
func NewAPI(opts config.Options, req *http.Request) (*API, error) {
user, err := getUserFromReq(opts, req)
if err != nil {
return nil, &HTTPError{Msg: err.Error(), Code: 403}
}
return &API{
Opts: opts,
User: user,
Req: req,
}, nil
}
func Invoke(w http.ResponseWriter, apiFn APIHandler) {
resp, err := apiFn()
if err != nil {
he := &HTTPError{}
_ = errors.As(err, &he)
resp := BBJResponse{
Error: true,
Data: he.Msg,
}
w.WriteHeader(he.Code)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func getUserFromReq(opts config.Options, req *http.Request) (u *db.User, err error) {
u = &db.User{}
u.Username = req.Header.Get("User")
u.Hash = req.Header.Get("Auth")
if u.Username == "" || u.Username == "anon" {
return
}
db := opts.DB
stmt, err := db.Prepare("select auth_hash, id from users where user_name = ?")
if err != nil {
err = fmt.Errorf("db error: %w", err)
return
}
defer stmt.Close()
opts.Logger.Printf("querying for %s", u.Username)
var authHash string
if err = stmt.QueryRow(u.Username).Scan(&authHash, u.ID); err != nil {
if strings.Contains(err.Error(), "no rows in result") {
err = errors.New("no such user")
} else {
err = fmt.Errorf("db error: %w", err)
}
}
if authHash != u.Hash {
err = errors.New("bad credentials")
}
return
} }
type instanceInfo struct { type instanceInfo struct {
@ -33,7 +105,18 @@ type instanceInfo struct {
Admins []string Admins []string
} }
func (a *API) IsGet() bool {
return a.Req.Method == "GET"
}
func (a *API) IsPost() bool {
return a.Req.Method == "POST"
}
func (a *API) InstanceInfo() (*BBJResponse, error) { func (a *API) InstanceInfo() (*BBJResponse, error) {
if !a.IsGet() {
return nil, &HTTPError{Msg: "bad method", Code: 400}
}
return &BBJResponse{ return &BBJResponse{
Data: instanceInfo{ Data: instanceInfo{
InstanceName: a.Opts.Config.InstanceName, InstanceName: a.Opts.Config.InstanceName,
@ -43,4 +126,9 @@ func (a *API) InstanceInfo() (*BBJResponse, error) {
}, nil }, nil
} }
type ApiHandler func() (*BBJResponse, error) func (a *API) UserRegister() (*BBJResponse, error) {
if !a.IsPost() {
return nil, &HTTPError{Msg: "bad method", Code: 400}
}
return nil, nil
}

View File

@ -3,15 +3,18 @@ package api
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"fmt" "log"
"net/http"
"os" "os"
"reflect" "reflect"
"strings"
"testing" "testing"
"git.tilde.town/tildetown/bbj2/server/cmd/config" "git.tilde.town/tildetown/bbj2/server/cmd/config"
) )
func TestInstanceInfo(t *testing.T) { func TestInstanceInfo(t *testing.T) {
// TODO a lot of this needs to be cleaned up and generalized etc
stderr := []byte{} stderr := []byte{}
stdout := []byte{} stdout := []byte{}
testIO := config.IOStreams{ testIO := config.IOStreams{
@ -22,13 +25,10 @@ func TestInstanceInfo(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to make test db: %s", err.Error()) t.Fatalf("failed to make test db: %s", err.Error())
} }
logger := log.New(os.Stdout, "bbj test", log.Lshortfile)
defaultOptions := config.Options{ defaultOptions := config.Options{
IO: testIO, IO: testIO,
Log: func(s string) { fmt.Fprintln(testIO.Out, s) }, Logger: logger,
Logf: func(s string, args ...interface{}) {
fmt.Fprintf(testIO.Out, s, args...)
fmt.Fprintln(testIO.Out)
},
Config: config.Config{ Config: config.Config{
Admins: []string{"jillValentine", "rebeccaChambers"}, Admins: []string{"jillValentine", "rebeccaChambers"},
Port: 666, Port: 666,
@ -57,8 +57,10 @@ func TestInstanceInfo(t *testing.T) {
for _, tt := range ts { for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest("GET", "", strings.NewReader(""))
api := &API{ api := &API{
Opts: tt.opts, Opts: tt.opts,
Req: req,
} }
resp, err := api.InstanceInfo() resp, err := api.InstanceInfo()
if tt.wantErr != nil && err != nil { if tt.wantErr != nil && err != nil {

View File

@ -4,6 +4,7 @@ import (
"database/sql" "database/sql"
"fmt" "fmt"
"io" "io"
"log"
"os" "os"
yaml "gopkg.in/yaml.v3" yaml "gopkg.in/yaml.v3"
@ -34,6 +35,7 @@ type Config struct {
type Options struct { type Options struct {
ConfigPath string ConfigPath string
IO IOStreams IO IOStreams
Logger *log.Logger
Log func(string) Log func(string)
Logf func(string, ...interface{}) Logf func(string, ...interface{})
Config Config Config Config

View File

@ -7,13 +7,13 @@ import (
"errors" "errors"
"flag" "flag"
"fmt" "fmt"
"log"
"net/http" "net/http"
"os" "os"
"strings" "strings"
"git.tilde.town/tildetown/bbj2/server/cmd/api" "git.tilde.town/tildetown/bbj2/server/cmd/api"
"git.tilde.town/tildetown/bbj2/server/cmd/config" "git.tilde.town/tildetown/bbj2/server/cmd/config"
"git.tilde.town/tildetown/bbj2/server/cmd/db"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
@ -30,23 +30,17 @@ func main() {
Err: os.Stderr, Err: os.Stderr,
Out: os.Stdout, Out: os.Stdout,
} }
logger := log.New(io.Out, "", log.Ldate|log.Ltime|log.Lshortfile)
opts := &config.Options{ opts := &config.Options{
ConfigPath: *configFlag, ConfigPath: *configFlag,
Reset: *resetFlag, Reset: *resetFlag,
IO: io, IO: io,
// TODO use real logger Logger: logger,
Log: func(s string) {
fmt.Fprintln(io.Out, s)
},
Logf: func(s string, args ...interface{}) {
fmt.Fprintf(io.Out, s, args...)
fmt.Fprintf(io.Out, "\n")
},
} }
err := _main(opts) err := _main(opts)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed: %s", err) logger.Fatalln(err.Error())
} }
} }
@ -81,7 +75,7 @@ func _main(opts *config.Options) error {
setupAPI(*opts) setupAPI(*opts)
// TODO TLS or SSL or something // TODO TLS or SSL or something
opts.Logf("starting server at %s:%d", cfg.Host, cfg.Port) opts.Logger.Printf("starting server at %s:%d", cfg.Host, cfg.Port)
if err := http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), nil); err != nil { if err := http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), nil); err != nil {
return fmt.Errorf("http server exited with error: %w", err) return fmt.Errorf("http server exited with error: %w", err)
} }
@ -127,7 +121,7 @@ func ensureSchema(opts config.Options) error {
func handler(opts config.Options, f http.HandlerFunc) http.HandlerFunc { func handler(opts config.Options, f http.HandlerFunc) http.HandlerFunc {
// TODO make this more real // TODO make this more real
return func(w http.ResponseWriter, req *http.Request) { return func(w http.ResponseWriter, req *http.Request) {
opts.Log(req.URL.Path) opts.Logger.Printf("<- %s", req.URL.Path)
// TODO add user info to opts // TODO add user info to opts
f(w, req) f(w, req)
} }
@ -137,54 +131,7 @@ func handler(opts config.Options, f http.HandlerFunc) http.HandlerFunc {
// encryption, it doesn't really help anything. I'd rather have plaintext + // encryption, it doesn't really help anything. I'd rather have plaintext +
// transport encryption and then, on the server side, proper salted hashing. // transport encryption and then, on the server side, proper salted hashing.
// TODO get rid of these
func writeResponse(w http.ResponseWriter, resp api.BBJResponse) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
// NB breaking: i'm not just returning 200 always but using http status codes // NB breaking: i'm not just returning 200 always but using http status codes
func writeErrorResponse(w http.ResponseWriter, code int, resp api.BBJResponse) {
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func getUserFromReq(opts config.Options, req *http.Request) (u *db.User, err error) {
u = &db.User{}
u.Username = req.Header.Get("User")
u.Hash = req.Header.Get("Auth")
if u.Username == "" || u.Username == "anon" {
return
}
db := opts.DB
stmt, err := db.Prepare("select auth_hash, id from users where user_name = ?")
if err != nil {
err = fmt.Errorf("db error: %w", err)
return
}
defer stmt.Close()
opts.Logf("querying for %s", u.Username)
var authHash string
if err = stmt.QueryRow(u.Username).Scan(&authHash, u.ID); err != nil {
if strings.Contains(err.Error(), "no rows in result") {
err = errors.New("no such user")
} else {
err = fmt.Errorf("db error: %w", err)
}
}
if authHash != u.Hash {
err = errors.New("bad credentials")
}
return
}
func checkAuth(opts config.Options, username, hash string) error { func checkAuth(opts config.Options, username, hash string) error {
db := opts.DB db := opts.DB
@ -194,7 +141,7 @@ func checkAuth(opts config.Options, username, hash string) error {
} }
defer stmt.Close() defer stmt.Close()
opts.Logf("querying for %s", username) opts.Logger.Printf("querying for %s", username)
var authHash string var authHash string
if err = stmt.QueryRow(username).Scan(&authHash); err != nil { if err = stmt.QueryRow(username).Scan(&authHash); err != nil {
@ -212,66 +159,37 @@ func checkAuth(opts config.Options, username, hash string) error {
} }
func setupAPI(opts config.Options) { func setupAPI(opts config.Options) {
newAPI := func(opts config.Options, w http.ResponseWriter, req *http.Request) *api.API { handleFailedAPICreate := func(w http.ResponseWriter, err error) {
user, err := getUserFromReq(opts, req) opts.Logger.Printf("failed to create API: %s", err.Error())
if err != nil { w.WriteHeader(500)
writeErrorResponse(w, 403, api.BBJResponse{ w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(api.BBJResponse{
Error: true, Error: true,
Data: err.Error(), Data: "server error check logs",
}) })
return nil
}
return &api.API{
Opts: opts,
User: user,
}
} }
invokeAPI := func(w http.ResponseWriter, apiFn api.ApiHandler) { // TODO could probably generalize this even further but it's fine for now
resp, err := apiFn()
if err != nil {
he := &api.HTTPError{}
_ = errors.As(err, &he)
resp := api.BBJResponse{
Error: true,
Data: he.Msg,
}
w.WriteHeader(he.Code)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
http.HandleFunc("/instance_info", handler(opts, func(w http.ResponseWriter, req *http.Request) { http.HandleFunc("/instance_info", handler(opts, func(w http.ResponseWriter, req *http.Request) {
api := newAPI(opts, w, req) a, err := api.NewAPI(opts, req)
if api == nil { if err != nil {
handleFailedAPICreate(w, err)
return return
} }
invokeAPI(w, api.InstanceInfo) api.Invoke(w, a.InstanceInfo)
}))
http.HandleFunc("/user_register", handler(opts, func(w http.ResponseWriter, req *http.Request) {
a, err := api.NewAPI(opts, req)
if err != nil {
handleFailedAPICreate(w, err)
return
}
api.Invoke(w, a.UserRegister)
})) }))
/* /*
http.HandleFunc("/instance_info", handler(opts, func(w http.ResponseWriter, req *http.Request) {
type instanceInfo struct {
InstanceName string `json:"instance_name"`
AllowAnon bool `json:"allow_anon"`
Admins []string
}
writeResponse(w, BBJResponse{
Data: instanceInfo{
InstanceName: opts.Config.InstanceName,
AllowAnon: opts.Config.AllowAnon,
Admins: opts.Config.Admins,
},
})
}))
http.HandleFunc("/user_register", handler(opts, func(w http.ResponseWriter, req *http.Request) { http.HandleFunc("/user_register", handler(opts, func(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" { if req.Method != "POST" {
badMethod(w) badMethod(w)