-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthenticator.go
More file actions
214 lines (186 loc) · 4.96 KB
/
authenticator.go
File metadata and controls
214 lines (186 loc) · 4.96 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
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2025 Aaron LI
//
// Implement a simple authenticator
//
package main
import (
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"log/slog"
"net/http"
"strings"
"sync"
"time"
)
type Authenticator struct {
// Secret for the HMAC to sign the cookie.
// If unspecified, then randomly generate one.
Secret []byte
// Number of retries to pass the authentication.
Retries int
// Time (seconds) to wait for a client to finish authenticating.
WaitTime int
// Cache time (seconds) of a successful authentication.
TTL int
// HMAC to sign and verify the cookie.
hmac hash.Hash
// Mutex to protect hmac from concurrent accesses.
mutex sync.Mutex
// Allow to override the clock to accelerate tests.
clock iClock
}
type authInfo struct {
// randomly generated unique session id
SID string `json:"sid"`
// remaining tries to go
Tries int `json:"t"`
// expire time of the tries (before) or the session (after)
Expires int64 `json:"exp"`
}
func (a *Authenticator) Middleware(next http.Handler) http.Handler {
const (
cookieName = "wikiproxy"
cookieMaxAge = 86400 // seconds
)
// Initialize HMAC.
secret := a.Secret
if len(secret) == 0 {
secret = make([]byte, 33)
_, err := rand.Read(secret)
if err != nil {
// crypto/rand.Read() will always succeed on Go 1.24+,
// but we're using Go 1.21+ in go.mod.
panic(err)
}
slog.Info("generated a random HMAC secret")
}
a.hmac = hmac.New(md5.New, secret)
if a.clock == nil {
a.clock = realClock{}
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookieSecure := (r.TLS != nil)
if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
cookieSecure = (proto == "https")
}
setCookie := &http.Cookie{
Name: cookieName,
MaxAge: cookieMaxAge,
Secure: cookieSecure,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Path: "/",
}
cookie, _ := r.Cookie(cookieName)
if cookie == nil {
setCookie.Value = a.makeCookie(nil)
slog.Debug("created cookie", "cookie", setCookie)
http.SetCookie(w, setCookie)
http.Error(w, fmt.Sprintf("not found: %d...", a.Retries),
http.StatusNotFound)
return
}
slog.Debug("got cookie", "cookie", cookie)
info, err := a.parseCookie(cookie.Value)
if err != nil {
slog.Info("invalid cookie", "cookie", cookie, "error", err)
http.Error(w, "forbidden", http.StatusForbidden)
return
}
if info.Expires <= a.clock.Now().Unix() {
setCookie.Value = a.makeCookie(nil)
slog.Debug("replaced cookie", "cookie", setCookie)
http.SetCookie(w, setCookie)
http.Error(w, fmt.Sprintf("not found: %d...", a.Retries),
http.StatusNotFound)
return
}
if info.Tries > 0 {
info.Tries--
setCookie.Value = a.makeCookie(info)
slog.Debug("updated cookie", "cookie", setCookie)
http.SetCookie(w, setCookie)
}
if info.Tries > 0 {
http.Error(w, fmt.Sprintf("not found: %d...", info.Tries),
http.StatusNotFound)
return
}
// Strip the "wikiproxy" cookie to avoid proxying it.
cookies := []string{}
for _, c := range r.Cookies() {
if c.Name != cookieName {
cookies = append(cookies, c.String())
}
}
r.Header.Set("Cookie", strings.Join(cookies, "; "))
next.ServeHTTP(w, r)
})
}
// Cookie value format: <base64url(json(authInfo))>.<hmac_signature>
func (a *Authenticator) parseCookie(value string) (*authInfo, error) {
dataStr, sig, found := strings.Cut(value, ".")
if !found {
return nil, errors.New("invalid cookie format")
}
if a.sign(dataStr) != sig {
return nil, errors.New("invalid cookie signature")
}
data, err := base64.URLEncoding.DecodeString(dataStr)
if err != nil {
return nil, errors.New("invalid cookie data")
}
info := authInfo{}
if err := json.Unmarshal(data, &info); err != nil {
return nil, fmt.Errorf("invalid cookie json: %v", err)
}
slog.Debug("parsed authInfo", "value", &info)
return &info, nil
}
func (a *Authenticator) makeCookie(info *authInfo) string {
if info == nil {
info = &authInfo{
Tries: a.Retries,
Expires: a.clock.Now().Unix() + int64(a.WaitTime),
}
}
if info.SID == "" {
sid := make([]byte, 12)
_, _ = rand.Read(sid)
info.SID = base64.URLEncoding.EncodeToString(sid)
}
if info.Tries == 0 {
info.Expires = a.clock.Now().Unix() + int64(a.TTL)
} else if info.Expires == 0 {
info.Expires = a.clock.Now().Unix() + int64(a.WaitTime)
}
slog.Debug("made authInfo", "value", info)
data, _ := json.Marshal(info)
dataStr := base64.URLEncoding.EncodeToString(data)
return dataStr + "." + a.sign(dataStr)
}
func (a *Authenticator) sign(data string) string {
a.mutex.Lock()
defer a.mutex.Unlock()
a.hmac.Reset()
a.hmac.Write([]byte(data))
result := a.hmac.Sum(nil)
return hex.EncodeToString(result)
}
// ---------------------------------------------------------------------
type iClock interface {
Now() time.Time
}
type realClock struct{}
func (realClock) Now() time.Time {
return time.Now()
}