Files
SimpleRemoter/server/go/wsauth/wsauth_test.go
T
yuanyuanxiangandClaude Code 46434b46d0 Feature: add per-device owner bindings to the web console
Web 控制台此前所有 admin 角色用户共享全部设备。新增设备级归属:内置 admin
把设备绑定给一个用户名后,该设备对其他 admin/viewer 不可见不可控,只有
owner 与内置 admin 可见可控。

- 新增 device_acl.json(与 users.json 同目录,YAMA_DEVICE_ACL_FILE 可覆盖),
  原子写、启动加载;文件损坏拒绝启动,避免私人设备变成公共。
- 可见性:内置 admin 全部;未绑定设备仅 admin 角色;绑定设备仅 owner。
  覆盖 get_devices、/api/devices、屏幕墙,以及 connect/term_open/mouse/key/
  clipboard/keyframe/rdp_reset 全部控制通道;device_update 也只推给可见者。
- 只有内置 admin(用户名 admin + role admin)能 bind/unbind;admin 角色保留
  建用户、删设备、审计等既有功能。删设备清绑定。
- 审计日志也按归属过滤:非内置 admin 只能看到公共设备和自己绑定设备的记录
  (device_id / device / devices 三种写法都识别);auditquery 增 DeviceAllowed
  钩子,ACL 提供 Owner 快照,避免扫描时逐条加锁。
- 删用户会解绑其设备;但账号名下有绑定设备时只有内置 admin 能删,其他 admin
  删除会把设备释放到公共池,属于越权。解绑在删除前完成,解绑失败中止删除;
  删除失败时回滚绑定。
- 绑定/解绑后立即重新校验在线会话:失去权限的屏幕/终端会话被断开。
- 本地用户名禁止 '@'(保留给 SSO 邮箱);本地密码登录拒绝 '@' 用户名,
  SSO 拒绝名为 admin 的身份,避免绕过超级管理员判定。
- 前端:superadmin 卡片显示 owner、绑定按钮和弹窗(本地用户 datalist +
  SSO 邮箱自由输入);deviceAcl 能力位由服务端挑战下发,C++ 端无此位不显示;
  设备 ID 经 jsAttr 转义后再进 onclick,修掉存储型 XSS。

验证:go build/test/vet 全绿;新增 ACL 持久化、可见性矩阵、控制通道拒绝、
绑定/解绑会话重校验、device_update 不泄露、分组过滤、删用户解绑与越权拒绝、
审计按归属过滤等测试;本地起 Go 服务 + WebSocket 探针验证 challenge、绑定、
非 superadmin 拒绝、解绑。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 11:17:51 +01:00

246 lines
6.8 KiB
Go

package wsauth
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
)
func TestSHA256Vector(t *testing.T) {
// Known vector — keeps us honest against accidental algorithm changes.
got := ComputeSHA256("abc")
want := "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
if got != want {
t.Fatalf("SHA256(abc): got %s want %s", got, want)
}
}
// adminLoginResponse helps tests compute the right login response for an
// admin account that now uses a real per-instance salt.
func adminLoginResponse(t *testing.T, a *Authenticator, username, password, nonce string) string {
t.Helper()
salt, ok := a.GetSalt(username)
if !ok {
t.Fatalf("admin %s not registered", username)
}
return ComputeSHA256(HashPassword(password, salt) + nonce)
}
func TestLoginRoundTripAdmin(t *testing.T) {
a := New()
a.AddAdminFromPlainPassword("admin", "hunter2")
salt, ok := a.GetSalt("admin")
if !ok {
t.Fatal("admin should be found")
}
if len(salt) != 2*saltBytes {
t.Fatalf("admin salt should be a real 16-hex value, got %q (len=%d)", salt, len(salt))
}
nonce := "abc123"
response := adminLoginResponse(t, a, "admin", "hunter2", nonce)
token, role, err := a.VerifyLogin("admin", response, nonce)
if err != nil {
t.Fatalf("VerifyLogin: %v", err)
}
if role != "admin" {
t.Fatalf("role: got %q want admin", role)
}
if len(token) != 2*tokenBytes {
t.Fatalf("token length: got %d want %d", len(token), 2*tokenBytes)
}
sess, err := a.ValidateToken(token)
if err != nil {
t.Fatalf("ValidateToken: %v", err)
}
if sess.Username != "admin" || sess.Role != "admin" {
t.Fatalf("session: %+v", sess)
}
}
func TestLoginRoundTripViewerWithSalt(t *testing.T) {
a := New()
salt, _ := NewSalt()
a.AddUser(User{
Username: "alice",
PasswordHash: HashPassword("p@ss", salt),
Salt: salt,
Role: "viewer",
})
gotSalt, ok := a.GetSalt("alice")
if !ok || gotSalt != salt {
t.Fatalf("salt: ok=%v got=%q want=%q", ok, gotSalt, salt)
}
nonce, _ := NewNonce()
response := ComputeSHA256(HashPassword("p@ss", salt) + nonce)
_, role, err := a.VerifyLogin("alice", response, nonce)
if err != nil || role != "viewer" {
t.Fatalf("VerifyLogin: role=%q err=%v", role, err)
}
}
// TestGetSaltUnknownUserShape verifies the salt-probe mitigation: an
// unknown user must get back a value that's shape-identical to a real
// salt, so an attacker can't tell from /get_salt alone whether a
// username exists.
func TestGetSaltUnknownUserShape(t *testing.T) {
a := New()
a.AddAdminFromPlainPassword("admin", "pw")
fake, ok := a.GetSalt("nobody")
if ok {
t.Fatal("ok should be false for unknown user")
}
if len(fake) != 2*saltBytes {
t.Fatalf("fake salt should be %d hex chars; got %q (len=%d)", 2*saltBytes, fake, len(fake))
}
// Determinism: repeated probes for the same username get the same fake.
fake2, _ := a.GetSalt("nobody")
if fake != fake2 {
t.Fatalf("fake salt should be deterministic for repeated probes; got %q vs %q", fake, fake2)
}
// Different usernames get different fake salts.
other, _ := a.GetSalt("ghost")
if fake == other {
t.Fatalf("fake salts should differ across usernames; both = %q", fake)
}
}
func TestLoginRejectsWrongResponse(t *testing.T) {
a := New()
a.AddAdminFromPlainPassword("admin", "x")
_, _, err := a.VerifyLogin("admin", "deadbeef", "nonce")
if err == nil {
t.Fatal("expected error for bad response")
}
_, _, err = a.VerifyLogin("ghost", "anything", "anything")
if err == nil {
t.Fatal("expected error for unknown user")
}
}
func TestTokenExpiry(t *testing.T) {
a := New()
a.SetTokenExpire(50 * time.Millisecond)
a.AddAdminFromPlainPassword("admin", "x")
nonce, _ := NewNonce()
response := adminLoginResponse(t, a, "admin", "x", nonce)
token, _, err := a.VerifyLogin("admin", response, nonce)
if err != nil {
t.Fatal(err)
}
if _, err := a.ValidateToken(token); err != nil {
t.Fatalf("fresh token should validate: %v", err)
}
time.Sleep(80 * time.Millisecond)
if _, err := a.ValidateToken(token); err == nil {
t.Fatal("expired token should not validate")
}
}
func TestRevoke(t *testing.T) {
a := New()
a.AddAdminFromPlainPassword("admin", "x")
nonce, _ := NewNonce()
response := adminLoginResponse(t, a, "admin", "x", nonce)
token, _, _ := a.VerifyLogin("admin", response, nonce)
a.RevokeToken(token)
if _, err := a.ValidateToken(token); err == nil {
t.Fatal("revoked token should not validate")
}
}
func TestRateLimiterAllowsBurstThenBlocks(t *testing.T) {
r := NewRateLimiter(3, time.Minute)
for i := 0; i < 3; i++ {
if !r.Allow("ip-a") {
t.Fatalf("attempt %d should be allowed", i+1)
}
}
if r.Allow("ip-a") {
t.Fatal("4th attempt should be denied")
}
// Different key has independent budget.
if !r.Allow("ip-b") {
t.Fatal("different key should still be allowed")
}
}
func TestRateLimiterReset(t *testing.T) {
r := NewRateLimiter(2, time.Minute)
r.Allow("k")
r.Allow("k")
if r.Allow("k") {
t.Fatal("3rd should be denied")
}
r.Reset("k")
if !r.Allow("k") {
t.Fatal("after Reset, should be allowed again")
}
}
func TestRateLimiterDisabledWhenZeroLimit(t *testing.T) {
r := NewRateLimiter(0, time.Minute)
for i := 0; i < 100; i++ {
if !r.Allow("k") {
t.Fatalf("limit=0 should never deny, denied at i=%d", i)
}
}
}
func TestRateLimiterNilSafe(t *testing.T) {
var r *RateLimiter
if !r.Allow("anything") {
t.Fatal("nil limiter should allow")
}
r.Reset("anything")
r.Sweep()
}
// TestCreateUserRejectsAtSign keeps the local and SSO namespaces disjoint:
// '@' is reserved for portal identities, so a locally-created account can
// never inherit an SSO user's device bindings.
func TestCreateUserRejectsAtSign(t *testing.T) {
a := New()
if err := a.CreateUser("user@corp.com", "pw", "admin", nil); err == nil {
t.Fatal("CreateUser accepted an '@' username")
}
if err := a.CreateUser("alice", "pw", "admin", nil); err != nil {
t.Fatalf("CreateUser(alice): %v", err)
}
}
// TestUsersFileLoadsLegacyAtSignRecord: the loader keeps legacy '@' records
// (dropping them silently would orphan their device bindings). The web login
// handler is what rejects password logins for SSO-shaped usernames.
func TestUsersFileLoadsLegacyAtSignRecord(t *testing.T) {
path := filepath.Join(t.TempDir(), "users.json")
data, err := json.Marshal(usersFile{Users: []usersFileEntry{
{Username: "legacy@corp.com", PasswordHash: "hash", Salt: "salt", Role: "admin"},
{Username: "alice", PasswordHash: "hash", Salt: "salt", Role: "admin"},
}})
if err != nil {
t.Fatalf("marshal: %v", err)
}
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatalf("WriteFile: %v", err)
}
a := New()
if err := a.SetUsersFile(path); err != nil {
t.Fatalf("SetUsersFile: %v", err)
}
if _, ok := a.GetSalt("legacy@corp.com"); !ok {
t.Fatal("loader dropped a legacy '@' record")
}
if _, ok := a.GetSalt("alice"); !ok {
t.Fatal("loader dropped a valid local user")
}
}