feat: 实现账号设备分组与命令日志
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemoryKiB = 19 * 1024
|
||||
argonTime = 2
|
||||
argonThreads = 1
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
|
||||
MinPasswordLen = 8
|
||||
MaxPasswordLen = 128
|
||||
)
|
||||
|
||||
const passwordAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"
|
||||
|
||||
var ErrInvalidHash = errors.New("auth: invalid password hash")
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := argon2.IDKey([]byte(password), salt, argonTime, argonMemoryKiB, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
argonMemoryKiB,
|
||||
argonTime,
|
||||
argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(sum),
|
||||
), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encoded string) (bool, error) {
|
||||
salt, want, err := decodeHash(encoded)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, argonTime, argonMemoryKiB, argonThreads, argonKeyLen)
|
||||
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||
}
|
||||
|
||||
func ValidatePassword(password string) error {
|
||||
n := utf8.RuneCountInString(password)
|
||||
if n < MinPasswordLen || n > MaxPasswordLen {
|
||||
return fmt.Errorf("password length")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GeneratePassword(n int) (string, error) {
|
||||
if n < MinPasswordLen {
|
||||
n = MinPasswordLen
|
||||
}
|
||||
buf := make([]byte, n)
|
||||
alpha := []byte(passwordAlphabet)
|
||||
for i := 0; i < n; {
|
||||
var b [1]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if int(b[0]) >= 256-(256%len(alpha)) {
|
||||
continue
|
||||
}
|
||||
buf[i] = alpha[int(b[0])%len(alpha)]
|
||||
i++
|
||||
}
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
func decodeHash(encoded string) (salt, sum []byte, err error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
var version int
|
||||
if _, scanErr := fmt.Sscanf(parts[2], "v=%d", &version); scanErr != nil || version != argon2.Version {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
var memory, timeCost, threads int
|
||||
if _, scanErr := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); scanErr != nil {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
if memory != argonMemoryKiB || timeCost != argonTime || threads != argonThreads {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
salt, err = base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) != argonSaltLen {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
sum, err = base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(sum) != argonKeyLen {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
return salt, sum, nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package boot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.asio.asia/TapRemly/server/internal/auth"
|
||||
"git.asio.asia/TapRemly/server/internal/store"
|
||||
)
|
||||
|
||||
// Admin 在还没有管理员时,用给定账号创建一个。
|
||||
// password 为空则生成密码,并通过 generated 返回,调用方只应打印一次。
|
||||
func Admin(ctx context.Context, st *store.Store, username, password string) (created bool, generated string, err error) {
|
||||
if username == "" {
|
||||
return false, "", nil
|
||||
}
|
||||
has, err := st.HasAdmin(ctx)
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
if has {
|
||||
return false, "", nil
|
||||
}
|
||||
if password == "" {
|
||||
password, err = auth.GeneratePassword(20)
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
generated = password
|
||||
}
|
||||
if err := auth.ValidatePassword(password); err != nil {
|
||||
return false, "", fmt.Errorf("bootstrap admin password is too short")
|
||||
}
|
||||
hash, err := auth.HashPassword(password)
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
created, err = st.CreateAdmin(ctx, username, hash)
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
if !created {
|
||||
return false, "", nil
|
||||
}
|
||||
return true, generated, nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Listen string
|
||||
DataDir string
|
||||
CookieSecure bool
|
||||
NixMsgURL string
|
||||
NixMsgAdminUser string
|
||||
NixMsgAdminPassword string
|
||||
AdminUsername string
|
||||
AdminPassword string
|
||||
}
|
||||
|
||||
func FromEnv() (Config, error) {
|
||||
cfg := Config{
|
||||
Listen: getenv("TAPREMLY_LISTEN", ":8080"),
|
||||
DataDir: getenv("TAPREMLY_DATA_DIR", "data"),
|
||||
CookieSecure: getenvBool("TAPREMLY_COOKIE_SECURE"),
|
||||
NixMsgURL: strings.TrimRight(getenv("NIXMSG_URL", "http://127.0.0.1:7443"), "/"),
|
||||
NixMsgAdminUser: getenv("NIXMSG_ADMIN_USER", "admin"),
|
||||
AdminUsername: strings.TrimSpace(os.Getenv("TAPREMLY_ADMIN_USERNAME")),
|
||||
AdminPassword: os.Getenv("TAPREMLY_ADMIN_PASSWORD"),
|
||||
}
|
||||
cfg.NixMsgAdminPassword = os.Getenv("NIXMSG_ADMIN_PASSWORD")
|
||||
if strings.TrimSpace(cfg.NixMsgAdminPassword) == "" {
|
||||
path := strings.TrimSpace(os.Getenv("NIXMSG_ADMIN_PASSWORD_FILE"))
|
||||
if path != "" {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("read nixmsg admin password file: %w", err)
|
||||
}
|
||||
cfg.NixMsgAdminPassword = strings.TrimSpace(string(b))
|
||||
}
|
||||
} else {
|
||||
cfg.NixMsgAdminPassword = strings.TrimSpace(cfg.NixMsgAdminPassword)
|
||||
}
|
||||
if cfg.Listen == "" {
|
||||
return Config{}, fmt.Errorf("listen address is empty")
|
||||
}
|
||||
if cfg.DataDir == "" {
|
||||
return Config{}, fmt.Errorf("data dir is empty")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
v := strings.TrimSpace(os.Getenv(key))
|
||||
if v == "" {
|
||||
return fallback
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func getenvBool(key string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
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, string) (string, string, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.next++
|
||||
id := "e_dev" + string(rune('0'+f.next))
|
||||
if f.next >= 10 {
|
||||
id = "e_devx"
|
||||
}
|
||||
pw := "DevicePassw0rd" + string(rune('0'+f.next))
|
||||
f.online[id] = f.next == 1
|
||||
f.passwords[id] = pw
|
||||
return id, 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 == "" || 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)
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.asio.asia/TapRemly/server/internal/auth"
|
||||
"git.asio.asia/TapRemly/server/internal/store"
|
||||
)
|
||||
|
||||
func (h *Handler) register(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !decodeJSON(w, r, maxLoginBody, &req) {
|
||||
return
|
||||
}
|
||||
username := strings.TrimSpace(req.Username)
|
||||
if !validUsername(username) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "账号需要 2 到 32 个字符,可以用中文、字母、数字、下划线或连字符")
|
||||
return
|
||||
}
|
||||
if err := auth.ValidatePassword(req.Password); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "密码至少 8 位")
|
||||
return
|
||||
}
|
||||
hash, err := auth.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
h.log.Error("hash password")
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
user, err := h.store.Register(r.Context(), username, hash)
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
writeError(w, http.StatusConflict, "conflict", "这个账号已经有人用了")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.log.Error("register", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
if err := h.setSession(w, r, user.ID); err != nil {
|
||||
h.log.Error("session", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
writeOK(w, toPublic(user))
|
||||
}
|
||||
|
||||
func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !decodeJSON(w, r, maxLoginBody, &req) {
|
||||
return
|
||||
}
|
||||
user, err := h.store.UserByUsername(r.Context(), strings.TrimSpace(req.Username))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "账号或密码不正确")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.log.Error("login lookup", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
ok, err := auth.VerifyPassword(req.Password, user.PasswordHash)
|
||||
if err != nil || !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "账号或密码不正确")
|
||||
return
|
||||
}
|
||||
if !user.Enabled {
|
||||
writeError(w, http.StatusForbidden, "forbidden", "账号已停用")
|
||||
return
|
||||
}
|
||||
if err := h.setSession(w, r, user.ID); err != nil {
|
||||
h.log.Error("session", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
writeOK(w, toPublic(user))
|
||||
}
|
||||
|
||||
func (h *Handler) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.requireUser(w, r); !ok {
|
||||
return
|
||||
}
|
||||
h.clearSession(w, r)
|
||||
writeOK(w, map[string]any{})
|
||||
}
|
||||
|
||||
func (h *Handler) me(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeOK(w, toPublic(user))
|
||||
}
|
||||
|
||||
func (h *Handler) listUsers(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.requireAdmin(w, r); !ok {
|
||||
return
|
||||
}
|
||||
users, err := h.store.ListUsers(r.Context())
|
||||
if err != nil {
|
||||
h.log.Error("list users", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
items := make([]publicUser, 0, len(users))
|
||||
for _, u := range users {
|
||||
items = append(items, toPublic(u))
|
||||
}
|
||||
writeOK(w, map[string]any{"items": items})
|
||||
}
|
||||
|
||||
func (h *Handler) setUserStatus(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := h.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := parseID(r.PathValue("id"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "找不到这个账号")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if !decodeJSON(w, r, maxLoginBody, &req) {
|
||||
return
|
||||
}
|
||||
if req.Enabled == nil {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "请选择启用或停用")
|
||||
return
|
||||
}
|
||||
user, err := h.store.SetEnabled(r.Context(), actor.ID, id, *req.Enabled)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这个账号")
|
||||
case errors.Is(err, store.ErrForbidden):
|
||||
writeError(w, http.StatusForbidden, "forbidden", "不能停用自己")
|
||||
case errors.Is(err, store.ErrLastAdmin):
|
||||
writeError(w, http.StatusConflict, "conflict", "至少要留下一位可用的管理员")
|
||||
case err != nil:
|
||||
h.log.Error("set user status", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
default:
|
||||
writeOK(w, toPublic(user))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.asio.asia/TapRemly/server/internal/auth"
|
||||
"git.asio.asia/TapRemly/server/internal/store"
|
||||
)
|
||||
|
||||
type deviceView struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
EndpointID string `json:"endpoint_id"`
|
||||
GroupID *int64 `json:"group_id"`
|
||||
Presence string `json:"presence"`
|
||||
Password string `json:"login_password,omitempty"`
|
||||
}
|
||||
|
||||
func viewDevice(d store.Device, presence string) deviceView {
|
||||
if presence == "" {
|
||||
presence = "unknown"
|
||||
}
|
||||
return deviceView{
|
||||
ID: d.ID,
|
||||
Name: d.Name,
|
||||
EndpointID: d.EndpointID,
|
||||
GroupID: d.GroupID,
|
||||
Presence: presence,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) listDevices(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
devices, err := h.store.ListDevices(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
h.log.Error("list devices", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
groups, err := h.store.ListGroups(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
h.log.Error("list groups", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
views := make([]deviceView, len(devices))
|
||||
var wg sync.WaitGroup
|
||||
sem := make(chan struct{}, 8)
|
||||
for i := range devices {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
views[i] = viewDevice(devices[i], h.presence(r, devices[i].EndpointID))
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
groupViews := make([]map[string]any, 0, len(groups))
|
||||
for _, g := range groups {
|
||||
groupViews = append(groupViews, map[string]any{"id": g.ID, "name": g.Name})
|
||||
}
|
||||
writeOK(w, map[string]any{"devices": views, "groups": groupViews})
|
||||
}
|
||||
|
||||
func (h *Handler) presence(r *http.Request, endpointID string) string {
|
||||
if h.nix == nil {
|
||||
return "unknown"
|
||||
}
|
||||
found, online, err := h.nix.Lookup(r.Context(), endpointID)
|
||||
if err != nil || !found {
|
||||
return "unknown"
|
||||
}
|
||||
if online {
|
||||
return "online"
|
||||
}
|
||||
return "offline"
|
||||
}
|
||||
|
||||
func (h *Handler) createDevice(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
EndpointID string `json:"endpoint_id"`
|
||||
GroupID *int64 `json:"group_id"`
|
||||
}
|
||||
if !decodeJSON(w, r, maxJSONBody, &req) {
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(req.Name)
|
||||
if !validDisplayName(name, 64) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "请填写设备名称,最多 64 个字")
|
||||
return
|
||||
}
|
||||
endpointID := strings.TrimSpace(req.EndpointID)
|
||||
var password string
|
||||
provisioned := false
|
||||
if endpointID == "" {
|
||||
if h.nix == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法新建设备")
|
||||
return
|
||||
}
|
||||
id, pw, err := h.nix.CreateEndpoint(r.Context(), name)
|
||||
if err != nil {
|
||||
h.log.Error("provision endpoint failed")
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法新建设备")
|
||||
return
|
||||
}
|
||||
endpointID = id
|
||||
password = pw
|
||||
provisioned = true
|
||||
} else if !validEndpointID(endpointID) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "端编号不正确")
|
||||
return
|
||||
} else {
|
||||
found, _, err := h.nix.Lookup(r.Context(), endpointID)
|
||||
if err != nil {
|
||||
h.log.Error("lookup endpoint")
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法确认这台设备")
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这台设备")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var hash string
|
||||
if provisioned {
|
||||
var err error
|
||||
hash, err = auth.HashPassword(password)
|
||||
if err != nil {
|
||||
h.rollbackEndpoint(r, endpointID)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
}
|
||||
device, err := h.store.AddDevice(r.Context(), user.ID, name, endpointID, hash, req.GroupID)
|
||||
if err != nil {
|
||||
if provisioned {
|
||||
h.rollbackEndpoint(r, endpointID)
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
writeError(w, http.StatusConflict, "conflict", "这台设备已经在列表里")
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
||||
default:
|
||||
h.log.Error("add device", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
}
|
||||
return
|
||||
}
|
||||
view := viewDevice(device, h.presence(r, device.EndpointID))
|
||||
if provisioned {
|
||||
view.Password = password
|
||||
}
|
||||
writeOK(w, view)
|
||||
}
|
||||
|
||||
func (h *Handler) rollbackEndpoint(r *http.Request, endpointID string) {
|
||||
if h.nix == nil || endpointID == "" {
|
||||
return
|
||||
}
|
||||
if err := h.nix.DeleteEndpoint(r.Context(), endpointID); err != nil {
|
||||
h.log.Error("rollback endpoint", "endpoint", endpointID)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) updateDevice(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := parseID(r.PathValue("id"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这台设备")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name *string `json:"name"`
|
||||
GroupID json.RawMessage `json:"group_id"`
|
||||
}
|
||||
if !decodeJSON(w, r, maxJSONBody, &req) {
|
||||
return
|
||||
}
|
||||
var name *string
|
||||
if req.Name != nil {
|
||||
trimmed := strings.TrimSpace(*req.Name)
|
||||
if !validDisplayName(trimmed, 64) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "请填写设备名称,最多 64 个字")
|
||||
return
|
||||
}
|
||||
name = &trimmed
|
||||
}
|
||||
var group store.GroupChange
|
||||
if req.GroupID != nil {
|
||||
group.Set = true
|
||||
if string(req.GroupID) == "null" {
|
||||
group.ID = nil
|
||||
} else {
|
||||
var n int64
|
||||
if err := json.Unmarshal(req.GroupID, &n); err != nil || n <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "找不到这个分组")
|
||||
return
|
||||
}
|
||||
group.ID = &n
|
||||
}
|
||||
}
|
||||
if name == nil && !group.Set {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "没有要修改的内容")
|
||||
return
|
||||
}
|
||||
device, err := h.store.UpdateDevice(r.Context(), user.ID, id, name, group)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这台设备或分组")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.log.Error("update device", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
writeOK(w, viewDevice(device, h.presence(r, device.EndpointID)))
|
||||
}
|
||||
|
||||
func (h *Handler) deleteDevice(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := parseID(r.PathValue("id"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这台设备")
|
||||
return
|
||||
}
|
||||
err := h.store.DeleteDevice(r.Context(), user.ID, id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这台设备")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.log.Error("delete device", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
writeOK(w, map[string]any{})
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.asio.asia/TapRemly/server/internal/store"
|
||||
)
|
||||
|
||||
func (h *Handler) createGroup(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if !decodeJSON(w, r, maxJSONBody, &req) {
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(req.Name)
|
||||
if !validDisplayName(name, 32) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "请填写分组名称,最多 32 个字")
|
||||
return
|
||||
}
|
||||
g, err := h.store.CreateGroup(r.Context(), user.ID, name)
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
writeError(w, http.StatusConflict, "conflict", "已经有同名分组")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.log.Error("create group", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
writeOK(w, map[string]any{"id": g.ID, "name": g.Name})
|
||||
}
|
||||
|
||||
func (h *Handler) renameGroup(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := parseID(r.PathValue("id"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if !decodeJSON(w, r, maxJSONBody, &req) {
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(req.Name)
|
||||
if !validDisplayName(name, 32) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "请填写分组名称,最多 32 个字")
|
||||
return
|
||||
}
|
||||
g, err := h.store.RenameGroup(r.Context(), user.ID, id, name)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
writeError(w, http.StatusConflict, "conflict", "已经有同名分组")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.log.Error("rename group", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
writeOK(w, map[string]any{"id": g.ID, "name": g.Name})
|
||||
}
|
||||
|
||||
func (h *Handler) deleteGroup(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := parseID(r.PathValue("id"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
||||
return
|
||||
}
|
||||
err := h.store.DeleteGroup(r.Context(), user.ID, id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这个分组")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.log.Error("delete group", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
writeOK(w, map[string]any{})
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.asio.asia/TapRemly/server/internal/auth"
|
||||
"git.asio.asia/TapRemly/server/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxCommandLogs = 20
|
||||
maxLogTextRunes = 200
|
||||
)
|
||||
|
||||
func (h *Handler) listLogs(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := parseID(r.PathValue("id"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这台设备")
|
||||
return
|
||||
}
|
||||
items, err := h.store.LogsForDevice(r.Context(), user.ID, id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "找不到这台设备")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.log.Error("list logs", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
out := make([]map[string]any, 0, len(items))
|
||||
for _, item := range items {
|
||||
out = append(out, map[string]any{
|
||||
"at_ms": item.AtMs,
|
||||
"summary": item.Summary,
|
||||
"ok": item.OK,
|
||||
"result": item.Result,
|
||||
})
|
||||
}
|
||||
writeOK(w, map[string]any{"items": out})
|
||||
}
|
||||
|
||||
func (h *Handler) replaceLogs(w http.ResponseWriter, r *http.Request) {
|
||||
password := bearer(r)
|
||||
if password == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "凭证无效")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
EndpointID string `json:"endpoint_id"`
|
||||
Items json.RawMessage `json:"items"`
|
||||
}
|
||||
if !decodeJSON(w, r, maxJSONBody, &req) {
|
||||
return
|
||||
}
|
||||
endpointID := strings.TrimSpace(req.EndpointID)
|
||||
if !validEndpointID(endpointID) || len(req.Items) == 0 || string(req.Items) == "null" {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "请提供这台设备最近的记录")
|
||||
return
|
||||
}
|
||||
var rawItems []struct {
|
||||
AtMs int64 `json:"at_ms"`
|
||||
Summary string `json:"summary"`
|
||||
OK bool `json:"ok"`
|
||||
Result string `json:"result"`
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(string(req.Items)))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&rawItems); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "记录内容不正确")
|
||||
return
|
||||
}
|
||||
if len(rawItems) > maxCommandLogs {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "最多保留 20 条")
|
||||
return
|
||||
}
|
||||
items := make([]store.LogItem, 0, len(rawItems))
|
||||
for _, item := range rawItems {
|
||||
summary := strings.TrimSpace(item.Summary)
|
||||
result := strings.TrimSpace(item.Result)
|
||||
if item.AtMs <= 0 || summary == "" || utf8.RuneCountInString(summary) > maxLogTextRunes || utf8.RuneCountInString(result) > maxLogTextRunes {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "记录内容不正确")
|
||||
return
|
||||
}
|
||||
items = append(items, store.LogItem{
|
||||
AtMs: item.AtMs,
|
||||
Summary: summary,
|
||||
OK: item.OK,
|
||||
Result: result,
|
||||
})
|
||||
}
|
||||
hash, err := h.store.CredentialHash(r.Context(), endpointID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "凭证无效")
|
||||
return
|
||||
}
|
||||
ok, err := auth.VerifyPassword(password, hash)
|
||||
if err != nil || !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "凭证无效")
|
||||
return
|
||||
}
|
||||
if err := h.store.ReplaceLogs(r.Context(), endpointID, items); err != nil {
|
||||
h.log.Error("replace logs", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
return
|
||||
}
|
||||
writeOK(w, map[string]any{})
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.asio.asia/TapRemly/server/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
cookieName = "tapremly_session"
|
||||
csrfHeader = "X-Tapremly-Request"
|
||||
sessionTTL = 7 * 24 * time.Hour
|
||||
maxLoginBody = 8 << 10
|
||||
maxJSONBody = 1 << 20
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.Store
|
||||
nix EndpointService
|
||||
cookieSecure bool
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
type EndpointService interface {
|
||||
CreateEndpoint(ctx context.Context, name string) (id, password string, err error)
|
||||
Lookup(ctx context.Context, id string) (found, online bool, err error)
|
||||
DeleteEndpoint(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
func New(st *store.Store, nix EndpointService, cookieSecure bool, log *slog.Logger) *Handler {
|
||||
if log == nil {
|
||||
log = slog.New(slog.NewJSONHandler(io.Discard, nil))
|
||||
}
|
||||
return &Handler{store: st, nix: nix, cookieSecure: cookieSecure, log: log}
|
||||
}
|
||||
|
||||
func (h *Handler) Routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", h.health)
|
||||
mux.HandleFunc("GET /readyz", h.ready)
|
||||
mux.HandleFunc("POST /api/register", h.register)
|
||||
mux.HandleFunc("POST /api/login", h.login)
|
||||
mux.HandleFunc("POST /api/logout", h.logout)
|
||||
mux.HandleFunc("GET /api/me", h.me)
|
||||
mux.HandleFunc("GET /api/devices", h.listDevices)
|
||||
mux.HandleFunc("POST /api/devices", h.createDevice)
|
||||
mux.HandleFunc("PATCH /api/devices/{id}", h.updateDevice)
|
||||
mux.HandleFunc("DELETE /api/devices/{id}", h.deleteDevice)
|
||||
mux.HandleFunc("GET /api/devices/{id}/command-logs", h.listLogs)
|
||||
mux.HandleFunc("PUT /api/command-logs", h.replaceLogs)
|
||||
mux.HandleFunc("POST /api/groups", h.createGroup)
|
||||
mux.HandleFunc("PATCH /api/groups/{id}", h.renameGroup)
|
||||
mux.HandleFunc("DELETE /api/groups/{id}", h.deleteGroup)
|
||||
mux.HandleFunc("GET /api/admin/users", h.listUsers)
|
||||
mux.HandleFunc("POST /api/admin/users/{id}/status", h.setUserStatus)
|
||||
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "没有这个功能")
|
||||
})
|
||||
mux.Handle("/", h.spa())
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
h.log.Error("panic", "err", rec)
|
||||
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
|
||||
}
|
||||
}()
|
||||
mux.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) health(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (h *Handler) ready(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.store.Ping(r.Context()); err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
type publicUser struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
func toPublic(u store.User) publicUser {
|
||||
return publicUser{ID: u.ID, Username: u.Username, Role: u.Role, Enabled: u.Enabled}
|
||||
}
|
||||
|
||||
func (h *Handler) requireUser(w http.ResponseWriter, r *http.Request) (store.User, bool) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
if r.Header.Get(csrfHeader) != "1" {
|
||||
writeError(w, http.StatusForbidden, "forbidden", "请从页面发起这个操作")
|
||||
return store.User{}, false
|
||||
}
|
||||
}
|
||||
c, err := r.Cookie(cookieName)
|
||||
if err != nil || c.Value == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "请先登录")
|
||||
return store.User{}, false
|
||||
}
|
||||
u, err := h.store.UserBySession(r.Context(), hashToken(c.Value), time.Now().UnixMilli())
|
||||
if errors.Is(err, store.ErrForbidden) {
|
||||
writeError(w, http.StatusForbidden, "forbidden", "账号已停用")
|
||||
return store.User{}, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "请先登录")
|
||||
return store.User{}, false
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
func (h *Handler) requireAdmin(w http.ResponseWriter, r *http.Request) (store.User, bool) {
|
||||
u, ok := h.requireUser(w, r)
|
||||
if !ok {
|
||||
return store.User{}, false
|
||||
}
|
||||
if u.Role != "admin" {
|
||||
writeError(w, http.StatusForbidden, "forbidden", "没有权限")
|
||||
return store.User{}, false
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
func (h *Handler) setSession(w http.ResponseWriter, r *http.Request, userID int64) error {
|
||||
plain, hash, err := newToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
exp := time.Now().Add(sessionTTL)
|
||||
if err := h.store.CreateSession(r.Context(), userID, hash, exp.UnixMilli()); err != nil {
|
||||
return err
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: plain,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Secure: h.cookieSecure,
|
||||
MaxAge: int(sessionTTL.Seconds()),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) clearSession(w http.ResponseWriter, r *http.Request) {
|
||||
if c, err := r.Cookie(cookieName); err == nil && c.Value != "" {
|
||||
_ = h.store.DeleteSession(r.Context(), hashToken(c.Value))
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Secure: h.cookieSecure,
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
|
||||
func newToken() (plain, hash string, err error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err = rand.Read(buf); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
plain = base64.RawURLEncoding.EncodeToString(buf)
|
||||
return plain, hashToken(plain), nil
|
||||
}
|
||||
|
||||
func hashToken(plain string) string {
|
||||
sum := sha256.Sum256([]byte(plain))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, max int64, dest any) bool {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, max)
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dest); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "提交的内容不正确")
|
||||
return false
|
||||
}
|
||||
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "提交的内容不正确")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeOK(w http.ResponseWriter, data any) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "data": data})
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, code, message string) {
|
||||
writeJSON(w, status, map[string]any{
|
||||
"ok": false,
|
||||
"error": map[string]string{
|
||||
"code": code,
|
||||
"message": message,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func validUsername(s string) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
if n < 2 || n > 32 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '-' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validDisplayName(s string, max int) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
if n < 1 || n > max {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validEndpointID(s string) bool {
|
||||
if len(s) < 1 || len(s) > 64 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '.' || r == '-' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func bearer(r *http.Request) string {
|
||||
h := r.Header.Get("Authorization")
|
||||
const prefix = "Bearer "
|
||||
if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(h[len(prefix):])
|
||||
}
|
||||
|
||||
func parseID(s string) (int64, bool) {
|
||||
if s == "" {
|
||||
return 0, false
|
||||
}
|
||||
var n int64
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return 0, false
|
||||
}
|
||||
n = n*10 + int64(r-'0')
|
||||
if n < 0 {
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"git.asio.asia/TapRemly/server/internal/webui"
|
||||
)
|
||||
|
||||
func (h *Handler) spa() http.Handler {
|
||||
sub, err := fs.Sub(webui.Dist, "dist")
|
||||
if err != nil {
|
||||
return http.NotFoundHandler()
|
||||
}
|
||||
if _, err := fs.Stat(sub, "index.html"); err != nil {
|
||||
return http.NotFoundHandler()
|
||||
}
|
||||
files := http.FileServer(http.FS(sub))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
rel := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
|
||||
if rel == "" || rel == "." {
|
||||
serveIndex(w, r, sub)
|
||||
return
|
||||
}
|
||||
info, err := fs.Stat(sub, rel)
|
||||
if err == nil && !info.IsDir() {
|
||||
if strings.HasPrefix(rel, "assets/") {
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
}
|
||||
files.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if path.Ext(rel) != "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
serveIndex(w, r, sub)
|
||||
})
|
||||
}
|
||||
|
||||
func serveIndex(w http.ResponseWriter, r *http.Request, fsys fs.FS) {
|
||||
f, err := fsys.Open("index.html")
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if r.Method == http.MethodHead {
|
||||
return
|
||||
}
|
||||
_, _ = io.Copy(w, f)
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package nixmsg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
baseURL string
|
||||
username string
|
||||
password string
|
||||
http *http.Client
|
||||
mu sync.Mutex
|
||||
loggedIn bool
|
||||
}
|
||||
|
||||
func New(baseURL, username, password string) (*Client, error) {
|
||||
jar, err := cookiejar.New(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Client{
|
||||
baseURL: strings.TrimRight(baseURL, "/"),
|
||||
username: username,
|
||||
password: password,
|
||||
http: &http.Client{
|
||||
Timeout: 20 * time.Second,
|
||||
Jar: jar,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
type Endpoint struct {
|
||||
ID string
|
||||
LoginPassword string
|
||||
Online bool
|
||||
Found bool
|
||||
}
|
||||
|
||||
func (c *Client) CreateEndpoint(ctx context.Context, name string) (Endpoint, error) {
|
||||
var out struct {
|
||||
ID string `json:"id"`
|
||||
LoginPassword string `json:"login_password"`
|
||||
}
|
||||
err := c.call(ctx, http.MethodPost, "/api/admin/endpoints", map[string]any{
|
||||
"id": "",
|
||||
"name": name,
|
||||
"remark": "",
|
||||
"login_password": "",
|
||||
"talk_password": "",
|
||||
"default_delay_seconds": 0,
|
||||
}, &out)
|
||||
if err != nil {
|
||||
return Endpoint{}, err
|
||||
}
|
||||
if out.ID == "" || out.LoginPassword == "" {
|
||||
return Endpoint{}, errors.New("nixmsg: endpoint was created without a one-time password")
|
||||
}
|
||||
return Endpoint{ID: out.ID, LoginPassword: out.LoginPassword, Found: true}, nil
|
||||
}
|
||||
|
||||
func (c *Client) DeleteEndpoint(ctx context.Context, id string) error {
|
||||
return c.call(ctx, http.MethodDelete, "/api/admin/endpoints/"+id, nil, nil)
|
||||
}
|
||||
|
||||
func (c *Client) Lookup(ctx context.Context, id string) (Endpoint, error) {
|
||||
var out struct {
|
||||
ID string `json:"id"`
|
||||
Online bool `json:"online"`
|
||||
}
|
||||
err := c.call(ctx, http.MethodGet, "/api/admin/endpoints/"+id, nil, &out)
|
||||
if err != nil {
|
||||
var apiErr *APIError
|
||||
if errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound {
|
||||
return Endpoint{Found: false}, nil
|
||||
}
|
||||
return Endpoint{}, err
|
||||
}
|
||||
return Endpoint{ID: out.ID, Online: out.Online, Found: true}, nil
|
||||
}
|
||||
|
||||
type APIError struct {
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string {
|
||||
if e.Message != "" {
|
||||
return e.Message
|
||||
}
|
||||
return fmt.Sprintf("nixmsg status %d", e.Status)
|
||||
}
|
||||
|
||||
func (c *Client) call(ctx context.Context, method, path string, body any, dest any) error {
|
||||
status, payload, err := c.do(ctx, method, path, body, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &env); err != nil {
|
||||
return fmt.Errorf("nixmsg: invalid response")
|
||||
}
|
||||
if status < 200 || status >= 300 || !env.OK {
|
||||
return &APIError{Status: status, Code: env.Error.Code, Message: env.Error.Message}
|
||||
}
|
||||
if dest != nil && len(env.Data) > 0 && string(env.Data) != "null" {
|
||||
if err := json.Unmarshal(env.Data, dest); err != nil {
|
||||
return fmt.Errorf("nixmsg: invalid data")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, path string, body any, retry bool) (int, []byte, error) {
|
||||
status, payload, err := c.roundTrip(ctx, method, path, body)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
if status == http.StatusUnauthorized && retry && path != "/api/admin/login" {
|
||||
if err := c.login(ctx); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return c.do(ctx, method, path, body, false)
|
||||
}
|
||||
return status, payload, nil
|
||||
}
|
||||
|
||||
func (c *Client) login(ctx context.Context) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
status, payload, err := c.roundTrip(ctx, http.MethodPost, "/api/admin/login", map[string]string{
|
||||
"username": c.username,
|
||||
"password": c.password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
return &APIError{Status: status, Message: "nixmsg login failed"}
|
||||
}
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &env); err != nil || !env.OK {
|
||||
return errors.New("nixmsg login failed")
|
||||
}
|
||||
c.loggedIn = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) roundTrip(ctx context.Context, method, path string, body any) (int, []byte, error) {
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
reader = bytes.NewReader(raw)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if method != http.MethodGet && method != http.MethodHead && path != "/api/admin/login" {
|
||||
req.Header.Set("X-Nixmsg-Request", "1")
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return resp.StatusCode, payload, nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package nixmsg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClientCreatesAndReadsEndpoint(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
online := map[string]bool{}
|
||||
var sawCSRF bool
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/admin/login", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Password != "nix-secret" || req.Username != "admin" {
|
||||
http.Error(w, "no", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "nixmsg_admin", Value: "session", Path: "/"})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "data": map[string]any{"username": "admin"}})
|
||||
})
|
||||
mux.HandleFunc("POST /api/admin/endpoints", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-Nixmsg-Request") != "1" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": map[string]string{"code": "forbidden", "message": "missing header"}})
|
||||
return
|
||||
}
|
||||
c, err := r.Cookie("nixmsg_admin")
|
||||
if err != nil || c.Value == "" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": map[string]string{"code": "unauthorized", "message": "no"}})
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
sawCSRF = true
|
||||
online["e_abc"] = true
|
||||
mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "data": map[string]any{"id": "e_abc", "login_password": "OnceFromNix12345"}})
|
||||
})
|
||||
mux.HandleFunc("GET /api/admin/endpoints/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
on := online[r.PathValue("id")]
|
||||
_, ok := online[r.PathValue("id")]
|
||||
mu.Unlock()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": map[string]string{"code": "not_found", "message": "missing"}})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "data": map[string]any{"id": r.PathValue("id"), "online": on}})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
client, err := New(srv.URL, "admin", "nix-secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ep, err := client.CreateEndpoint(context.Background(), "客厅")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ep.ID != "e_abc" || ep.LoginPassword != "OnceFromNix12345" {
|
||||
t.Fatalf("endpoint %+v", ep)
|
||||
}
|
||||
got, err := client.Lookup(context.Background(), "e_abc")
|
||||
if err != nil || !got.Found || !got.Online {
|
||||
t.Fatalf("lookup %+v %v", got, err)
|
||||
}
|
||||
missing, err := client.Lookup(context.Background(), "e_missing")
|
||||
if err != nil || missing.Found {
|
||||
t.Fatalf("missing %+v %v", missing, err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if !sawCSRF {
|
||||
t.Fatal("csrf header was not sent")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,695 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
const schemaVersion = 1
|
||||
|
||||
const schemaSQL = `
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL CHECK (role IN ('user', 'admin')),
|
||||
enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)),
|
||||
created_at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username ON users(username COLLATE NOCASE);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
created_at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_groups_user_name ON groups(user_id, name COLLATE NOCASE);
|
||||
CREATE INDEX IF NOT EXISTS idx_groups_user ON groups(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS endpoint_secrets (
|
||||
endpoint_id TEXT PRIMARY KEY,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at_ms INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
endpoint_id TEXT NOT NULL,
|
||||
group_id INTEGER REFERENCES groups(id) ON DELETE SET NULL,
|
||||
created_at_ms INTEGER NOT NULL,
|
||||
UNIQUE(user_id, endpoint_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_devices_user ON devices(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS command_logs (
|
||||
endpoint_id TEXT NOT NULL,
|
||||
ord INTEGER NOT NULL,
|
||||
at_ms INTEGER NOT NULL,
|
||||
summary TEXT NOT NULL,
|
||||
ok INTEGER NOT NULL,
|
||||
result TEXT NOT NULL,
|
||||
PRIMARY KEY (endpoint_id, ord)
|
||||
);
|
||||
`
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("store: not found")
|
||||
ErrConflict = errors.New("store: conflict")
|
||||
ErrForbidden = errors.New("store: forbidden")
|
||||
ErrLastAdmin = errors.New("store: last admin")
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID int64
|
||||
Username string
|
||||
PasswordHash string
|
||||
Role string
|
||||
Enabled bool
|
||||
CreatedAtMs int64
|
||||
}
|
||||
|
||||
type Group struct {
|
||||
ID int64
|
||||
Name string
|
||||
CreatedAtMs int64
|
||||
}
|
||||
|
||||
type Device struct {
|
||||
ID int64
|
||||
Name string
|
||||
EndpointID string
|
||||
GroupID *int64
|
||||
CreatedAtMs int64
|
||||
}
|
||||
|
||||
type LogItem struct {
|
||||
AtMs int64
|
||||
Summary string
|
||||
OK bool
|
||||
Result string
|
||||
}
|
||||
|
||||
type GroupChange struct {
|
||||
Set bool
|
||||
ID *int64
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func Open(path string) (*Store, error) {
|
||||
abs, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dsn := "file:" + filepath.ToSlash(abs) + "?_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)"
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
db.SetMaxIdleConns(1)
|
||||
if err := db.Ping(); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, err
|
||||
}
|
||||
for _, pragma := range []string{
|
||||
"PRAGMA foreign_keys = ON",
|
||||
"PRAGMA busy_timeout = 5000",
|
||||
"PRAGMA journal_mode = WAL",
|
||||
} {
|
||||
if _, err := db.Exec(pragma); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &Store{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error {
|
||||
return s.db.Close()
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
return s.db.PingContext(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) Migrate(ctx context.Context) error {
|
||||
if _, err := s.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER NOT NULL)`); err != nil {
|
||||
return err
|
||||
}
|
||||
var version int
|
||||
if err := s.db.QueryRowContext(ctx, `SELECT COALESCE(MAX(version), 0) FROM schema_migrations`).Scan(&version); err != nil {
|
||||
return err
|
||||
}
|
||||
if version >= schemaVersion {
|
||||
return nil
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if _, err := tx.ExecContext(ctx, schemaSQL); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES (?)`, schemaVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) HasAdmin(ctx context.Context) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = 'admin'`).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
func (s *Store) CreateAdmin(ctx context.Context, username, passwordHash string) (bool, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
var n int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = 'admin'`).Scan(&n); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if n > 0 {
|
||||
return false, nil
|
||||
}
|
||||
var existing int
|
||||
err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE username = ? COLLATE NOCASE`, username).Scan(&existing)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if existing > 0 {
|
||||
return false, ErrConflict
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO users(username, password_hash, role, enabled, created_at_ms)
|
||||
VALUES (?, ?, 'admin', 1, ?)`, username, passwordHash, nowMS())
|
||||
if err != nil {
|
||||
if isUnique(err) {
|
||||
return false, ErrConflict
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) Register(ctx context.Context, username, passwordHash string) (User, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO users(username, password_hash, role, enabled, created_at_ms)
|
||||
VALUES (?, ?, 'user', 1, ?)`, username, passwordHash, nowMS())
|
||||
if err != nil {
|
||||
if isUnique(err) {
|
||||
return User{}, ErrConflict
|
||||
}
|
||||
return User{}, err
|
||||
}
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE users SET role = 'admin'
|
||||
WHERE id = ? AND NOT EXISTS (
|
||||
SELECT 1 FROM users WHERE role = 'admin' AND id != ?
|
||||
)`, id, id); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return s.UserByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (User, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, username, password_hash, role, enabled, created_at_ms
|
||||
FROM users WHERE username = ? COLLATE NOCASE`, username)
|
||||
return scanUser(row)
|
||||
}
|
||||
|
||||
func (s *Store) UserByID(ctx context.Context, id int64) (User, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, username, password_hash, role, enabled, created_at_ms
|
||||
FROM users WHERE id = ?`, id)
|
||||
return scanUser(row)
|
||||
}
|
||||
|
||||
func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, username, password_hash, role, enabled, created_at_ms
|
||||
FROM users ORDER BY id ASC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []User
|
||||
for rows.Next() {
|
||||
u, err := scanUser(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, u)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) SetEnabled(ctx context.Context, actorID, targetID int64, enabled bool) (User, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
var role string
|
||||
var cur int
|
||||
err = tx.QueryRowContext(ctx, `SELECT role, enabled FROM users WHERE id = ?`, targetID).Scan(&role, &cur)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if !enabled && actorID == targetID {
|
||||
return User{}, ErrForbidden
|
||||
}
|
||||
if !enabled && role == "admin" && cur == 1 {
|
||||
var others int
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM users WHERE role = 'admin' AND enabled = 1 AND id != ?`, targetID).Scan(&others); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if others == 0 {
|
||||
return User{}, ErrLastAdmin
|
||||
}
|
||||
}
|
||||
flag := 0
|
||||
if enabled {
|
||||
flag = 1
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE users SET enabled = ? WHERE id = ?`, flag, targetID); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return s.UserByID(ctx, targetID)
|
||||
}
|
||||
|
||||
func (s *Store) CreateSession(ctx context.Context, userID int64, tokenHash string, expiresAtMs int64) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO sessions(token_hash, user_id, expires_at_ms) VALUES (?, ?, ?)`,
|
||||
tokenHash, userID, expiresAtMs)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) DeleteSession(ctx context.Context, tokenHash string) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE token_hash = ?`, tokenHash)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UserBySession(ctx context.Context, tokenHash string, now int64) (User, error) {
|
||||
var exp int64
|
||||
var u User
|
||||
var enabled int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT u.id, u.username, u.password_hash, u.role, u.enabled, u.created_at_ms, s.expires_at_ms
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ?`, tokenHash).Scan(
|
||||
&u.ID, &u.Username, &u.PasswordHash, &u.Role, &enabled, &u.CreatedAtMs, &exp)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
u.Enabled = enabled == 1
|
||||
if exp <= now {
|
||||
_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE token_hash = ?`, tokenHash)
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
if !u.Enabled {
|
||||
return User{}, ErrForbidden
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListGroups(ctx context.Context, userID int64) ([]Group, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, name, created_at_ms FROM groups
|
||||
WHERE user_id = ? ORDER BY created_at_ms ASC, id ASC`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Group
|
||||
for rows.Next() {
|
||||
var g Group
|
||||
if err := rows.Scan(&g.ID, &g.Name, &g.CreatedAtMs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, g)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) CreateGroup(ctx context.Context, userID int64, name string) (Group, error) {
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO groups(user_id, name, created_at_ms) VALUES (?, ?, ?)`,
|
||||
userID, name, nowMS())
|
||||
if err != nil {
|
||||
if isUnique(err) {
|
||||
return Group{}, ErrConflict
|
||||
}
|
||||
return Group{}, err
|
||||
}
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
return Group{ID: id, Name: name}, nil
|
||||
}
|
||||
|
||||
func (s *Store) RenameGroup(ctx context.Context, userID, groupID int64, name string) (Group, error) {
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
UPDATE groups SET name = ? WHERE id = ? AND user_id = ?`, name, groupID, userID)
|
||||
if err != nil {
|
||||
if isUnique(err) {
|
||||
return Group{}, ErrConflict
|
||||
}
|
||||
return Group{}, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
if n == 0 {
|
||||
return Group{}, ErrNotFound
|
||||
}
|
||||
return Group{ID: groupID, Name: name}, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteGroup(ctx context.Context, userID, groupID int64) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
var n int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM groups WHERE id = ? AND user_id = ?`, groupID, userID).Scan(&n); err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE devices SET group_id = NULL WHERE user_id = ? AND group_id = ?`, userID, groupID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM groups WHERE id = ? AND user_id = ?`, groupID, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) ListDevices(ctx context.Context, userID int64) ([]Device, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, name, endpoint_id, group_id, created_at_ms
|
||||
FROM devices WHERE user_id = ?
|
||||
ORDER BY created_at_ms ASC, id ASC`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Device
|
||||
for rows.Next() {
|
||||
d, err := scanDevice(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) AddDevice(ctx context.Context, userID int64, name, endpointID, passwordHash string, groupID *int64) (Device, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if groupID != nil {
|
||||
var n int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM groups WHERE id = ? AND user_id = ?`, *groupID, userID).Scan(&n); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
if n == 0 {
|
||||
return Device{}, ErrNotFound
|
||||
}
|
||||
}
|
||||
now := nowMS()
|
||||
if passwordHash != "" {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO endpoint_secrets(endpoint_id, password_hash, created_at_ms) VALUES (?, ?, ?)`,
|
||||
endpointID, passwordHash, now); err != nil {
|
||||
if isUnique(err) {
|
||||
return Device{}, ErrConflict
|
||||
}
|
||||
return Device{}, err
|
||||
}
|
||||
}
|
||||
var gid any
|
||||
if groupID != nil {
|
||||
gid = *groupID
|
||||
}
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO devices(user_id, name, endpoint_id, group_id, created_at_ms)
|
||||
VALUES (?, ?, ?, ?, ?)`, userID, name, endpointID, gid, now)
|
||||
if err != nil {
|
||||
if isUnique(err) {
|
||||
return Device{}, ErrConflict
|
||||
}
|
||||
return Device{}, err
|
||||
}
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
return Device{ID: id, Name: name, EndpointID: endpointID, GroupID: groupID, CreatedAtMs: now}, nil
|
||||
}
|
||||
|
||||
func (s *Store) UpdateDevice(ctx context.Context, userID, deviceID int64, name *string, group GroupChange) (Device, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
var n int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM devices WHERE id = ? AND user_id = ?`, deviceID, userID).Scan(&n); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
if n == 0 {
|
||||
return Device{}, ErrNotFound
|
||||
}
|
||||
if name != nil {
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE devices SET name = ? WHERE id = ? AND user_id = ?`, *name, deviceID, userID); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
}
|
||||
if group.Set {
|
||||
if group.ID != nil {
|
||||
var gn int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM groups WHERE id = ? AND user_id = ?`, *group.ID, userID).Scan(&gn); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
if gn == 0 {
|
||||
return Device{}, ErrNotFound
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE devices SET group_id = ? WHERE id = ? AND user_id = ?`, *group.ID, deviceID, userID); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
} else if _, err := tx.ExecContext(ctx, `UPDATE devices SET group_id = NULL WHERE id = ? AND user_id = ?`, deviceID, userID); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
return s.deviceByID(ctx, userID, deviceID)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteDevice(ctx context.Context, userID, deviceID int64) error {
|
||||
res, err := s.db.ExecContext(ctx, `DELETE FROM devices WHERE id = ? AND user_id = ?`, deviceID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CredentialHash(ctx context.Context, endpointID string) (string, error) {
|
||||
var hash string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT password_hash FROM endpoint_secrets WHERE endpoint_id = ?`, endpointID).Scan(&hash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
return hash, err
|
||||
}
|
||||
|
||||
func (s *Store) ReplaceLogs(ctx context.Context, endpointID string, items []LogItem) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM command_logs WHERE endpoint_id = ?`, endpointID); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, item := range items {
|
||||
ok := 0
|
||||
if item.OK {
|
||||
ok = 1
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO command_logs(endpoint_id, ord, at_ms, summary, ok, result)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, endpointID, i, item.AtMs, item.Summary, ok, item.Result); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) LogsForDevice(ctx context.Context, userID, deviceID int64) ([]LogItem, error) {
|
||||
var endpointID string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT endpoint_id FROM devices WHERE id = ? AND user_id = ?`, deviceID, userID).Scan(&endpointID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT at_ms, summary, ok, result FROM command_logs
|
||||
WHERE endpoint_id = ? ORDER BY at_ms DESC, ord ASC`, endpointID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []LogItem
|
||||
for rows.Next() {
|
||||
var item LogItem
|
||||
var ok int
|
||||
if err := rows.Scan(&item.AtMs, &item.Summary, &ok, &item.Result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.OK = ok == 1
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) deviceByID(ctx context.Context, userID, deviceID int64) (Device, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, name, endpoint_id, group_id, created_at_ms
|
||||
FROM devices WHERE id = ? AND user_id = ?`, deviceID, userID)
|
||||
d, err := scanDevice(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Device{}, ErrNotFound
|
||||
}
|
||||
return d, err
|
||||
}
|
||||
|
||||
type scanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanUser(row scanner) (User, error) {
|
||||
var u User
|
||||
var enabled int
|
||||
err := row.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role, &enabled, &u.CreatedAtMs)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
u.Enabled = enabled == 1
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func scanDevice(row scanner) (Device, error) {
|
||||
var d Device
|
||||
var gid sql.NullInt64
|
||||
if err := row.Scan(&d.ID, &d.Name, &d.EndpointID, &gid, &d.CreatedAtMs); err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
if gid.Valid {
|
||||
v := gid.Int64
|
||||
d.GroupID = &v
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func isUnique(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed")
|
||||
}
|
||||
|
||||
func nowMS() int64 {
|
||||
return time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
func (s *Store) PlaintextSecretCount(ctx context.Context, secret string) (int, error) {
|
||||
if secret == "" {
|
||||
return 0, fmt.Errorf("empty secret")
|
||||
}
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM users WHERE username LIKE '%' || ? || '%' OR password_hash LIKE '%' || ? || '%')
|
||||
+ (SELECT COUNT(*) FROM endpoint_secrets WHERE endpoint_id LIKE '%' || ? || '%' OR password_hash LIKE '%' || ? || '%')
|
||||
+ (SELECT COUNT(*) FROM command_logs WHERE summary LIKE '%' || ? || '%' OR result LIKE '%' || ? || '%')
|
||||
+ (SELECT COUNT(*) FROM devices WHERE name LIKE '%' || ? || '%' OR endpoint_id LIKE '%' || ? || '%')
|
||||
`, secret, secret, secret, secret, secret, secret, secret, secret).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func openTest(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
st, err := 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)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func TestDeleteGroupUngroupsDevices(t *testing.T) {
|
||||
st := openTest(t)
|
||||
ctx := context.Background()
|
||||
user, err := st.Register(ctx, "alice", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if user.Role != "admin" {
|
||||
t.Fatalf("first user role %s", user.Role)
|
||||
}
|
||||
second, err := st.Register(ctx, "bob", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second.Role != "user" {
|
||||
t.Fatalf("second user role %s", second.Role)
|
||||
}
|
||||
group, err := st.CreateGroup(ctx, user.ID, "家里")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.AddDevice(ctx, user.ID, "客厅", "e_a", "secret-hash", &group.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.AddDevice(ctx, user.ID, "卧室", "e_b", "", &group.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside, err := st.CreateGroup(ctx, user.ID, "公司")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.AddDevice(ctx, user.ID, "工位", "e_c", "", &outside.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.DeleteGroup(ctx, user.ID, group.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
devices, err := st.ListDevices(ctx, user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(devices) != 3 {
|
||||
t.Fatalf("devices=%d", len(devices))
|
||||
}
|
||||
for _, d := range devices {
|
||||
if d.EndpointID == "e_c" {
|
||||
if d.GroupID == nil || *d.GroupID != outside.ID {
|
||||
t.Fatalf("outside device group changed: %+v", d.GroupID)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if d.GroupID != nil {
|
||||
t.Fatalf("%s still grouped", d.Name)
|
||||
}
|
||||
}
|
||||
groups, err := st.ListGroups(ctx, user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(groups) != 1 || groups[0].Name != "公司" {
|
||||
t.Fatalf("groups=%+v", groups)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastEnabledAdmin(t *testing.T) {
|
||||
st := openTest(t)
|
||||
ctx := context.Background()
|
||||
alice, err := st.Register(ctx, "alice", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bob, err := st.Register(ctx, "bob", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.db.ExecContext(ctx, `UPDATE users SET role = 'admin' WHERE id = ?`, bob.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.SetEnabled(ctx, alice.ID, alice.ID, false); err != ErrForbidden {
|
||||
t.Fatalf("self disable: %v", err)
|
||||
}
|
||||
if _, err := st.SetEnabled(ctx, alice.ID, bob.ID, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.SetEnabled(ctx, alice.ID, alice.ID, false); err != ErrForbidden {
|
||||
t.Fatalf("last admin self: %v", err)
|
||||
}
|
||||
if _, err := st.db.ExecContext(ctx, `UPDATE users SET enabled = 0 WHERE id = ?`, alice.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.db.ExecContext(ctx, `UPDATE users SET enabled = 1 WHERE id = ?`, bob.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.SetEnabled(ctx, alice.ID, bob.ID, false); err != ErrLastAdmin {
|
||||
t.Fatalf("last admin: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build embeddist
|
||||
|
||||
package webui
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed all:dist
|
||||
var Dist embed.FS
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !embeddist
|
||||
|
||||
package webui
|
||||
|
||||
import "embed"
|
||||
|
||||
var Dist embed.FS
|
||||
Reference in New Issue
Block a user