Files

441 lines
13 KiB
Go

package httpapi
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"path/filepath"
"strings"
"sync"
"testing"
"git.asio.asia/TapRemly/server/internal/auth"
"git.asio.asia/TapRemly/server/internal/boot"
"git.asio.asia/TapRemly/server/internal/store"
)
type fakeNix struct {
mu sync.Mutex
next int
online map[string]bool
passwords map[string]string
deleted []string
}
func newFakeNix() *fakeNix {
return &fakeNix{online: map[string]bool{}, passwords: map[string]string{}}
}
func (f *fakeNix) CreateEndpoint(_ context.Context, id, name string) (string, error) {
f.mu.Lock()
defer f.mu.Unlock()
if id == "" {
f.next++
id = "e_dev"
}
_ = name
pw := "DevicePassw0rd"
f.online[id] = true
f.passwords[id] = pw
return pw, nil
}
func (f *fakeNix) Lookup(_ context.Context, id string) (bool, bool, error) {
f.mu.Lock()
defer f.mu.Unlock()
on, ok := f.online[id]
if !ok {
return false, false, nil
}
return true, on, nil
}
func (f *fakeNix) DeleteEndpoint(_ context.Context, id string) error {
f.mu.Lock()
defer f.mu.Unlock()
delete(f.online, id)
f.deleted = append(f.deleted, id)
return nil
}
func (f *fakeNix) password(id string) string {
f.mu.Lock()
defer f.mu.Unlock()
return f.passwords[id]
}
type apiEnv struct {
srv *httptest.Server
store *store.Store
nix *fakeNix
}
func newEnv(t *testing.T) *apiEnv {
t.Helper()
st, err := store.Open(filepath.Join(t.TempDir(), "t.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
if err := st.Migrate(context.Background()); err != nil {
t.Fatal(err)
}
nix := newFakeNix()
h := New(st, nix, false, nil)
srv := httptest.NewServer(h.Routes())
t.Cleanup(srv.Close)
return &apiEnv{srv: srv, store: st, nix: nix}
}
type session struct {
base string
http *http.Client
}
func newSession(t *testing.T, base string) *session {
t.Helper()
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatal(err)
}
return &session{base: base, http: &http.Client{Jar: jar}}
}
func (s *session) call(t *testing.T, method, path string, body any, csrf bool) (int, map[string]any) {
t.Helper()
var buf io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
buf = bytes.NewReader(raw)
}
req, err := http.NewRequest(method, s.base+path, buf)
if err != nil {
t.Fatal(err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if csrf {
req.Header.Set("X-Tapremly-Request", "1")
}
resp, err := s.http.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
t.Fatalf("status %d body %s", resp.StatusCode, raw)
}
return resp.StatusCode, out
}
func (s *session) callAuth(t *testing.T, method, path, token string, body any) (int, map[string]any) {
t.Helper()
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequest(method, s.base+path, bytes.NewReader(raw))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := s.http.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
payload, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
var out map[string]any
if err := json.Unmarshal(payload, &out); err != nil {
t.Fatalf("status %d body %s", resp.StatusCode, payload)
}
return resp.StatusCode, out
}
func dataOf(t *testing.T, env map[string]any) map[string]any {
t.Helper()
data, ok := env["data"].(map[string]any)
if !ok {
t.Fatalf("data %#v", env)
}
return data
}
func TestHealthAndAccounts(t *testing.T) {
env := newEnv(t)
resp, err := http.Get(env.srv.URL + "/healthz")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("health %d", resp.StatusCode)
}
s := newSession(t, env.srv.URL)
status, body := s.call(t, http.MethodPost, "/api/register", map[string]string{"username": "alice", "password": "alice-pass-1"}, false)
if status != http.StatusOK || dataOf(t, body)["role"] != "admin" {
t.Fatalf("register admin %d %#v", status, body)
}
bob := newSession(t, env.srv.URL)
status, body = bob.call(t, http.MethodPost, "/api/register", map[string]string{"username": "bob", "password": "bob-pass-12"}, false)
if status != http.StatusOK || dataOf(t, body)["role"] != "user" {
t.Fatalf("register user %d %#v", status, body)
}
status, _ = s.call(t, http.MethodPost, "/api/groups", map[string]string{"name": "家里"}, false)
if status != http.StatusForbidden {
t.Fatalf("csrf %d", status)
}
status, body = s.call(t, http.MethodGet, "/api/admin/users", nil, false)
if status != http.StatusOK {
t.Fatalf("users %d %#v", status, body)
}
items := dataOf(t, body)["items"].([]any)
var bobID float64
for _, item := range items {
row := item.(map[string]any)
if row["username"] == "bob" {
bobID = row["id"].(float64)
}
}
status, _ = s.call(t, http.MethodPost, "/api/admin/users/1/status", map[string]any{"enabled": false}, true)
if status != http.StatusForbidden {
t.Fatalf("self disable %d", status)
}
status, _ = s.call(t, http.MethodPost, "/api/admin/users/"+formatID(bobID)+"/status", map[string]any{"enabled": false}, true)
if status != http.StatusOK {
t.Fatalf("disable bob %d", status)
}
other := newSession(t, env.srv.URL)
status, body = other.call(t, http.MethodPost, "/api/login", map[string]string{"username": "bob", "password": "bob-pass-12"}, false)
if status != http.StatusForbidden {
t.Fatalf("disabled login %d %#v", status, body)
}
status, _ = bob.call(t, http.MethodGet, "/api/me", nil, false)
if status != http.StatusForbidden {
t.Fatalf("disabled session %d", status)
}
status, _ = s.call(t, http.MethodPost, "/api/logout", map[string]any{}, true)
if status != http.StatusOK {
t.Fatalf("logout %d", status)
}
status, _ = s.call(t, http.MethodGet, "/api/me", nil, false)
if status != http.StatusUnauthorized {
t.Fatalf("after logout %d", status)
}
}
func TestGroupsDevicesAndLogs(t *testing.T) {
env := newEnv(t)
alice := newSession(t, env.srv.URL)
status, body := alice.call(t, http.MethodPost, "/api/register", map[string]string{"username": "alice", "password": "alice-pass-1"}, false)
if status != http.StatusOK {
t.Fatal(body)
}
status, body = alice.call(t, http.MethodPost, "/api/groups", map[string]string{"name": "家里"}, true)
if status != http.StatusOK {
t.Fatalf("group %d %#v", status, body)
}
groupID := dataOf(t, body)["id"]
status, body = alice.call(t, http.MethodPost, "/api/devices", map[string]any{"name": "客厅电脑", "group_id": groupID}, true)
if status != http.StatusOK {
t.Fatalf("device %d %#v", status, body)
}
created := dataOf(t, body)
deviceID := created["id"]
endpointID, _ := created["endpoint_id"].(string)
password, _ := created["login_password"].(string)
if endpointID != "00000001" || password == "" {
t.Fatalf("missing one-time secret %#v", created)
}
if created["presence"] != "online" {
t.Fatalf("presence %#v", created["presence"])
}
status, body = alice.call(t, http.MethodPost, "/api/devices", map[string]any{"name": "卧室", "group_id": groupID}, true)
if status != http.StatusOK {
t.Fatalf("second device %d %#v", status, body)
}
secondID := dataOf(t, body)["endpoint_id"].(string)
if secondID != "00000002" {
t.Fatalf("second endpoint %s", secondID)
}
status, body = alice.call(t, http.MethodGet, "/api/devices", nil, false)
if status != http.StatusOK {
t.Fatal(body)
}
if strings.Contains(string(mustJSON(body)), password) {
t.Fatal("list leaked initial password")
}
status, body = alice.call(t, http.MethodPatch, "/api/groups/"+formatID(groupID.(float64)), map[string]string{"name": "住宅"}, true)
if status != http.StatusOK || dataOf(t, body)["name"] != "住宅" {
t.Fatalf("rename %#v", body)
}
status, _ = alice.call(t, http.MethodDelete, "/api/groups/"+formatID(groupID.(float64)), nil, true)
if status != http.StatusOK {
t.Fatalf("delete group %d", status)
}
status, body = alice.call(t, http.MethodGet, "/api/devices", nil, false)
if status != http.StatusOK {
t.Fatal(body)
}
list := dataOf(t, body)
if groups, _ := list["groups"].([]any); len(groups) != 0 {
t.Fatalf("groups remain %#v", list["groups"])
}
for _, item := range list["devices"].([]any) {
dev := item.(map[string]any)
if dev["group_id"] != nil {
t.Fatalf("device still grouped %#v", dev)
}
if _, ok := env.nix.online[dev["endpoint_id"].(string)]; !ok {
t.Fatalf("endpoint removed from nix %#v", dev)
}
}
anon := newSession(t, env.srv.URL)
status, _ = anon.callAuth(t, http.MethodPut, "/api/command-logs", "wrong-password", map[string]any{
"endpoint_id": endpointID,
"items": []map[string]any{{"at_ms": 10, "summary": "关机", "ok": true, "result": "已执行"}},
})
if status != http.StatusUnauthorized {
t.Fatalf("bad credential %d", status)
}
items := make([]map[string]any, 0, 21)
for i := 1; i <= 21; i++ {
items = append(items, map[string]any{"at_ms": i, "summary": "一条", "ok": true, "result": ""})
}
status, _ = anon.callAuth(t, http.MethodPut, "/api/command-logs", password, map[string]any{
"endpoint_id": endpointID,
"items": items,
})
if status != http.StatusBadRequest {
t.Fatalf("too many %d", status)
}
status, _ = anon.callAuth(t, http.MethodPut, "/api/command-logs", password, map[string]any{
"endpoint_id": endpointID,
"items": []map[string]any{
{"at_ms": 20, "summary": "开灯", "ok": false, "result": "没执行"},
{"at_ms": 30, "summary": "关机", "ok": true, "result": "已执行", "password": password},
},
})
if status != http.StatusBadRequest {
t.Fatalf("secret field %d", status)
}
status, _ = anon.callAuth(t, http.MethodPut, "/api/command-logs", password, map[string]any{
"endpoint_id": endpointID,
"password": password,
"items": []map[string]any{{"at_ms": 30, "summary": "关机", "ok": true, "result": "已执行"}},
})
if status != http.StatusBadRequest {
t.Fatalf("secret field top %d", status)
}
status, body = anon.callAuth(t, http.MethodPut, "/api/command-logs", password, map[string]any{
"endpoint_id": endpointID,
"items": []map[string]any{
{"at_ms": 20, "summary": "开灯", "ok": false, "result": "没执行"},
{"at_ms": 30, "summary": "关机", "ok": true, "result": "已执行"},
},
})
if status != http.StatusOK {
t.Fatalf("replace %d %#v", status, body)
}
status, body = alice.call(t, http.MethodGet, "/api/devices/"+formatID(deviceID.(float64))+"/command-logs", nil, false)
if status != http.StatusOK {
t.Fatalf("logs %d %#v", status, body)
}
got := dataOf(t, body)["items"].([]any)
if len(got) != 2 || got[0].(map[string]any)["summary"] != "关机" {
t.Fatalf("order %#v", got)
}
if strings.Contains(string(mustJSON(body)), password) {
t.Fatal("logs contain password")
}
n, err := env.store.PlaintextSecretCount(context.Background(), password)
if err != nil || n != 0 {
t.Fatalf("plaintext count %d %v", n, err)
}
n, err = env.store.PlaintextSecretCount(context.Background(), env.nix.password(secondID))
if err != nil || n != 0 {
t.Fatalf("second plaintext %d %v", n, err)
}
bob := newSession(t, env.srv.URL)
status, _ = bob.call(t, http.MethodPost, "/api/register", map[string]string{"username": "bob", "password": "bob-pass-12"}, false)
if status != http.StatusOK {
t.Fatal(status)
}
status, body = bob.call(t, http.MethodPost, "/api/devices", map[string]any{"name": "对方的电脑", "endpoint_id": endpointID}, true)
if status != http.StatusOK {
t.Fatalf("link %d %#v", status, body)
}
if _, ok := dataOf(t, body)["login_password"]; ok {
t.Fatal("linked device returned a password")
}
linkedID := dataOf(t, body)["id"].(float64)
status, body = bob.call(t, http.MethodGet, "/api/devices/"+formatID(linkedID)+"/command-logs", nil, false)
if status != http.StatusOK || len(dataOf(t, body)["items"].([]any)) != 2 {
t.Fatalf("shared logs %#v", body)
}
status, _ = bob.call(t, http.MethodGet, "/api/devices/"+formatID(deviceID.(float64))+"/command-logs", nil, false)
if status != http.StatusNotFound {
t.Fatalf("other device id %d", status)
}
}
func TestBootstrapAdmin(t *testing.T) {
env := newEnv(t)
created, generated, err := boot.Admin(context.Background(), env.store, "root", "")
if err != nil || !created || generated == "" {
t.Fatalf("bootstrap %v %v %q", created, err, generated)
}
if err := auth.ValidatePassword(generated); err != nil {
t.Fatal(err)
}
again, gen2, err := boot.Admin(context.Background(), env.store, "root", "")
if err != nil || again || gen2 != "" {
t.Fatalf("second bootstrap %v %q %v", again, gen2, err)
}
s := newSession(t, env.srv.URL)
status, body := s.call(t, http.MethodPost, "/api/login", map[string]string{"username": "root", "password": generated}, false)
if status != http.StatusOK || dataOf(t, body)["role"] != "admin" {
t.Fatalf("login bootstrap %d %#v", status, body)
}
status, body = newSession(t, env.srv.URL).call(t, http.MethodPost, "/api/register", map[string]string{"username": "later", "password": "later-pass-1"}, false)
if status != http.StatusOK || dataOf(t, body)["role"] != "user" {
t.Fatalf("later user %#v", body)
}
}
func formatID(n float64) string {
return strings.TrimSuffix(strings.TrimSuffix(jsonNumber(n), ".0"), ".")
}
func jsonNumber(n float64) string {
b, _ := json.Marshal(n)
return string(b)
}
func mustJSON(v any) []byte {
b, _ := json.Marshal(v)
return b
}