bbj2/server/cmd/api/api_test.go

502 lines
11 KiB
Go
Raw Normal View History

2022-06-01 03:27:55 +00:00
package api
import (
2022-06-21 18:20:47 +00:00
"database/sql"
2022-06-29 04:32:35 +00:00
"errors"
2022-06-14 17:44:03 +00:00
"log"
"net/http"
2022-06-14 16:33:27 +00:00
"os"
"reflect"
2022-06-14 17:44:03 +00:00
"strings"
2022-06-01 03:27:55 +00:00
"testing"
2022-06-17 21:01:25 +00:00
"time"
2022-06-01 03:27:55 +00:00
"git.tilde.town/tildetown/bbj2/server/cmd/config"
2022-06-14 21:05:39 +00:00
"git.tilde.town/tildetown/bbj2/server/cmd/db"
2022-06-01 03:27:55 +00:00
)
func createTestState() (opts *config.Options, err error) {
var dbFile *os.File
if dbFile, err = os.CreateTemp("", "bbj2-test"); err != nil {
return
2022-06-14 16:33:27 +00:00
}
opts = &config.Options{
Logger: log.New(os.Stdout, "bbj2 test", log.Lshortfile),
2022-06-14 16:33:27 +00:00
Config: config.Config{
Admins: []string{"jillValentine", "rebeccaChambers"},
Port: 666,
Host: "hell.cool",
InstanceName: "cool test zone",
AllowAnon: true,
DBPath: dbFile.Name(),
},
}
2022-06-14 21:05:39 +00:00
return
}
2022-06-21 18:20:47 +00:00
func userCount(db *sql.DB) (count int, err error) {
err = db.QueryRow("SELECT count(*) FROM users").Scan(&count)
return
}
2022-07-01 02:49:59 +00:00
func Test_CheckAuth(t *testing.T) {
ts := []struct {
name string
req func() *http.Request
setup func(*config.Options) error
assert func(*BBJResponse, *testing.T)
wantErr *HTTPError
}{
{
name: "blank user",
req: func() *http.Request {
req, _ := http.NewRequest("POST", "/check_auth", strings.NewReader(`{"target_hash":"abc123"}`))
return req
},
wantErr: &HTTPError{Code: 400, Msg: "invalid args: missing either username or auth hash"},
},
{
name: "blank hash",
req: func() *http.Request {
req, _ := http.NewRequest("POST", "/check_auth", strings.NewReader(`{"target_user":"jillvalentine"}`))
return req
},
wantErr: &HTTPError{Code: 400, Msg: "invalid args: missing either username or auth hash"},
},
{
name: "bad method",
req: func() *http.Request {
r, _ := http.NewRequest("GET", "", strings.NewReader(""))
return r
},
wantErr: &HTTPError{
Msg: "bad method",
Code: 400,
},
},
{
name: "mismatch hash",
setup: func(opts *config.Options) error {
return db.CreateUser(opts.DB, db.User{
Username: "jillvalentine",
Hash: "xyz789",
Created: time.Now(),
})
},
req: func() *http.Request {
req, _ := http.NewRequest("POST", "/check_auth", strings.NewReader(`{"target_user":"jillvalentine", "target_hash":"abc123"}`))
return req
},
wantErr: &HTTPError{Code: 403, Msg: "bad credentials"},
},
{
name: "good",
setup: func(opts *config.Options) error {
return db.CreateUser(opts.DB, db.User{
Username: "jillvalentine",
Hash: "xyz789",
Created: time.Now(),
})
},
req: func() *http.Request {
req, _ := http.NewRequest("POST", "/check_auth", strings.NewReader(`{"target_user":"jillvalentine", "target_hash":"xyz789"}`))
return req
},
assert: func(resp *BBJResponse, t *testing.T) {
if !resp.Data.(bool) {
t.Error("expected true Data")
}
},
},
}
for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) {
// TODO BOILERPLATE
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
var req *http.Request
if tt.req == nil {
req, _ = http.NewRequest("POST", "", strings.NewReader(`{"user_name":"albertwesker","auth_hash":"1234abc"}`))
} else {
req = tt.req()
}
teardown, err := db.Setup(opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
defer teardown()
err = db.EnsureSchema(*opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
if tt.setup != nil {
err = tt.setup(opts)
if err != nil {
t.Fatalf("setup failed: %s", err.Error())
return
}
}
// END BOILERPLATE
api := &API{Opts: *opts}
ctx := &ReqCtx{Req: req}
var resp *BBJResponse
resp, err = api.CheckAuth(ctx)
if err != nil {
if tt.wantErr == nil || tt.wantErr.Error() != err.Error() {
t.Errorf("got unexpected error: %s", err)
}
return
} else {
if tt.wantErr != nil {
t.Error("expected error, got none")
return
}
}
if tt.assert != nil {
tt.assert(resp, t)
}
})
}
}
2022-06-21 18:35:34 +00:00
func Test_UserRegister(t *testing.T) {
ts := []struct {
name string
2022-06-17 22:02:27 +00:00
req func() *http.Request
2022-06-21 17:57:52 +00:00
setup func(*config.Options) error
assert func(*config.Options, *testing.T) error
wantErr *HTTPError
}{
{
name: "user already exists",
setup: func(opts *config.Options) error {
2022-06-17 21:01:25 +00:00
return db.CreateUser(opts.DB, db.User{
Username: "albertwesker",
Hash: "1234abc",
Created: time.Now(),
})
},
2022-06-21 18:20:47 +00:00
assert: func(opts *config.Options, t *testing.T) (err error) {
2022-06-21 17:57:52 +00:00
var count int
2022-06-21 18:20:47 +00:00
count, err = userCount(opts.DB)
2022-06-21 17:57:52 +00:00
2022-06-21 18:20:47 +00:00
if count != 2 {
t.Errorf("expected 2 users, got %d", count)
2022-06-21 17:57:52 +00:00
}
2022-06-21 18:20:47 +00:00
return
},
wantErr: &HTTPError{Code: 403, Msg: "user already exists"},
},
2022-06-21 17:57:52 +00:00
{
name: "bad method",
req: func() *http.Request {
r, _ := http.NewRequest("GET", "", strings.NewReader(""))
return r
},
wantErr: &HTTPError{
Msg: "bad method",
Code: 400,
},
},
2022-06-21 18:20:47 +00:00
{
name: "add new user",
req: func() *http.Request {
r, _ := http.NewRequest("POST", "", strings.NewReader(`{"user_name":"chrisredfield", "auth_hash":"abc123"}`))
return r
},
assert: func(opts *config.Options, t *testing.T) (err error) {
var count int
count, err = userCount(opts.DB)
if count != 2 {
t.Errorf("expected 2 users, got %d", count)
}
return
},
},
// TODO bad args
}
for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) {
2022-06-21 18:20:47 +00:00
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
2022-06-17 22:02:27 +00:00
var req *http.Request
if tt.req == nil {
2022-06-21 17:57:52 +00:00
req, _ = http.NewRequest("POST", "", strings.NewReader(`{"user_name":"albertwesker","auth_hash":"1234abc"}`))
2022-06-17 22:02:27 +00:00
} else {
req = tt.req()
}
2022-06-17 21:01:25 +00:00
teardown, err := db.Setup(opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
defer teardown()
2022-06-17 21:12:05 +00:00
err = db.EnsureSchema(*opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
2022-06-21 17:57:52 +00:00
if tt.setup != nil {
err = tt.setup(opts)
if err != nil {
t.Fatalf("setup failed: %s", err.Error())
return
}
2022-06-17 21:01:25 +00:00
}
2022-06-17 22:02:27 +00:00
api := &API{Opts: *opts}
ctx := &ReqCtx{Req: req}
2022-06-21 17:57:52 +00:00
_, err = api.UserRegister(ctx)
2022-06-17 22:02:27 +00:00
2022-06-21 17:57:52 +00:00
if tt.assert != nil {
2022-06-21 18:20:47 +00:00
err := tt.assert(opts, t)
2022-06-21 17:57:52 +00:00
if err != nil {
t.Fatal(err.Error())
return
}
}
2022-06-21 18:20:47 +00:00
if tt.wantErr != nil && err != nil {
if !reflect.DeepEqual(tt.wantErr, err) {
t.Errorf("got unwanted error: %s", err.Error())
}
return
}
2022-06-17 22:02:27 +00:00
if tt.wantErr != nil && err == nil {
t.Errorf("expected error")
return
}
})
}
}
2022-06-21 18:35:34 +00:00
func Test_InstanceInfo(t *testing.T) {
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
2022-06-01 03:27:55 +00:00
ts := []struct {
name string
2022-06-17 21:44:30 +00:00
req func() *http.Request
2022-06-14 16:33:27 +00:00
wantData instanceInfo
2022-06-02 04:40:43 +00:00
wantErr *HTTPError
2022-06-14 16:33:27 +00:00
}{
{
name: "basic",
wantData: instanceInfo{
InstanceName: "cool test zone",
AllowAnon: true,
Admins: []string{"jillValentine", "rebeccaChambers"},
},
},
2022-06-17 21:44:30 +00:00
{
name: "bad method",
req: func() *http.Request {
r, _ := http.NewRequest("POST", "", strings.NewReader(""))
return r
},
wantErr: &HTTPError{
Msg: "bad method",
Code: 400,
},
},
2022-06-14 16:33:27 +00:00
}
2022-06-01 03:27:55 +00:00
for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) {
2022-06-17 21:44:30 +00:00
var req *http.Request
if tt.req == nil {
req, _ = http.NewRequest("GET", "", strings.NewReader(""))
} else {
req = tt.req()
}
2022-06-17 22:02:27 +00:00
api := &API{Opts: *opts}
2022-06-17 21:12:05 +00:00
ctx := &ReqCtx{Req: req}
resp, err := api.InstanceInfo(ctx)
2022-06-02 04:40:43 +00:00
if tt.wantErr != nil && err != nil {
2022-06-17 21:44:30 +00:00
if !reflect.DeepEqual(tt.wantErr, err) {
t.Errorf("got unwanted error: %s", err.Error())
}
2022-06-02 04:40:43 +00:00
return
}
2022-06-17 21:44:30 +00:00
if tt.wantErr != nil && err == nil {
t.Errorf("expected error")
return
}
2022-06-14 16:33:27 +00:00
ii, ok := resp.Data.(instanceInfo)
if !ok {
t.Errorf("could not cast data in %s", tt.name)
}
if !reflect.DeepEqual(ii, tt.wantData) {
t.Errorf("did not get expected data in %s", tt.name)
2022-06-02 04:40:43 +00:00
}
2022-06-01 03:27:55 +00:00
})
}
}
2022-06-21 18:35:34 +00:00
func Test_getUserFromReq(t *testing.T) {
2022-06-29 04:32:35 +00:00
ts := []struct {
name string
req func() *http.Request
setup func(*config.Options) error
assert func(*db.User, *testing.T)
wantErr error
}{
{
name: "no auth attempt",
req: func() *http.Request {
r, _ := http.NewRequest("GET", "", strings.NewReader(""))
return r
},
assert: func(u *db.User, t *testing.T) {
if u != nil {
t.Errorf("expected nil, got %v", u)
}
},
},
{
name: "anon",
req: func() *http.Request {
r, _ := http.NewRequest("GET", "", strings.NewReader(""))
r.Header.Add("User", "anon")
return r
},
assert: func(u *db.User, t *testing.T) {
if u != nil {
t.Errorf("expected nil, got %v", u)
}
},
},
{
name: "no such user",
req: func() *http.Request {
r, _ := http.NewRequest("GET", "", strings.NewReader(""))
r.Header.Set("User", "williambirkin")
r.Header.Set("Auth", "abc123")
return r
},
wantErr: errors.New("no such user"),
},
{
name: "bad creds",
setup: func(opts *config.Options) error {
return db.CreateUser(opts.DB, db.User{
Username: "jillvalentine",
Hash: "abc123",
Created: time.Now(),
})
},
req: func() *http.Request {
r, _ := http.NewRequest("GET", "", strings.NewReader(""))
r.Header.Set("User", "jillvalentine")
r.Header.Set("Auth", "xyz789")
return r
},
wantErr: errors.New("bad credentials"),
},
{
name: "good creds",
setup: func(opts *config.Options) error {
return db.CreateUser(opts.DB, db.User{
Username: "jillvalentine",
Hash: "abc123",
Created: time.Now(),
})
},
req: func() *http.Request {
r, _ := http.NewRequest("GET", "", strings.NewReader(""))
r.Header.Set("User", "jillvalentine")
r.Header.Set("Auth", "abc123")
return r
},
assert: func(u *db.User, t *testing.T) {
if u.Username != "jillvalentine" {
t.Errorf("expected 'jillvalentine' got %s", u.Username)
}
},
},
}
for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) {
// TODO BOILERPLATE
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
var req *http.Request
if tt.req == nil {
req, _ = http.NewRequest("POST", "", strings.NewReader(`{"user_name":"albertwesker","auth_hash":"1234abc"}`))
} else {
req = tt.req()
}
teardown, err := db.Setup(opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
defer teardown()
err = db.EnsureSchema(*opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
if tt.setup != nil {
err = tt.setup(opts)
if err != nil {
t.Fatalf("setup failed: %s", err.Error())
return
}
}
// END BOILERPLATE
u, err := getUserFromReq(*opts, req)
if err != nil {
if tt.wantErr == nil || tt.wantErr.Error() != err.Error() {
t.Errorf("got unexpected error: %s", err)
}
return
} else {
if tt.wantErr != nil {
t.Error("expected error, got none")
return
}
}
tt.assert(u, t)
})
}
2022-06-21 18:35:34 +00:00
}