-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathauth.go
More file actions
235 lines (191 loc) · 6.2 KB
/
auth.go
File metadata and controls
235 lines (191 loc) · 6.2 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package home
import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghuser"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/netutil/httputil"
"github.com/AdguardTeam/golibs/timeutil"
"golang.org/x/crypto/bcrypt"
)
// sessionsDBName is the name of the file where session data is stored.
const sessionsDBName = "sessions.db"
// webUser represents a user of the Web UI.
//
// TODO(s.chzhen): Improve naming.
type webUser struct {
// Name represents the login name of the web user.
Name string `yaml:"name"`
// PasswordHash is the hashed representation of the web user password.
PasswordHash string `yaml:"password"`
// UserID is the unique identifier of the web user.
UserID aghuser.UserID `yaml:"-"`
}
// toUser returns the new properly initialized *aghuser.User using stored
// properties. It panics if there is an error generating the user ID.
func (wu *webUser) toUser() (u *aghuser.User) {
uid := wu.UserID
if uid == (aghuser.UserID{}) {
uid = aghuser.MustNewUserID()
}
return &aghuser.User{
Password: aghuser.NewDefaultPassword(wu.PasswordHash),
Login: aghuser.Login(wu.Name),
ID: uid,
}
}
// authConfig is the configuration structure for [auth].
type authConfig struct {
// baseLogger is used for creating other loggers. It must not be nil.
baseLogger *slog.Logger
// mux is the server's multiplexer. It must not be nil.
mux *http.ServeMux
// gliNetTokenRoot is the root where GLiNet tokens are stored. It must not
// be nil if isGLiNet is true.
gliNetTokenRoot *os.Root
// rateLimiter manages the rate limiting for login attempts. It must not be
// nil.
rateLimiter loginRateLimiter
// trustedProxies is a set of subnets considered as trusted.
trustedProxies netutil.SubnetSet
// dbFilename is the name of the file where session data is stored. It must
// not be empty.
dbFilename string
// doHRoutes is a list of DoH routes for public access.
doHRoutes []string
// users contains web user information from the configuration file.
users []webUser
// sessionTTL is the TTL (Time To Live) for web user sessions.
sessionTTL time.Duration
// isGLiNet indicates whether GLiNet mode is enabled.
isGLiNet bool
}
// auth stores web user information and handles authentication.
type auth struct {
// logger is used to log the operation of the auth module.
logger *slog.Logger
// mux is the server's multiplexer.
mux *http.ServeMux
// gliNetTokenRoot is the root where GLiNet tokens are stored. It must not
// be nil if isGLiNet is true.
gliNetTokenRoot *os.Root
// rateLimiter manages rate limiting for login attempts.
rateLimiter loginRateLimiter
// trustedProxies is a set of subnets considered trusted.
trustedProxies netutil.SubnetSet
// sessions stores web users' sessions.
sessions aghuser.SessionStorage
// users stores user credentials.
users aghuser.DB
// doHRoutes is a list of DoH routes for public access.
doHRoutes []string
// isGLiNet indicates whether GLiNet mode is enabled.
isGLiNet bool
// isUserless indicates that there are no users defined in the configuration
// file.
isUserless bool
}
// newAuth returns the new properly initialized *auth.
func newAuth(ctx context.Context, conf *authConfig) (a *auth, err error) {
userDB := aghuser.NewDefaultDB()
for i, u := range conf.users {
err = userDB.Create(ctx, u.toUser())
if err != nil {
return nil, fmt.Errorf("users: at index %d: %w", i, err)
}
}
s, err := aghuser.NewDefaultSessionStorage(ctx, &aghuser.DefaultSessionStorageConfig{
Logger: conf.baseLogger.With(slogutil.KeyPrefix, "session_storage"),
Clock: timeutil.SystemClock{},
UserDB: userDB,
DBPath: conf.dbFilename,
SessionTTL: conf.sessionTTL,
})
if err != nil {
return nil, fmt.Errorf("creating session storage: %w", err)
}
return &auth{
logger: conf.baseLogger.With(slogutil.KeyPrefix, "auth"),
mux: conf.mux,
rateLimiter: conf.rateLimiter,
trustedProxies: conf.trustedProxies,
gliNetTokenRoot: conf.gliNetTokenRoot,
sessions: s,
users: userDB,
doHRoutes: conf.doHRoutes,
isGLiNet: conf.isGLiNet,
isUserless: len(conf.users) == 0,
}, nil
}
// middleware returns authentication middleware.
func (a *auth) middleware() (mw httputil.Middleware) {
if a.isGLiNet {
return newAuthMiddlewareGLiNet(&authMiddlewareGLiNetConfig{
logger: a.logger,
mux: a.mux,
clock: timeutil.SystemClock{},
doHRoutes: a.doHRoutes,
tokenFileRoot: a.gliNetTokenRoot,
ttl: glTokenTimeout,
maxTokenSize: MaxFileSize,
})
}
return newAuthMiddlewareDefault(&authMiddlewareDefaultConfig{
logger: a.logger,
mux: a.mux,
rateLimiter: a.rateLimiter,
trustedProxies: a.trustedProxies,
sessions: a.sessions,
users: a.users,
doHRoutes: a.doHRoutes,
})
}
// usersList returns a copy of a users list.
func (a *auth) usersList(ctx context.Context) (webUsers []webUser) {
users, err := a.users.All(ctx)
if err != nil {
// Should not happen.
panic(err)
}
webUsers = make([]webUser, 0, len(users))
for _, u := range users {
webUsers = append(webUsers, webUser{
Name: string(u.Login),
PasswordHash: string(u.Password.Hash()),
UserID: u.ID,
})
}
return webUsers
}
// addUser adds a new user with the given password. u must not be nil.
func (a *auth) addUser(ctx context.Context, u *webUser, password string) (err error) {
if len(password) == 0 {
return errors.Error("empty password")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("generating hash: %w", err)
}
u.PasswordHash = string(hash)
err = a.users.Create(ctx, u.toUser())
if err != nil {
// Should not happen.
panic(err)
}
a.isUserless = false
a.logger.DebugContext(ctx, "added user", "login", u.Name)
return nil
}
// close closes the authentication database.
func (a *auth) close(ctx context.Context) {
err := a.sessions.Close()
if err != nil {
a.logger.ErrorContext(ctx, "closing session storage", slogutil.KeyError, err)
}
}