Compare commits
8 Commits
feature/co
...
feature/us
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6244cf039d | ||
|
|
3e6dc108db | ||
|
|
67460ea6b2 | ||
|
|
b7999b201f | ||
|
|
d85956ca1a | ||
|
|
58f958c8d3 | ||
|
|
0fef7929ad | ||
|
|
c4652728b8 |
2
Makefile
2
Makefile
@@ -32,7 +32,7 @@ fmt-check:
|
||||
@test -z "$$(gofmt -l .)" || (echo "Files not formatted:" && gofmt -l . && exit 1)
|
||||
|
||||
test: ensure-web-dist
|
||||
go test -timeout 30s -v -race -cover ./...
|
||||
go test -timeout 30s -race -cover ./... || go test -timeout 30s -race -v ./...
|
||||
|
||||
# check runs all validation without making changes
|
||||
# Used by CI and Docker build — fails if anything is wrong
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -29,19 +28,16 @@ var errHTTP = errors.New("HTTP error")
|
||||
// Client wraps HTTP calls to the neoirc server API.
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
Token string
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
// NewClient creates a new API client with a cookie jar
|
||||
// for automatic auth cookie management.
|
||||
// NewClient creates a new API client.
|
||||
func NewClient(baseURL string) *Client {
|
||||
jar, _ := cookiejar.New(nil)
|
||||
|
||||
return &Client{
|
||||
return &Client{ //nolint:exhaustruct // Token set after CreateSession
|
||||
BaseURL: baseURL,
|
||||
HTTPClient: &http.Client{ //nolint:exhaustruct // defaults fine
|
||||
Timeout: httpTimeout,
|
||||
Jar: jar,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -83,6 +79,8 @@ func (client *Client) CreateSession(
|
||||
return nil, fmt.Errorf("decode session: %w", err)
|
||||
}
|
||||
|
||||
client.Token = resp.Token
|
||||
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
@@ -123,7 +121,6 @@ func (client *Client) PollMessages(
|
||||
Timeout: time.Duration(
|
||||
timeout+pollExtraTime,
|
||||
) * time.Second,
|
||||
Jar: client.HTTPClient.Jar,
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
@@ -148,6 +145,10 @@ func (client *Client) PollMessages(
|
||||
return nil, fmt.Errorf("new request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set(
|
||||
"Authorization", "Bearer "+client.Token,
|
||||
)
|
||||
|
||||
resp, err := pollClient.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("poll request: %w", err)
|
||||
@@ -303,6 +304,12 @@ func (client *Client) do(
|
||||
"Content-Type", "application/json",
|
||||
)
|
||||
|
||||
if client.Token != "" {
|
||||
request.Header.Set(
|
||||
"Authorization", "Bearer "+client.Token,
|
||||
)
|
||||
}
|
||||
|
||||
resp, err := client.HTTPClient.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http: %w", err)
|
||||
|
||||
@@ -10,8 +10,9 @@ type SessionRequest struct {
|
||||
|
||||
// SessionResponse is the response from session creation.
|
||||
type SessionResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Nick string `json:"nick"`
|
||||
ID int64 `json:"id"`
|
||||
Nick string `json:"nick"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// StateResponse is the response from GET /api/v1/state.
|
||||
|
||||
@@ -46,6 +46,8 @@ type Config struct {
|
||||
FederationKey string
|
||||
SessionIdleTimeout string
|
||||
HashcashBits int
|
||||
OperName string
|
||||
OperPassword string
|
||||
params *Params
|
||||
log *slog.Logger
|
||||
}
|
||||
@@ -78,6 +80,8 @@ func New(
|
||||
viper.SetDefault("FEDERATION_KEY", "")
|
||||
viper.SetDefault("SESSION_IDLE_TIMEOUT", "720h")
|
||||
viper.SetDefault("NEOIRC_HASHCASH_BITS", "20")
|
||||
viper.SetDefault("NEOIRC_OPER_NAME", "")
|
||||
viper.SetDefault("NEOIRC_OPER_PASSWORD", "")
|
||||
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
@@ -104,6 +108,8 @@ func New(
|
||||
FederationKey: viper.GetString("FEDERATION_KEY"),
|
||||
SessionIdleTimeout: viper.GetString("SESSION_IDLE_TIMEOUT"),
|
||||
HashcashBits: viper.GetInt("NEOIRC_HASHCASH_BITS"),
|
||||
OperName: viper.GetString("NEOIRC_OPER_NAME"),
|
||||
OperPassword: viper.GetString("NEOIRC_OPER_PASSWORD"),
|
||||
log: log,
|
||||
params: ¶ms,
|
||||
}
|
||||
|
||||
@@ -10,41 +10,104 @@ import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const bcryptCost = bcrypt.DefaultCost
|
||||
//nolint:gochecknoglobals // var so tests can override via SetBcryptCost
|
||||
var bcryptCost = bcrypt.DefaultCost
|
||||
|
||||
// SetBcryptCost overrides the bcrypt cost.
|
||||
// Use bcrypt.MinCost in tests to avoid slow hashing.
|
||||
func SetBcryptCost(cost int) { bcryptCost = cost }
|
||||
|
||||
var errNoPassword = errors.New(
|
||||
"account has no password set",
|
||||
)
|
||||
|
||||
// SetPassword sets a bcrypt-hashed password on a session,
|
||||
// enabling multi-client login via POST /api/v1/login.
|
||||
func (database *Database) SetPassword(
|
||||
// RegisterUser creates a session with a hashed password
|
||||
// and returns session ID, client ID, and token.
|
||||
func (database *Database) RegisterUser(
|
||||
ctx context.Context,
|
||||
sessionID int64,
|
||||
password string,
|
||||
) error {
|
||||
nick, password, username, hostname, remoteIP string,
|
||||
) (int64, int64, string, error) {
|
||||
if username == "" {
|
||||
username = nick
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword(
|
||||
[]byte(password), bcryptCost,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash password: %w", err)
|
||||
return 0, 0, "", fmt.Errorf(
|
||||
"hash password: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
_, err = database.conn.ExecContext(ctx,
|
||||
"UPDATE sessions SET password_hash = ? WHERE id = ?",
|
||||
string(hash), sessionID)
|
||||
sessionUUID := uuid.New().String()
|
||||
clientUUID := uuid.New().String()
|
||||
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return fmt.Errorf("set password: %w", err)
|
||||
return 0, 0, "", err
|
||||
}
|
||||
|
||||
return nil
|
||||
now := time.Now()
|
||||
|
||||
transaction, err := database.conn.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, 0, "", fmt.Errorf(
|
||||
"begin tx: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
res, err := transaction.ExecContext(ctx,
|
||||
`INSERT INTO sessions
|
||||
(uuid, nick, username, hostname, ip,
|
||||
password_hash, created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
sessionUUID, nick, username, hostname,
|
||||
remoteIP, string(hash), now, now)
|
||||
if err != nil {
|
||||
_ = transaction.Rollback()
|
||||
|
||||
return 0, 0, "", fmt.Errorf(
|
||||
"create session: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
sessionID, _ := res.LastInsertId()
|
||||
|
||||
tokenHash := hashToken(token)
|
||||
|
||||
clientRes, err := transaction.ExecContext(ctx,
|
||||
`INSERT INTO clients
|
||||
(uuid, session_id, token, ip, hostname,
|
||||
created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
clientUUID, sessionID, tokenHash,
|
||||
remoteIP, hostname, now, now)
|
||||
if err != nil {
|
||||
_ = transaction.Rollback()
|
||||
|
||||
return 0, 0, "", fmt.Errorf(
|
||||
"create client: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
clientID, _ := clientRes.LastInsertId()
|
||||
|
||||
err = transaction.Commit()
|
||||
if err != nil {
|
||||
return 0, 0, "", fmt.Errorf(
|
||||
"commit registration: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
return sessionID, clientID, token, nil
|
||||
}
|
||||
|
||||
// LoginUser verifies a nick/password and creates a new
|
||||
// client token.
|
||||
func (database *Database) LoginUser(
|
||||
ctx context.Context,
|
||||
nick, password string,
|
||||
nick, password, remoteIP, hostname string,
|
||||
) (int64, int64, string, error) {
|
||||
var (
|
||||
sessionID int64
|
||||
@@ -91,10 +154,11 @@ func (database *Database) LoginUser(
|
||||
|
||||
res, err := database.conn.ExecContext(ctx,
|
||||
`INSERT INTO clients
|
||||
(uuid, session_id, token,
|
||||
(uuid, session_id, token, ip, hostname,
|
||||
created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
clientUUID, sessionID, tokenHash, now, now)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
clientUUID, sessionID, tokenHash,
|
||||
remoteIP, hostname, now, now)
|
||||
if err != nil {
|
||||
return 0, 0, "", fmt.Errorf(
|
||||
"create login client: %w", err,
|
||||
|
||||
@@ -6,65 +6,126 @@ import (
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func TestSetPassword(t *testing.T) {
|
||||
func TestRegisterUser(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, _, _, err :=
|
||||
database.CreateSession(ctx, "passuser")
|
||||
sessionID, clientID, token, err :=
|
||||
database.RegisterUser(ctx, "reguser", "password123", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.SetPassword(
|
||||
ctx, sessionID, "password123",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Verify we can now log in with the password.
|
||||
loginSID, loginCID, loginToken, err :=
|
||||
database.LoginUser(ctx, "passuser", "password123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if loginSID == 0 || loginCID == 0 || loginToken == "" {
|
||||
if sessionID == 0 || clientID == 0 || token == "" {
|
||||
t.Fatal("expected valid ids and token")
|
||||
}
|
||||
|
||||
// Verify session works via token lookup.
|
||||
sid, cid, nick, err :=
|
||||
database.GetSessionByToken(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if sid != sessionID || cid != clientID {
|
||||
t.Fatal("session/client id mismatch")
|
||||
}
|
||||
|
||||
if nick != "reguser" {
|
||||
t.Fatalf("expected reguser, got %s", nick)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetPasswordThenWrongLogin(t *testing.T) {
|
||||
func TestRegisterUserWithUserHost(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, _, _, err :=
|
||||
database.CreateSession(ctx, "wrongpw")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.SetPassword(
|
||||
ctx, sessionID, "correctpass",
|
||||
sessionID, _, _, err := database.RegisterUser(
|
||||
ctx, "reguhost", "password123",
|
||||
"myident", "example.org", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
loginSID, loginCID, loginToken, loginErr :=
|
||||
database.LoginUser(ctx, "wrongpw", "wrongpass12")
|
||||
if loginErr == nil {
|
||||
t.Fatal("expected error for wrong password")
|
||||
info, err := database.GetSessionHostInfo(
|
||||
ctx, sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_ = loginSID
|
||||
_ = loginCID
|
||||
_ = loginToken
|
||||
if info.Username != "myident" {
|
||||
t.Fatalf(
|
||||
"expected myident, got %s", info.Username,
|
||||
)
|
||||
}
|
||||
|
||||
if info.Hostname != "example.org" {
|
||||
t.Fatalf(
|
||||
"expected example.org, got %s",
|
||||
info.Hostname,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUserDefaultUsername(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, _, _, err := database.RegisterUser(
|
||||
ctx, "regdefault", "password123", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
info, err := database.GetSessionHostInfo(
|
||||
ctx, sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if info.Username != "regdefault" {
|
||||
t.Fatalf(
|
||||
"expected regdefault, got %s",
|
||||
info.Username,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUserDuplicateNick(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
regSID, regCID, regToken, err :=
|
||||
database.RegisterUser(ctx, "dupnick", "password123", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_ = regSID
|
||||
_ = regCID
|
||||
_ = regToken
|
||||
|
||||
dupSID, dupCID, dupToken, dupErr :=
|
||||
database.RegisterUser(ctx, "dupnick", "other12345", "", "", "")
|
||||
if dupErr == nil {
|
||||
t.Fatal("expected error for duplicate nick")
|
||||
}
|
||||
|
||||
_ = dupSID
|
||||
_ = dupCID
|
||||
_ = dupToken
|
||||
}
|
||||
|
||||
func TestLoginUser(t *testing.T) {
|
||||
@@ -73,26 +134,23 @@ func TestLoginUser(t *testing.T) {
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, _, _, err :=
|
||||
database.CreateSession(ctx, "loginuser")
|
||||
regSID, regCID, regToken, err :=
|
||||
database.RegisterUser(ctx, "loginuser", "mypassword", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.SetPassword(
|
||||
ctx, sessionID, "mypassword",
|
||||
)
|
||||
_ = regSID
|
||||
_ = regCID
|
||||
_ = regToken
|
||||
|
||||
sessionID, clientID, token, err :=
|
||||
database.LoginUser(ctx, "loginuser", "mypassword", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
loginSID, loginCID, token, err :=
|
||||
database.LoginUser(ctx, "loginuser", "mypassword")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if loginSID == 0 || loginCID == 0 || token == "" {
|
||||
if sessionID == 0 || clientID == 0 || token == "" {
|
||||
t.Fatal("expected valid ids and token")
|
||||
}
|
||||
|
||||
@@ -108,6 +166,110 @@ func TestLoginUser(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginUserStoresClientIPHostname(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
regSID, regCID, regToken, err := database.RegisterUser(
|
||||
ctx, "loginipuser", "password123",
|
||||
"", "", "10.0.0.1",
|
||||
)
|
||||
|
||||
_ = regSID
|
||||
_ = regCID
|
||||
_ = regToken
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, clientID, _, err := database.LoginUser(
|
||||
ctx, "loginipuser", "password123",
|
||||
"10.0.0.99", "newhost.example.com",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
clientInfo, err := database.GetClientHostInfo(
|
||||
ctx, clientID,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if clientInfo.IP != "10.0.0.99" {
|
||||
t.Fatalf(
|
||||
"expected client IP 10.0.0.99, got %s",
|
||||
clientInfo.IP,
|
||||
)
|
||||
}
|
||||
|
||||
if clientInfo.Hostname != "newhost.example.com" {
|
||||
t.Fatalf(
|
||||
"expected hostname newhost.example.com, got %s",
|
||||
clientInfo.Hostname,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUserStoresSessionIP(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, _, _, err := database.RegisterUser(
|
||||
ctx, "regipuser", "password123",
|
||||
"ident", "host.local", "172.16.0.5",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
info, err := database.GetSessionHostInfo(
|
||||
ctx, sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if info.IP != "172.16.0.5" {
|
||||
t.Fatalf(
|
||||
"expected session IP 172.16.0.5, got %s",
|
||||
info.IP,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginUserWrongPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
regSID, regCID, regToken, err :=
|
||||
database.RegisterUser(ctx, "wrongpw", "correctpass", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_ = regSID
|
||||
_ = regCID
|
||||
_ = regToken
|
||||
|
||||
loginSID, loginCID, loginToken, loginErr :=
|
||||
database.LoginUser(ctx, "wrongpw", "wrongpass12", "", "")
|
||||
if loginErr == nil {
|
||||
t.Fatal("expected error for wrong password")
|
||||
}
|
||||
|
||||
_ = loginSID
|
||||
_ = loginCID
|
||||
_ = loginToken
|
||||
}
|
||||
|
||||
func TestLoginUserNoPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -116,7 +278,7 @@ func TestLoginUserNoPassword(t *testing.T) {
|
||||
|
||||
// Create anonymous session (no password).
|
||||
anonSID, anonCID, anonToken, err :=
|
||||
database.CreateSession(ctx, "anon")
|
||||
database.CreateSession(ctx, "anon", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -126,7 +288,7 @@ func TestLoginUserNoPassword(t *testing.T) {
|
||||
_ = anonToken
|
||||
|
||||
loginSID, loginCID, loginToken, loginErr :=
|
||||
database.LoginUser(ctx, "anon", "anything1")
|
||||
database.LoginUser(ctx, "anon", "anything1", "", "")
|
||||
if loginErr == nil {
|
||||
t.Fatal(
|
||||
"expected error for login on passwordless account",
|
||||
@@ -145,7 +307,7 @@ func TestLoginUserNonexistent(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
loginSID, loginCID, loginToken, err :=
|
||||
database.LoginUser(ctx, "ghost", "password123")
|
||||
database.LoginUser(ctx, "ghost", "password123", "", "")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nonexistent user")
|
||||
}
|
||||
|
||||
14
internal/db/main_test.go
Normal file
14
internal/db/main_test.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package db_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"git.eeqj.de/sneak/neoirc/internal/db"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
db.SetBcryptCost(bcrypt.MinCost)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
@@ -74,14 +74,40 @@ type ChannelInfo struct {
|
||||
type MemberInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
Nick string `json:"nick"`
|
||||
Username string `json:"username"`
|
||||
Hostname string `json:"hostname"`
|
||||
LastSeen time.Time `json:"lastSeen"`
|
||||
}
|
||||
|
||||
// Hostmask returns the IRC hostmask in
|
||||
// nick!user@host format.
|
||||
func (m *MemberInfo) Hostmask() string {
|
||||
return FormatHostmask(m.Nick, m.Username, m.Hostname)
|
||||
}
|
||||
|
||||
// FormatHostmask formats a nick, username, and hostname
|
||||
// into a standard IRC hostmask string (nick!user@host).
|
||||
func FormatHostmask(nick, username, hostname string) string {
|
||||
if username == "" {
|
||||
username = nick
|
||||
}
|
||||
|
||||
if hostname == "" {
|
||||
hostname = "*"
|
||||
}
|
||||
|
||||
return nick + "!" + username + "@" + hostname
|
||||
}
|
||||
|
||||
// CreateSession registers a new session and its first client.
|
||||
func (database *Database) CreateSession(
|
||||
ctx context.Context,
|
||||
nick string,
|
||||
nick, username, hostname, remoteIP string,
|
||||
) (int64, int64, string, error) {
|
||||
if username == "" {
|
||||
username = nick
|
||||
}
|
||||
|
||||
sessionUUID := uuid.New().String()
|
||||
clientUUID := uuid.New().String()
|
||||
|
||||
@@ -101,9 +127,11 @@ func (database *Database) CreateSession(
|
||||
|
||||
res, err := transaction.ExecContext(ctx,
|
||||
`INSERT INTO sessions
|
||||
(uuid, nick, created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
sessionUUID, nick, now, now)
|
||||
(uuid, nick, username, hostname, ip,
|
||||
created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
sessionUUID, nick, username, hostname,
|
||||
remoteIP, now, now)
|
||||
if err != nil {
|
||||
_ = transaction.Rollback()
|
||||
|
||||
@@ -118,10 +146,11 @@ func (database *Database) CreateSession(
|
||||
|
||||
clientRes, err := transaction.ExecContext(ctx,
|
||||
`INSERT INTO clients
|
||||
(uuid, session_id, token,
|
||||
(uuid, session_id, token, ip, hostname,
|
||||
created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
clientUUID, sessionID, tokenHash, now, now)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
clientUUID, sessionID, tokenHash,
|
||||
remoteIP, hostname, now, now)
|
||||
if err != nil {
|
||||
_ = transaction.Rollback()
|
||||
|
||||
@@ -209,6 +238,135 @@ func (database *Database) GetSessionByNick(
|
||||
return sessionID, nil
|
||||
}
|
||||
|
||||
// SessionHostInfo holds the username, hostname, and IP
|
||||
// for a session.
|
||||
type SessionHostInfo struct {
|
||||
Username string
|
||||
Hostname string
|
||||
IP string
|
||||
}
|
||||
|
||||
// GetSessionHostInfo returns the username, hostname,
|
||||
// and IP for a session.
|
||||
func (database *Database) GetSessionHostInfo(
|
||||
ctx context.Context,
|
||||
sessionID int64,
|
||||
) (*SessionHostInfo, error) {
|
||||
var info SessionHostInfo
|
||||
|
||||
err := database.conn.QueryRowContext(
|
||||
ctx,
|
||||
`SELECT username, hostname, ip
|
||||
FROM sessions WHERE id = ?`,
|
||||
sessionID,
|
||||
).Scan(&info.Username, &info.Hostname, &info.IP)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"get session host info: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
// ClientHostInfo holds the IP and hostname for a client.
|
||||
type ClientHostInfo struct {
|
||||
IP string
|
||||
Hostname string
|
||||
}
|
||||
|
||||
// GetClientHostInfo returns the IP and hostname for a
|
||||
// client.
|
||||
func (database *Database) GetClientHostInfo(
|
||||
ctx context.Context,
|
||||
clientID int64,
|
||||
) (*ClientHostInfo, error) {
|
||||
var info ClientHostInfo
|
||||
|
||||
err := database.conn.QueryRowContext(
|
||||
ctx,
|
||||
`SELECT ip, hostname
|
||||
FROM clients WHERE id = ?`,
|
||||
clientID,
|
||||
).Scan(&info.IP, &info.Hostname)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"get client host info: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
// SetSessionOper sets the is_oper flag on a session.
|
||||
func (database *Database) SetSessionOper(
|
||||
ctx context.Context,
|
||||
sessionID int64,
|
||||
isOper bool,
|
||||
) error {
|
||||
val := 0
|
||||
if isOper {
|
||||
val = 1
|
||||
}
|
||||
|
||||
_, err := database.conn.ExecContext(
|
||||
ctx,
|
||||
`UPDATE sessions SET is_oper = ? WHERE id = ?`,
|
||||
val, sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set session oper: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsSessionOper returns whether the session has oper
|
||||
// status.
|
||||
func (database *Database) IsSessionOper(
|
||||
ctx context.Context,
|
||||
sessionID int64,
|
||||
) (bool, error) {
|
||||
var isOper int
|
||||
|
||||
err := database.conn.QueryRowContext(
|
||||
ctx,
|
||||
`SELECT is_oper FROM sessions WHERE id = ?`,
|
||||
sessionID,
|
||||
).Scan(&isOper)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf(
|
||||
"check session oper: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
return isOper != 0, nil
|
||||
}
|
||||
|
||||
// GetLatestClientForSession returns the IP and hostname
|
||||
// of the most recently created client for a session.
|
||||
func (database *Database) GetLatestClientForSession(
|
||||
ctx context.Context,
|
||||
sessionID int64,
|
||||
) (*ClientHostInfo, error) {
|
||||
var info ClientHostInfo
|
||||
|
||||
err := database.conn.QueryRowContext(
|
||||
ctx,
|
||||
`SELECT ip, hostname FROM clients
|
||||
WHERE session_id = ?
|
||||
ORDER BY created_at DESC LIMIT 1`,
|
||||
sessionID,
|
||||
).Scan(&info.IP, &info.Hostname)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"get latest client for session: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
// GetChannelByName returns the channel ID for a name.
|
||||
func (database *Database) GetChannelByName(
|
||||
ctx context.Context,
|
||||
@@ -388,7 +546,8 @@ func (database *Database) ChannelMembers(
|
||||
channelID int64,
|
||||
) ([]MemberInfo, error) {
|
||||
rows, err := database.conn.QueryContext(ctx,
|
||||
`SELECT s.id, s.nick, s.last_seen
|
||||
`SELECT s.id, s.nick, s.username,
|
||||
s.hostname, s.last_seen
|
||||
FROM sessions s
|
||||
INNER JOIN channel_members cm
|
||||
ON cm.session_id = s.id
|
||||
@@ -408,7 +567,9 @@ func (database *Database) ChannelMembers(
|
||||
var member MemberInfo
|
||||
|
||||
err = rows.Scan(
|
||||
&member.ID, &member.Nick, &member.LastSeen,
|
||||
&member.ID, &member.Nick,
|
||||
&member.Username, &member.Hostname,
|
||||
&member.LastSeen,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
@@ -859,6 +1020,26 @@ func (database *Database) GetUserCount(
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// GetOperCount returns the number of sessions with oper
|
||||
// status.
|
||||
func (database *Database) GetOperCount(
|
||||
ctx context.Context,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
|
||||
err := database.conn.QueryRowContext(
|
||||
ctx,
|
||||
"SELECT COUNT(*) FROM sessions WHERE is_oper = 1",
|
||||
).Scan(&count)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(
|
||||
"get oper count: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// ClientCountForSession returns the number of clients
|
||||
// belonging to a session.
|
||||
func (database *Database) ClientCountForSession(
|
||||
|
||||
@@ -34,7 +34,7 @@ func TestCreateSession(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, _, token, err := database.CreateSession(
|
||||
ctx, "alice",
|
||||
ctx, "alice", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -45,7 +45,7 @@ func TestCreateSession(t *testing.T) {
|
||||
}
|
||||
|
||||
_, _, dupToken, dupErr := database.CreateSession(
|
||||
ctx, "alice",
|
||||
ctx, "alice", "", "", "",
|
||||
)
|
||||
if dupErr == nil {
|
||||
t.Fatal("expected error for duplicate nick")
|
||||
@@ -54,13 +54,249 @@ func TestCreateSession(t *testing.T) {
|
||||
_ = dupToken
|
||||
}
|
||||
|
||||
// assertSessionHostInfo creates a session and verifies
|
||||
// the stored username and hostname match expectations.
|
||||
func assertSessionHostInfo(
|
||||
t *testing.T,
|
||||
database *db.Database,
|
||||
nick, inputUser, inputHost,
|
||||
expectUser, expectHost string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
sessionID, _, _, err := database.CreateSession(
|
||||
t.Context(), nick, inputUser, inputHost, "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
info, err := database.GetSessionHostInfo(
|
||||
t.Context(), sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if info.Username != expectUser {
|
||||
t.Fatalf(
|
||||
"expected username %s, got %s",
|
||||
expectUser, info.Username,
|
||||
)
|
||||
}
|
||||
|
||||
if info.Hostname != expectHost {
|
||||
t.Fatalf(
|
||||
"expected hostname %s, got %s",
|
||||
expectHost, info.Hostname,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSessionWithUserHost(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
|
||||
assertSessionHostInfo(
|
||||
t, database,
|
||||
"hostuser", "myident", "example.com",
|
||||
"myident", "example.com",
|
||||
)
|
||||
}
|
||||
|
||||
func TestCreateSessionDefaultUsername(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
|
||||
// Empty username defaults to nick.
|
||||
assertSessionHostInfo(
|
||||
t, database,
|
||||
"defaultu", "", "host.local",
|
||||
"defaultu", "host.local",
|
||||
)
|
||||
}
|
||||
|
||||
func TestCreateSessionStoresIP(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, clientID, _, err := database.CreateSession(
|
||||
ctx, "ipuser", "ident", "host.example.com",
|
||||
"192.168.1.42",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
info, err := database.GetSessionHostInfo(
|
||||
ctx, sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if info.IP != "192.168.1.42" {
|
||||
t.Fatalf(
|
||||
"expected session IP 192.168.1.42, got %s",
|
||||
info.IP,
|
||||
)
|
||||
}
|
||||
|
||||
clientInfo, err := database.GetClientHostInfo(
|
||||
ctx, clientID,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if clientInfo.IP != "192.168.1.42" {
|
||||
t.Fatalf(
|
||||
"expected client IP 192.168.1.42, got %s",
|
||||
clientInfo.IP,
|
||||
)
|
||||
}
|
||||
|
||||
if clientInfo.Hostname != "host.example.com" {
|
||||
t.Fatalf(
|
||||
"expected client hostname host.example.com, got %s",
|
||||
clientInfo.Hostname,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetClientHostInfoNotFound(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
|
||||
_, err := database.GetClientHostInfo(
|
||||
t.Context(), 99999,
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nonexistent client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetSessionHostInfoNotFound(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
|
||||
_, err := database.GetSessionHostInfo(
|
||||
t.Context(), 99999,
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nonexistent session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatHostmask(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
result := db.FormatHostmask(
|
||||
"nick", "user", "host.com",
|
||||
)
|
||||
if result != "nick!user@host.com" {
|
||||
t.Fatalf(
|
||||
"expected nick!user@host.com, got %s",
|
||||
result,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatHostmaskDefaults(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
result := db.FormatHostmask("nick", "", "")
|
||||
if result != "nick!nick@*" {
|
||||
t.Fatalf(
|
||||
"expected nick!nick@*, got %s",
|
||||
result,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemberInfoHostmask(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
member := &db.MemberInfo{ //nolint:exhaustruct // test only uses hostmask fields
|
||||
Nick: "alice",
|
||||
Username: "aliceident",
|
||||
Hostname: "alice.example.com",
|
||||
}
|
||||
|
||||
hostmask := member.Hostmask()
|
||||
expected := "alice!aliceident@alice.example.com"
|
||||
|
||||
if hostmask != expected {
|
||||
t.Fatalf(
|
||||
"expected %s, got %s", expected, hostmask,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelMembersIncludeUserHost(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sid, _, _, err := database.CreateSession(
|
||||
ctx, "memuser", "myuser", "myhost.net", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
chID, err := database.GetOrCreateChannel(
|
||||
ctx, "#hostchan",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = database.JoinChannel(ctx, chID, sid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
members, err := database.ChannelMembers(ctx, chID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(members) != 1 {
|
||||
t.Fatalf(
|
||||
"expected 1 member, got %d", len(members),
|
||||
)
|
||||
}
|
||||
|
||||
if members[0].Username != "myuser" {
|
||||
t.Fatalf(
|
||||
"expected username myuser, got %s",
|
||||
members[0].Username,
|
||||
)
|
||||
}
|
||||
|
||||
if members[0].Hostname != "myhost.net" {
|
||||
t.Fatalf(
|
||||
"expected hostname myhost.net, got %s",
|
||||
members[0].Hostname,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetSessionByToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
_, _, token, err := database.CreateSession(ctx, "bob")
|
||||
_, _, token, err := database.CreateSession(ctx, "bob", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -93,7 +329,7 @@ func TestGetSessionByNick(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
charlieID, charlieClientID, charlieToken, err :=
|
||||
database.CreateSession(ctx, "charlie")
|
||||
database.CreateSession(ctx, "charlie", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -150,7 +386,7 @@ func TestJoinAndPart(t *testing.T) {
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sid, _, _, err := database.CreateSession(ctx, "user1")
|
||||
sid, _, _, err := database.CreateSession(ctx, "user1", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -199,7 +435,7 @@ func TestDeleteChannelIfEmpty(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
sid, _, _, err := database.CreateSession(ctx, "temp")
|
||||
sid, _, _, err := database.CreateSession(ctx, "temp", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -234,7 +470,7 @@ func createSessionWithChannels(
|
||||
|
||||
ctx := t.Context()
|
||||
|
||||
sid, _, _, err := database.CreateSession(ctx, nick)
|
||||
sid, _, _, err := database.CreateSession(ctx, nick, "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -317,7 +553,7 @@ func TestChangeNick(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
sid, _, token, err := database.CreateSession(
|
||||
ctx, "old",
|
||||
ctx, "old", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -401,7 +637,7 @@ func TestPollMessages(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
sid, _, token, err := database.CreateSession(
|
||||
ctx, "poller",
|
||||
ctx, "poller", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -508,7 +744,7 @@ func TestDeleteSession(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
sid, _, _, err := database.CreateSession(
|
||||
ctx, "deleteme",
|
||||
ctx, "deleteme", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -548,12 +784,12 @@ func TestChannelMembers(t *testing.T) {
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sid1, _, _, err := database.CreateSession(ctx, "m1")
|
||||
sid1, _, _, err := database.CreateSession(ctx, "m1", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
sid2, _, _, err := database.CreateSession(ctx, "m2")
|
||||
sid2, _, _, err := database.CreateSession(ctx, "m2", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -611,7 +847,7 @@ func TestEnqueueToClient(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
_, _, token, err := database.CreateSession(
|
||||
ctx, "enqclient",
|
||||
ctx, "enqclient", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -651,3 +887,133 @@ func TestEnqueueToClient(t *testing.T) {
|
||||
t.Fatalf("expected 1, got %d", len(msgs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAndCheckSessionOper(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, _, _, err := database.CreateSession(
|
||||
ctx, "opernick", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Initially not oper.
|
||||
isOper, err := database.IsSessionOper(ctx, sessionID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if isOper {
|
||||
t.Fatal("expected session not to be oper")
|
||||
}
|
||||
|
||||
// Set oper.
|
||||
err = database.SetSessionOper(ctx, sessionID, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
isOper, err = database.IsSessionOper(ctx, sessionID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !isOper {
|
||||
t.Fatal("expected session to be oper")
|
||||
}
|
||||
|
||||
// Unset oper.
|
||||
err = database.SetSessionOper(ctx, sessionID, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
isOper, err = database.IsSessionOper(ctx, sessionID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if isOper {
|
||||
t.Fatal("expected session not to be oper")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLatestClientForSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
sessionID, _, _, err := database.CreateSession(
|
||||
ctx, "clientnick", "", "", "10.0.0.1",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
clientInfo, err := database.GetLatestClientForSession(
|
||||
ctx, sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if clientInfo.IP != "10.0.0.1" {
|
||||
t.Fatalf(
|
||||
"expected IP 10.0.0.1, got %s",
|
||||
clientInfo.IP,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOperCount(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
database := setupTestDB(t)
|
||||
ctx := t.Context()
|
||||
|
||||
// Create two sessions.
|
||||
sid1, _, _, err := database.CreateSession(
|
||||
ctx, "user1", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
sid2, _, _, err := database.CreateSession(
|
||||
ctx, "user2", "", "", "",
|
||||
)
|
||||
_ = sid2
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Initially zero opers.
|
||||
count, err := database.GetOperCount(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if count != 0 {
|
||||
t.Fatalf("expected 0 opers, got %d", count)
|
||||
}
|
||||
|
||||
// Set one as oper.
|
||||
err = database.SetSessionOper(ctx, sid1, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
count, err = database.GetOperCount(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if count != 1 {
|
||||
t.Fatalf("expected 1 oper, got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uuid TEXT NOT NULL UNIQUE,
|
||||
nick TEXT NOT NULL UNIQUE,
|
||||
username TEXT NOT NULL DEFAULT '',
|
||||
hostname TEXT NOT NULL DEFAULT '',
|
||||
ip TEXT NOT NULL DEFAULT '',
|
||||
is_oper INTEGER NOT NULL DEFAULT 0,
|
||||
password_hash TEXT NOT NULL DEFAULT '',
|
||||
signing_key TEXT NOT NULL DEFAULT '',
|
||||
away_message TEXT NOT NULL DEFAULT '',
|
||||
@@ -20,6 +24,8 @@ CREATE TABLE IF NOT EXISTS clients (
|
||||
uuid TEXT NOT NULL UNIQUE,
|
||||
session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
token TEXT NOT NULL UNIQUE,
|
||||
ip TEXT NOT NULL DEFAULT '',
|
||||
hostname TEXT NOT NULL DEFAULT '',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
last_seen DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
@@ -2,9 +2,11 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -30,13 +32,18 @@ var validChannelRe = regexp.MustCompile(
|
||||
`^#[a-zA-Z0-9_\-]{1,63}$`,
|
||||
)
|
||||
|
||||
var validUsernameRe = regexp.MustCompile(
|
||||
`^[a-zA-Z0-9_\-\[\]\\^{}|` + "`" + `]{1,32}$`,
|
||||
)
|
||||
|
||||
const dnsLookupTimeout = 3 * time.Second
|
||||
|
||||
const (
|
||||
maxLongPollTimeout = 30
|
||||
pollMessageLimit = 100
|
||||
defaultMaxBodySize = 4096
|
||||
defaultHistLimit = 50
|
||||
maxHistLimit = 500
|
||||
authCookieName = "neoirc_auth"
|
||||
)
|
||||
|
||||
func (hdlr *Handlers) maxBodySize() int64 {
|
||||
@@ -47,18 +54,72 @@ func (hdlr *Handlers) maxBodySize() int64 {
|
||||
return defaultMaxBodySize
|
||||
}
|
||||
|
||||
// authSession extracts the session from the auth cookie.
|
||||
// clientIP extracts the connecting client's IP address
|
||||
// from the request, checking X-Forwarded-For and
|
||||
// X-Real-IP headers before falling back to RemoteAddr.
|
||||
func clientIP(request *http.Request) string {
|
||||
if forwarded := request.Header.Get("X-Forwarded-For"); forwarded != "" {
|
||||
// X-Forwarded-For can contain a comma-separated list;
|
||||
// the first entry is the original client.
|
||||
parts := strings.SplitN(forwarded, ",", 2) //nolint:mnd
|
||||
ip := strings.TrimSpace(parts[0])
|
||||
|
||||
if ip != "" {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
|
||||
if realIP := request.Header.Get("X-Real-IP"); realIP != "" {
|
||||
return strings.TrimSpace(realIP)
|
||||
}
|
||||
|
||||
host, _, err := net.SplitHostPort(request.RemoteAddr)
|
||||
if err != nil {
|
||||
return request.RemoteAddr
|
||||
}
|
||||
|
||||
return host
|
||||
}
|
||||
|
||||
// resolveHostname performs a reverse DNS lookup on the
|
||||
// given IP address. Returns the first PTR record with the
|
||||
// trailing dot stripped, or the raw IP if lookup fails.
|
||||
func resolveHostname(
|
||||
reqCtx context.Context,
|
||||
addr string,
|
||||
) string {
|
||||
resolver := &net.Resolver{} //nolint:exhaustruct // using default resolver
|
||||
|
||||
ctx, cancel := context.WithTimeout(
|
||||
reqCtx, dnsLookupTimeout,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
names, err := resolver.LookupAddr(ctx, addr)
|
||||
if err != nil || len(names) == 0 {
|
||||
return addr
|
||||
}
|
||||
|
||||
return strings.TrimSuffix(names[0], ".")
|
||||
}
|
||||
|
||||
// authSession extracts the session from the client token.
|
||||
func (hdlr *Handlers) authSession(
|
||||
request *http.Request,
|
||||
) (int64, int64, string, error) {
|
||||
cookie, err := request.Cookie(authCookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
auth := request.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(auth, "Bearer ") {
|
||||
return 0, 0, "", errUnauthorized
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(auth, "Bearer ")
|
||||
if token == "" {
|
||||
return 0, 0, "", errUnauthorized
|
||||
}
|
||||
|
||||
sessionID, clientID, nick, err :=
|
||||
hdlr.params.Database.GetSessionByToken(
|
||||
request.Context(), cookie.Value,
|
||||
request.Context(), token,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, 0, "", fmt.Errorf("auth: %w", err)
|
||||
@@ -67,46 +128,6 @@ func (hdlr *Handlers) authSession(
|
||||
return sessionID, clientID, nick, nil
|
||||
}
|
||||
|
||||
// setAuthCookie sets the authentication cookie on the
|
||||
// response.
|
||||
func (hdlr *Handlers) setAuthCookie(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
token string,
|
||||
) {
|
||||
secure := request.TLS != nil ||
|
||||
request.Header.Get("X-Forwarded-Proto") == "https"
|
||||
|
||||
http.SetCookie(writer, &http.Cookie{ //nolint:exhaustruct // optional fields
|
||||
Name: authCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
}
|
||||
|
||||
// clearAuthCookie removes the authentication cookie from
|
||||
// the client.
|
||||
func (hdlr *Handlers) clearAuthCookie(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
) {
|
||||
secure := request.TLS != nil ||
|
||||
request.Header.Get("X-Forwarded-Proto") == "https"
|
||||
|
||||
http.SetCookie(writer, &http.Cookie{ //nolint:exhaustruct // optional fields
|
||||
Name: authCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
|
||||
func (hdlr *Handlers) requireAuth(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
@@ -191,6 +212,7 @@ func (hdlr *Handlers) handleCreateSession(
|
||||
) {
|
||||
type createRequest struct {
|
||||
Nick string `json:"nick"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Hashcash string `json:"pow_token,omitempty"` //nolint:tagliatelle
|
||||
}
|
||||
|
||||
@@ -207,30 +229,10 @@ func (hdlr *Handlers) handleCreateSession(
|
||||
return
|
||||
}
|
||||
|
||||
// Validate hashcash proof-of-work if configured.
|
||||
if hdlr.params.Config.HashcashBits > 0 {
|
||||
if payload.Hashcash == "" {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"hashcash proof-of-work required",
|
||||
http.StatusPaymentRequired,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = hdlr.hashcashVal.Validate(
|
||||
payload.Hashcash, hdlr.params.Config.HashcashBits,
|
||||
)
|
||||
if err != nil {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"invalid hashcash stamp: "+err.Error(),
|
||||
http.StatusPaymentRequired,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
if !hdlr.validateHashcash(
|
||||
writer, request, payload.Hashcash,
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
payload.Nick = strings.TrimSpace(payload.Nick)
|
||||
@@ -245,9 +247,40 @@ func (hdlr *Handlers) handleCreateSession(
|
||||
return
|
||||
}
|
||||
|
||||
username := resolveUsername(
|
||||
payload.Username, payload.Nick,
|
||||
)
|
||||
|
||||
if !validUsernameRe.MatchString(username) {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"invalid username format",
|
||||
http.StatusBadRequest,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
hdlr.executeCreateSession(
|
||||
writer, request, payload.Nick, username,
|
||||
)
|
||||
}
|
||||
|
||||
func (hdlr *Handlers) executeCreateSession(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
nick, username string,
|
||||
) {
|
||||
remoteIP := clientIP(request)
|
||||
|
||||
hostname := resolveHostname(
|
||||
request.Context(), remoteIP,
|
||||
)
|
||||
|
||||
sessionID, clientID, token, err :=
|
||||
hdlr.params.Database.CreateSession(
|
||||
request.Context(), payload.Nick,
|
||||
request.Context(),
|
||||
nick, username, hostname, remoteIP,
|
||||
)
|
||||
if err != nil {
|
||||
hdlr.handleCreateSessionError(
|
||||
@@ -260,16 +293,64 @@ func (hdlr *Handlers) handleCreateSession(
|
||||
hdlr.stats.IncrSessions()
|
||||
hdlr.stats.IncrConnections()
|
||||
|
||||
hdlr.deliverMOTD(request, clientID, sessionID, payload.Nick)
|
||||
|
||||
hdlr.setAuthCookie(writer, request, token)
|
||||
hdlr.deliverMOTD(request, clientID, sessionID, nick)
|
||||
|
||||
hdlr.respondJSON(writer, request, map[string]any{
|
||||
"id": sessionID,
|
||||
"nick": payload.Nick,
|
||||
"id": sessionID,
|
||||
"nick": nick,
|
||||
"token": token,
|
||||
}, http.StatusCreated)
|
||||
}
|
||||
|
||||
// validateHashcash validates a hashcash stamp if required.
|
||||
// Returns false if validation failed and a response was
|
||||
// already sent.
|
||||
func (hdlr *Handlers) validateHashcash(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
stamp string,
|
||||
) bool {
|
||||
if hdlr.params.Config.HashcashBits == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
if stamp == "" {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"hashcash proof-of-work required",
|
||||
http.StatusPaymentRequired,
|
||||
)
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
err := hdlr.hashcashVal.Validate(
|
||||
stamp, hdlr.params.Config.HashcashBits,
|
||||
)
|
||||
if err != nil {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"invalid hashcash stamp: "+err.Error(),
|
||||
http.StatusPaymentRequired,
|
||||
)
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// resolveUsername returns the trimmed username, defaulting
|
||||
// to the nick if empty.
|
||||
func resolveUsername(username, nick string) string {
|
||||
username = strings.TrimSpace(username)
|
||||
if username == "" {
|
||||
return nick
|
||||
}
|
||||
|
||||
return username
|
||||
}
|
||||
|
||||
func (hdlr *Handlers) handleCreateSessionError(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
@@ -389,9 +470,19 @@ func (hdlr *Handlers) deliverLusers(
|
||||
)
|
||||
|
||||
// 252 RPL_LUSEROP
|
||||
operCount, operErr := hdlr.params.Database.
|
||||
GetOperCount(ctx)
|
||||
if operErr != nil {
|
||||
hdlr.log.Error(
|
||||
"lusers oper count", "error", operErr,
|
||||
)
|
||||
|
||||
operCount = 0
|
||||
}
|
||||
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplLuserOp, nick,
|
||||
[]string{"0"},
|
||||
[]string{strconv.FormatInt(operCount, 10)},
|
||||
"operator(s) online",
|
||||
)
|
||||
|
||||
@@ -912,11 +1003,6 @@ func (hdlr *Handlers) dispatchCommand(
|
||||
writer, request,
|
||||
sessionID, clientID, nick, bodyLines,
|
||||
)
|
||||
case irc.CmdPass:
|
||||
hdlr.handlePass(
|
||||
writer, request,
|
||||
sessionID, clientID, nick, bodyLines,
|
||||
)
|
||||
case irc.CmdTopic:
|
||||
hdlr.handleTopic(
|
||||
writer, request,
|
||||
@@ -927,6 +1013,11 @@ func (hdlr *Handlers) dispatchCommand(
|
||||
hdlr.handleQuit(
|
||||
writer, request, sessionID, nick, body,
|
||||
)
|
||||
case irc.CmdOper:
|
||||
hdlr.handleOper(
|
||||
writer, request,
|
||||
sessionID, clientID, nick, bodyLines,
|
||||
)
|
||||
case irc.CmdMotd, irc.CmdPing:
|
||||
hdlr.dispatchInfoCommand(
|
||||
writer, request,
|
||||
@@ -1576,16 +1667,16 @@ func (hdlr *Handlers) deliverNamesNumerics(
|
||||
)
|
||||
|
||||
if memErr == nil && len(members) > 0 {
|
||||
nicks := make([]string, 0, len(members))
|
||||
entries := make([]string, 0, len(members))
|
||||
|
||||
for _, mem := range members {
|
||||
nicks = append(nicks, mem.Nick)
|
||||
entries = append(entries, mem.Hostmask())
|
||||
}
|
||||
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplNamReply, nick,
|
||||
[]string{"=", channel},
|
||||
strings.Join(nicks, " "),
|
||||
strings.Join(entries, " "),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2047,8 +2138,6 @@ func (hdlr *Handlers) handleQuit(
|
||||
request.Context(), sessionID,
|
||||
)
|
||||
|
||||
hdlr.clearAuthCookie(writer, request)
|
||||
|
||||
hdlr.respondJSON(writer, request,
|
||||
map[string]string{"status": "quit"},
|
||||
http.StatusOK)
|
||||
@@ -2373,16 +2462,16 @@ func (hdlr *Handlers) handleNames(
|
||||
ctx, chID,
|
||||
)
|
||||
if memErr == nil && len(members) > 0 {
|
||||
nicks := make([]string, 0, len(members))
|
||||
entries := make([]string, 0, len(members))
|
||||
|
||||
for _, mem := range members {
|
||||
nicks = append(nicks, mem.Nick)
|
||||
entries = append(entries, mem.Hostmask())
|
||||
}
|
||||
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplNamReply, nick,
|
||||
[]string{"=", channel},
|
||||
strings.Join(nicks, " "),
|
||||
strings.Join(entries, " "),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2489,55 +2578,42 @@ func (hdlr *Handlers) executeWhois(
|
||||
nick, queryNick string,
|
||||
) {
|
||||
ctx := request.Context()
|
||||
srvName := hdlr.serverName()
|
||||
|
||||
targetSID, err := hdlr.params.Database.GetSessionByNick(
|
||||
ctx, queryNick,
|
||||
)
|
||||
if err != nil {
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.ErrNoSuchNick, nick,
|
||||
[]string{queryNick},
|
||||
"No such nick/channel",
|
||||
hdlr.whoisNotFound(
|
||||
ctx, writer, request,
|
||||
sessionID, clientID, nick, queryNick,
|
||||
)
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplEndOfWhois, nick,
|
||||
[]string{queryNick},
|
||||
"End of /WHOIS list",
|
||||
)
|
||||
hdlr.broker.Notify(sessionID)
|
||||
hdlr.respondJSON(writer, request,
|
||||
map[string]string{"status": "ok"},
|
||||
http.StatusOK)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 311 RPL_WHOISUSER
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplWhoisUser, nick,
|
||||
[]string{queryNick, queryNick, srvName, "*"},
|
||||
queryNick,
|
||||
hdlr.deliverWhoisUser(
|
||||
ctx, clientID, nick, queryNick, targetSID,
|
||||
)
|
||||
|
||||
// 312 RPL_WHOISSERVER
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplWhoisServer, nick,
|
||||
[]string{queryNick, srvName},
|
||||
"neoirc server",
|
||||
// 313 RPL_WHOISOPERATOR — show if target is oper.
|
||||
hdlr.deliverWhoisOperator(
|
||||
ctx, clientID, nick, queryNick, targetSID,
|
||||
)
|
||||
|
||||
// 317 RPL_WHOISIDLE
|
||||
hdlr.deliverWhoisIdle(
|
||||
ctx, clientID, nick, queryNick, targetSID,
|
||||
)
|
||||
|
||||
// 319 RPL_WHOISCHANNELS
|
||||
hdlr.deliverWhoisChannels(
|
||||
ctx, clientID, nick, queryNick, targetSID,
|
||||
)
|
||||
|
||||
// 318 RPL_ENDOFWHOIS
|
||||
// 338 RPL_WHOISACTUALLY — oper-only.
|
||||
hdlr.deliverWhoisActually(
|
||||
ctx, clientID, nick, queryNick,
|
||||
sessionID, targetSID,
|
||||
)
|
||||
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplEndOfWhois, nick,
|
||||
[]string{queryNick},
|
||||
@@ -2550,6 +2626,90 @@ func (hdlr *Handlers) executeWhois(
|
||||
http.StatusOK)
|
||||
}
|
||||
|
||||
// whoisNotFound sends the error+end numerics when the
|
||||
// target nick is not found.
|
||||
func (hdlr *Handlers) whoisNotFound(
|
||||
ctx context.Context,
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
sessionID, clientID int64,
|
||||
nick, queryNick string,
|
||||
) {
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.ErrNoSuchNick, nick,
|
||||
[]string{queryNick},
|
||||
"No such nick/channel",
|
||||
)
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplEndOfWhois, nick,
|
||||
[]string{queryNick},
|
||||
"End of /WHOIS list",
|
||||
)
|
||||
hdlr.broker.Notify(sessionID)
|
||||
hdlr.respondJSON(writer, request,
|
||||
map[string]string{"status": "ok"},
|
||||
http.StatusOK)
|
||||
}
|
||||
|
||||
// deliverWhoisUser sends RPL_WHOISUSER (311) and
|
||||
// RPL_WHOISSERVER (312).
|
||||
func (hdlr *Handlers) deliverWhoisUser(
|
||||
ctx context.Context,
|
||||
clientID int64,
|
||||
nick, queryNick string,
|
||||
targetSID int64,
|
||||
) {
|
||||
srvName := hdlr.serverName()
|
||||
|
||||
username := queryNick
|
||||
hostname := srvName
|
||||
|
||||
hostInfo, hostErr := hdlr.params.Database.
|
||||
GetSessionHostInfo(ctx, targetSID)
|
||||
if hostErr == nil && hostInfo != nil {
|
||||
if hostInfo.Username != "" {
|
||||
username = hostInfo.Username
|
||||
}
|
||||
|
||||
if hostInfo.Hostname != "" {
|
||||
hostname = hostInfo.Hostname
|
||||
}
|
||||
}
|
||||
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplWhoisUser, nick,
|
||||
[]string{queryNick, username, hostname, "*"},
|
||||
queryNick,
|
||||
)
|
||||
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplWhoisServer, nick,
|
||||
[]string{queryNick, srvName},
|
||||
"neoirc server",
|
||||
)
|
||||
}
|
||||
|
||||
// deliverWhoisOperator sends RPL_WHOISOPERATOR (313) if
|
||||
// the target has server oper status.
|
||||
func (hdlr *Handlers) deliverWhoisOperator(
|
||||
ctx context.Context,
|
||||
clientID int64,
|
||||
nick, queryNick string,
|
||||
targetSID int64,
|
||||
) {
|
||||
targetIsOper, err := hdlr.params.Database.
|
||||
IsSessionOper(ctx, targetSID)
|
||||
if err != nil || !targetIsOper {
|
||||
return
|
||||
}
|
||||
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplWhoisOperator, nick,
|
||||
[]string{queryNick},
|
||||
"is an IRC operator",
|
||||
)
|
||||
}
|
||||
|
||||
func (hdlr *Handlers) deliverWhoisChannels(
|
||||
ctx context.Context,
|
||||
clientID int64,
|
||||
@@ -2575,6 +2735,44 @@ func (hdlr *Handlers) deliverWhoisChannels(
|
||||
)
|
||||
}
|
||||
|
||||
// deliverWhoisActually sends RPL_WHOISACTUALLY (338)
|
||||
// with the target's current client IP and hostname, but
|
||||
// only when the querying session has server oper status
|
||||
// (o-line). Non-opers see nothing extra.
|
||||
func (hdlr *Handlers) deliverWhoisActually(
|
||||
ctx context.Context,
|
||||
clientID int64,
|
||||
nick, queryNick string,
|
||||
querierSID, targetSID int64,
|
||||
) {
|
||||
isOper, err := hdlr.params.Database.IsSessionOper(
|
||||
ctx, querierSID,
|
||||
)
|
||||
if err != nil || !isOper {
|
||||
return
|
||||
}
|
||||
|
||||
clientInfo, clErr := hdlr.params.Database.
|
||||
GetLatestClientForSession(ctx, targetSID)
|
||||
if clErr != nil {
|
||||
return
|
||||
}
|
||||
|
||||
actualHost := clientInfo.Hostname
|
||||
if actualHost == "" {
|
||||
actualHost = clientInfo.IP
|
||||
}
|
||||
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplWhoisActually, nick,
|
||||
[]string{
|
||||
queryNick,
|
||||
clientInfo.IP,
|
||||
},
|
||||
"is actually using host "+actualHost,
|
||||
)
|
||||
}
|
||||
|
||||
// handleWho handles the WHO command.
|
||||
func (hdlr *Handlers) handleWho(
|
||||
writer http.ResponseWriter,
|
||||
@@ -2623,11 +2821,21 @@ func (hdlr *Handlers) handleWho(
|
||||
)
|
||||
if memErr == nil {
|
||||
for _, mem := range members {
|
||||
username := mem.Username
|
||||
if username == "" {
|
||||
username = mem.Nick
|
||||
}
|
||||
|
||||
hostname := mem.Hostname
|
||||
if hostname == "" {
|
||||
hostname = srvName
|
||||
}
|
||||
|
||||
// 352 RPL_WHOREPLY
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplWhoReply, nick,
|
||||
[]string{
|
||||
channel, mem.Nick, srvName,
|
||||
channel, username, hostname,
|
||||
srvName, mem.Nick, "H",
|
||||
},
|
||||
"0 "+mem.Nick,
|
||||
@@ -2851,8 +3059,6 @@ func (hdlr *Handlers) HandleLogout() http.HandlerFunc {
|
||||
)
|
||||
}
|
||||
|
||||
hdlr.clearAuthCookie(writer, request)
|
||||
|
||||
hdlr.respondJSON(writer, request,
|
||||
map[string]string{"status": "ok"},
|
||||
http.StatusOK)
|
||||
@@ -2952,6 +3158,76 @@ func (hdlr *Handlers) HandleServerInfo() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// handleOper handles the OPER command for server operator authentication.
|
||||
func (hdlr *Handlers) handleOper(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
sessionID, clientID int64,
|
||||
nick string,
|
||||
bodyLines func() []string,
|
||||
) {
|
||||
ctx := request.Context()
|
||||
|
||||
lines := bodyLines()
|
||||
if len(lines) < 2 { //nolint:mnd // name + password
|
||||
hdlr.respondIRCError(
|
||||
writer, request, clientID, sessionID,
|
||||
irc.ErrNeedMoreParams, nick,
|
||||
[]string{irc.CmdOper},
|
||||
"Not enough parameters",
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
operName := lines[0]
|
||||
operPass := lines[1]
|
||||
|
||||
cfgName := hdlr.params.Config.OperName
|
||||
cfgPass := hdlr.params.Config.OperPassword
|
||||
|
||||
if cfgName == "" || cfgPass == "" ||
|
||||
subtle.ConstantTimeCompare([]byte(operName), []byte(cfgName)) != 1 ||
|
||||
subtle.ConstantTimeCompare([]byte(operPass), []byte(cfgPass)) != 1 {
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.ErrNoOperHost, nick,
|
||||
nil, "No O-lines for your host",
|
||||
)
|
||||
hdlr.broker.Notify(sessionID)
|
||||
hdlr.respondJSON(writer, request,
|
||||
map[string]string{"status": "error"},
|
||||
http.StatusOK)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err := hdlr.params.Database.SetSessionOper(
|
||||
ctx, sessionID, true,
|
||||
)
|
||||
if err != nil {
|
||||
hdlr.log.Error(
|
||||
"set oper failed", "error", err,
|
||||
)
|
||||
hdlr.respondError(
|
||||
writer, request, "internal error",
|
||||
http.StatusInternalServerError,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 381 RPL_YOUREOPER
|
||||
hdlr.enqueueNumeric(
|
||||
ctx, clientID, irc.RplYoureOper, nick,
|
||||
nil, "You are now an IRC operator",
|
||||
)
|
||||
|
||||
hdlr.broker.Notify(sessionID)
|
||||
hdlr.respondJSON(writer, request,
|
||||
map[string]string{"status": "ok"},
|
||||
http.StatusOK)
|
||||
}
|
||||
|
||||
// handleAway handles the AWAY command. An empty body
|
||||
// clears the away status; a non-empty body sets it.
|
||||
func (hdlr *Handlers) handleAway(
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,11 +5,151 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.eeqj.de/sneak/neoirc/pkg/irc"
|
||||
"git.eeqj.de/sneak/neoirc/internal/db"
|
||||
)
|
||||
|
||||
const minPasswordLength = 8
|
||||
|
||||
// HandleRegister creates a new user with a password.
|
||||
func (hdlr *Handlers) HandleRegister() http.HandlerFunc {
|
||||
return func(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
) {
|
||||
request.Body = http.MaxBytesReader(
|
||||
writer, request.Body, hdlr.maxBodySize(),
|
||||
)
|
||||
|
||||
hdlr.handleRegister(writer, request)
|
||||
}
|
||||
}
|
||||
|
||||
func (hdlr *Handlers) handleRegister(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
) {
|
||||
type registerRequest struct {
|
||||
Nick string `json:"nick"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
var payload registerRequest
|
||||
|
||||
err := json.NewDecoder(request.Body).Decode(&payload)
|
||||
if err != nil {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"invalid request body",
|
||||
http.StatusBadRequest,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
payload.Nick = strings.TrimSpace(payload.Nick)
|
||||
|
||||
if !validNickRe.MatchString(payload.Nick) {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"invalid nick format",
|
||||
http.StatusBadRequest,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
username := resolveUsername(
|
||||
payload.Username, payload.Nick,
|
||||
)
|
||||
|
||||
if !validUsernameRe.MatchString(username) {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"invalid username format",
|
||||
http.StatusBadRequest,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if len(payload.Password) < minPasswordLength {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"password must be at least 8 characters",
|
||||
http.StatusBadRequest,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
hdlr.executeRegister(
|
||||
writer, request,
|
||||
payload.Nick, payload.Password, username,
|
||||
)
|
||||
}
|
||||
|
||||
func (hdlr *Handlers) executeRegister(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
nick, password, username string,
|
||||
) {
|
||||
remoteIP := clientIP(request)
|
||||
|
||||
hostname := resolveHostname(
|
||||
request.Context(), remoteIP,
|
||||
)
|
||||
|
||||
sessionID, clientID, token, err :=
|
||||
hdlr.params.Database.RegisterUser(
|
||||
request.Context(),
|
||||
nick, password, username, hostname, remoteIP,
|
||||
)
|
||||
if err != nil {
|
||||
hdlr.handleRegisterError(
|
||||
writer, request, err,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
hdlr.stats.IncrSessions()
|
||||
hdlr.stats.IncrConnections()
|
||||
|
||||
hdlr.deliverMOTD(request, clientID, sessionID, nick)
|
||||
|
||||
hdlr.respondJSON(writer, request, map[string]any{
|
||||
"id": sessionID,
|
||||
"nick": nick,
|
||||
"token": token,
|
||||
}, http.StatusCreated)
|
||||
}
|
||||
|
||||
func (hdlr *Handlers) handleRegisterError(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
err error,
|
||||
) {
|
||||
if db.IsUniqueConstraintError(err) {
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"nick already taken",
|
||||
http.StatusConflict,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
hdlr.log.Error(
|
||||
"register user failed", "error", err,
|
||||
)
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"internal error",
|
||||
http.StatusInternalServerError,
|
||||
)
|
||||
}
|
||||
|
||||
// HandleLogin authenticates a user with nick and password.
|
||||
func (hdlr *Handlers) HandleLogin() http.HandlerFunc {
|
||||
return func(
|
||||
@@ -58,11 +198,18 @@ func (hdlr *Handlers) handleLogin(
|
||||
return
|
||||
}
|
||||
|
||||
remoteIP := clientIP(request)
|
||||
|
||||
hostname := resolveHostname(
|
||||
request.Context(), remoteIP,
|
||||
)
|
||||
|
||||
sessionID, clientID, token, err :=
|
||||
hdlr.params.Database.LoginUser(
|
||||
request.Context(),
|
||||
payload.Nick,
|
||||
payload.Password,
|
||||
remoteIP, hostname,
|
||||
)
|
||||
if err != nil {
|
||||
hdlr.respondError(
|
||||
@@ -86,66 +233,9 @@ func (hdlr *Handlers) handleLogin(
|
||||
request, clientID, sessionID, payload.Nick,
|
||||
)
|
||||
|
||||
hdlr.setAuthCookie(writer, request, token)
|
||||
|
||||
hdlr.respondJSON(writer, request, map[string]any{
|
||||
"id": sessionID,
|
||||
"nick": payload.Nick,
|
||||
"id": sessionID,
|
||||
"nick": payload.Nick,
|
||||
"token": token,
|
||||
}, http.StatusOK)
|
||||
}
|
||||
|
||||
// handlePass handles the IRC PASS command to set a
|
||||
// password on the authenticated session, enabling
|
||||
// multi-client login via POST /api/v1/login.
|
||||
func (hdlr *Handlers) handlePass(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
sessionID, clientID int64,
|
||||
nick string,
|
||||
bodyLines func() []string,
|
||||
) {
|
||||
lines := bodyLines()
|
||||
if len(lines) == 0 || lines[0] == "" {
|
||||
hdlr.respondIRCError(
|
||||
writer, request, clientID, sessionID,
|
||||
irc.ErrNeedMoreParams, nick,
|
||||
[]string{irc.CmdPass},
|
||||
"Not enough parameters",
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
password := lines[0]
|
||||
|
||||
if len(password) < minPasswordLength {
|
||||
hdlr.respondIRCError(
|
||||
writer, request, clientID, sessionID,
|
||||
irc.ErrNeedMoreParams, nick,
|
||||
[]string{irc.CmdPass},
|
||||
"Password must be at least 8 characters",
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err := hdlr.params.Database.SetPassword(
|
||||
request.Context(), sessionID, password,
|
||||
)
|
||||
if err != nil {
|
||||
hdlr.log.Error(
|
||||
"set password failed", "error", err,
|
||||
)
|
||||
hdlr.respondError(
|
||||
writer, request,
|
||||
"internal error",
|
||||
http.StatusInternalServerError,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
hdlr.respondJSON(writer, request,
|
||||
map[string]string{"status": "ok"},
|
||||
http.StatusOK)
|
||||
}
|
||||
|
||||
@@ -126,23 +126,18 @@ func (mware *Middleware) Logging() func(http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
// CORS returns middleware that handles Cross-Origin Resource Sharing.
|
||||
// AllowCredentials is true so browsers include cookies in
|
||||
// cross-origin API requests.
|
||||
func (mware *Middleware) CORS() func(http.Handler) http.Handler {
|
||||
return cors.Handler(cors.Options{ //nolint:exhaustruct // optional fields
|
||||
AllowOriginFunc: func(
|
||||
_ *http.Request, _ string,
|
||||
) bool {
|
||||
return true
|
||||
},
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{
|
||||
"GET", "POST", "PUT", "DELETE", "OPTIONS",
|
||||
},
|
||||
AllowedHeaders: []string{
|
||||
"Accept", "Content-Type", "X-CSRF-Token",
|
||||
"Accept", "Authorization",
|
||||
"Content-Type", "X-CSRF-Token",
|
||||
},
|
||||
ExposedHeaders: []string{"Link"},
|
||||
AllowCredentials: true,
|
||||
AllowCredentials: false,
|
||||
MaxAge: corsMaxAge,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -75,6 +75,10 @@ func (srv *Server) setupAPIv1(router chi.Router) {
|
||||
"/session",
|
||||
srv.handlers.HandleCreateSession(),
|
||||
)
|
||||
router.Post(
|
||||
"/register",
|
||||
srv.handlers.HandleRegister(),
|
||||
)
|
||||
router.Post(
|
||||
"/login",
|
||||
srv.handlers.HandleLogin(),
|
||||
|
||||
@@ -11,7 +11,7 @@ const (
|
||||
CmdNames = "NAMES"
|
||||
CmdNick = "NICK"
|
||||
CmdNotice = "NOTICE"
|
||||
CmdPass = "PASS"
|
||||
CmdOper = "OPER"
|
||||
CmdPart = "PART"
|
||||
CmdPing = "PING"
|
||||
CmdPong = "PONG"
|
||||
|
||||
@@ -132,6 +132,7 @@ const (
|
||||
RplNoTopic IRCMessageType = 331
|
||||
RplTopic IRCMessageType = 332
|
||||
RplTopicWhoTime IRCMessageType = 333
|
||||
RplWhoisActually IRCMessageType = 338
|
||||
RplInviting IRCMessageType = 341
|
||||
RplSummoning IRCMessageType = 342
|
||||
RplInviteList IRCMessageType = 346
|
||||
@@ -295,6 +296,7 @@ var names = map[IRCMessageType]string{
|
||||
RplNoTopic: "RPL_NOTOPIC",
|
||||
RplTopic: "RPL_TOPIC",
|
||||
RplTopicWhoTime: "RPL_TOPICWHOTIME",
|
||||
RplWhoisActually: "RPL_WHOISACTUALLY",
|
||||
RplInviting: "RPL_INVITING",
|
||||
RplSummoning: "RPL_SUMMONING",
|
||||
RplInviteList: "RPL_INVITELIST",
|
||||
|
||||
Reference in New Issue
Block a user