summaryrefslogtreecommitdiff
path: root/internal/server/session/session.go
blob: 1eb2e80bb403519bcd62e86d6a8df7e304a5b14f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package session

import (
	"context"
	"crypto/ed25519"
	"crypto/rand"
	"log/slog"
	"net"
	"sync"
	"time"

	"github.com/kyren223/eko/internal/packet"
	"github.com/kyren223/eko/internal/server/ctxkeys"
	"github.com/kyren223/eko/pkg/assert"
	"github.com/kyren223/eko/pkg/rate"
	"github.com/kyren223/eko/pkg/snowflake"
)

const (
	WriteQueueSize = 10
	NonceSize      = 32

	DefaultRate        = 0.1 // ms per second
	DefaultLimit       = 3   // ms burst
	AuthenticatedRate  = 1   // ms per second
	AuthenticatedLimit = 20  // ms burst
)

type SessionManager interface {
	AddSession(session *Session, userId snowflake.ID, pubKey ed25519.PublicKey)
	RemoveSession(id snowflake.ID)
	Session(id snowflake.ID) *Session
	UseSessions(f func(map[snowflake.ID]*Session))

	Node() *snowflake.Node
}

type Session struct {
	manager SessionManager
	addr    *net.TCPAddr
	cancel  context.CancelFunc

	writeQueue chan packet.Payload
	writerWg   *sync.WaitGroup
	writeMu    sync.RWMutex

	issuedTime  time.Time
	challenge   []byte
	challengeMu sync.Mutex

	isTosAccepted bool
	pubKey        ed25519.PublicKey
	id            snowflake.ID
	rl            rate.Limiter
	start         time.Time
	analytics     *packet.DeviceAnalytics

	mu sync.RWMutex
}

func NewSession(
	manager SessionManager,
	addr *net.TCPAddr, cancel context.CancelFunc,
	writerWg *sync.WaitGroup,
) *Session {
	assert.NotNil(addr, "tcp address should be valid")
	assert.NotNil(manager, "session manager should be valid")
	session := &Session{
		manager:       manager,
		addr:          addr,
		cancel:        cancel,
		writeQueue:    make(chan packet.Payload, WriteQueueSize),
		writerWg:      writerWg,
		writeMu:       sync.RWMutex{},
		issuedTime:    time.Time{},
		challenge:     make([]byte, NonceSize),
		pubKey:        ed25519.PublicKey{},
		id:            snowflake.InvalidID,
		challengeMu:   sync.Mutex{},
		isTosAccepted: false,
		rl:            rate.NewLimiter(DefaultRate, DefaultLimit),
		start:         time.Time{},
		analytics:     nil,
		mu:            sync.RWMutex{},
	}
	return session
}

func (s *Session) Addr() *net.TCPAddr {
	assert.NotNil(s.addr, "tcp address should be valid")
	return s.addr
}

func (s *Session) RateLimiter() *rate.Limiter {
	return &s.rl
}

func (s *Session) IsTosAccepted() bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.isTosAccepted
}

func (s *Session) ReceivedTosAcceptance() {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.isTosAccepted = true
}

func (s *Session) IsAuthenticated() bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.id != snowflake.InvalidID
}

func (s *Session) ID() snowflake.ID {
	s.mu.RLock()
	defer s.mu.RUnlock()
	assert.Assert(s.IsAuthenticated(), "use of ID in an unauthenticated session", "addr", s.addr)
	return s.id
}

func (s *Session) PubKey() ed25519.PublicKey {
	s.mu.RLock()
	defer s.mu.RUnlock()
	assert.Assert(s.IsAuthenticated(), "use of PubKey in an unauthenticated session", "addr", s.addr)
	return s.pubKey
}

func (s *Session) Promote(userId snowflake.ID, pubKey ed25519.PublicKey) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.id = userId
	s.pubKey = pubKey
	s.rl.SetLimit(AuthenticatedLimit)
	s.rl.SetRate(AuthenticatedRate)
	s.start = time.Now().UTC()
}

func (s *Session) Duration() time.Duration {
	assert.Assert(s.IsAuthenticated(), "tried accessing session duration in an authenticated session")
	s.mu.RLock()
	defer s.mu.RUnlock()
	return time.Since(s.start)
}

func (s *Session) Analytics() *packet.DeviceAnalytics {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.analytics
}

func (s *Session) SetAnalytics(analytics *packet.DeviceAnalytics) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.analytics = analytics
}

func (s *Session) Manager() SessionManager {
	return s.manager
}

func (s *Session) Challenge() []byte {
	s.challengeMu.Lock()
	defer s.challengeMu.Unlock()
	if time.Since(s.issuedTime) > time.Minute {
		s.issuedTime = time.Now()
		_, err := rand.Read(s.challenge)
		assert.NoError(err, "random should always produce a value")
	}
	return s.challenge
}

func (s *Session) Write(ctx context.Context, payload packet.Payload) bool {
	s.writerWg.Add(1)
	defer s.writerWg.Done()

	s.writeMu.RLock()
	defer s.writeMu.RUnlock()

	select {
	case s.writeQueue <- payload:
		return true
	case <-ctx.Done():
		return false
	}
}

func (s *Session) Read() <-chan packet.Payload {
	s.writeMu.RLock()
	defer s.writeMu.RUnlock()
	return s.writeQueue
}

func (s *Session) CloseWriteQueue() {
	s.writeMu.Lock()
	defer s.writeMu.Unlock()

	close(s.writeQueue)
	s.writeQueue = nil
}

func (s *Session) Close() {
	s.cancel()
}

func (s *Session) LogValue() slog.Value {
	if s.IsAuthenticated() {
		return slog.GroupValue(
			slog.Any(ctxkeys.IpAddr.String(), s.Addr()),
			slog.Any(ctxkeys.UserID.String(), s.ID()),
			slog.Any("public_key", s.PubKey()),
		)
	} else {
		return slog.GroupValue(
			slog.Any(ctxkeys.IpAddr.String(), s.Addr()),
		)
	}
}