Repository navigation
Expand file tree
/
Copy pathmodule.go
More file actions
405 lines (346 loc) · 11.7 KB
/
Copy pathmodule.go
File metadata and controls
405 lines (346 loc) · 11.7 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package crawlwall
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
"go.uber.org/zap"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/jolovicdev/crawlwall/v2/internal/bot"
"github.com/jolovicdev/crawlwall/v2/internal/config"
"github.com/jolovicdev/crawlwall/v2/internal/ledger"
"github.com/jolovicdev/crawlwall/v2/internal/policy"
"github.com/jolovicdev/crawlwall/v2/internal/ratelimit"
"github.com/jolovicdev/crawlwall/v2/internal/receipt"
"github.com/jolovicdev/crawlwall/v2/internal/robots"
"github.com/jolovicdev/crawlwall/v2/internal/verify"
"github.com/jolovicdev/crawlwall/v2/internal/version"
)
const (
// actionRateLimitExceeded is the ledger action recorded when a request is
// over its limit, in enforce and shadow mode alike. `ledger report` counts
// it as blocked or would-block depending on Enforced.
actionRateLimitExceeded = "rate_limit_exceeded"
ledgerWriteTimeout = 5 * time.Second
robotsPath = "/robots.txt"
)
func init() {
caddy.RegisterModule(Crawlwall{})
}
type Crawlwall struct {
PolicyFile string `json:"policy_file,omitempty"`
LedgerDSN string `json:"ledger_dsn,omitempty"`
FailMode string `json:"fail_mode,omitempty"`
logger *zap.Logger
config *config.Config
bots *bot.Identifier
verifier *verify.Service
policy *policy.Engine
ledger ledger.Ledger
limiter *ratelimit.Limiter
signer *receipt.Signer
robotsTxt []byte
}
func (Crawlwall) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.crawlwall",
New: func() caddy.Module { return new(Crawlwall) },
}
}
func (m *Crawlwall) Provision(ctx caddy.Context) error {
m.logger = ctx.Logger()
if strings.TrimSpace(m.PolicyFile) == "" {
return errors.New("crawlwall policy file is required")
}
cfg, err := config.LoadFile(m.PolicyFile)
if err != nil {
return fmt.Errorf("load crawlwall policy: %w", err)
}
if strings.TrimSpace(m.FailMode) != "" {
cfg.Runtime.FailMode = m.FailMode
}
if err := cfg.Validate(); err != nil {
return err
}
led, err := ledger.Open(m.LedgerDSN, cfg.Ledger.Enabled, m.logger)
if err != nil {
return fmt.Errorf("open ledger: %w", err)
}
engine, err := policy.NewEngine(cfg)
if err != nil {
_ = led.Close()
return fmt.Errorf("compile policy: %w", err)
}
signer, err := receipt.NewSigner(cfg.Receipts)
if err != nil {
_ = led.Close()
return fmt.Errorf("load receipt signer: %w", err)
}
if err := m.setupRobots(cfg); err != nil {
_ = led.Close()
return err
}
m.config = cfg
m.bots = bot.NewIdentifier(cfg.Bots)
m.verifier = verify.NewService(cfg.Bots, m.logger)
m.policy = engine
m.ledger = led
m.limiter = ratelimit.New()
m.signer = signer
// Start background ip_ranges refreshers. They warm the caches without
// blocking startup; until warm, the request path uses an inline fetch.
m.verifier.Start()
m.logger.Info("crawlwall provisioned",
zap.String("version", version.Version),
zap.String("policy_file", m.PolicyFile),
zap.String("ledger_dsn", m.LedgerDSN),
zap.String("site_id", cfg.Site.ID),
zap.Int("rules", len(cfg.Rules)),
zap.Int("bots", len(cfg.Bots)),
)
return nil
}
// setupRobots renders robots.txt once, when the policy asks the handler to
// serve it. Rendering here rather than per request is safe because the policy
// cannot change without a reload, and a reload re-provisions the module, which
// is the whole point: the advisory file cannot go stale relative to the rules
// being enforced.
func (m *Crawlwall) setupRobots(cfg *config.Config) error {
if !cfg.Robots.Serve {
return nil
}
generated, err := robots.Generate(cfg)
if err != nil {
return fmt.Errorf("generate robots.txt: %w", err)
}
m.robotsTxt = []byte(generated.Body)
for _, warning := range generated.Warnings {
m.logger.Warn("crawlwall robots.txt cannot express a policy rule",
zap.String("detail", warning),
)
}
return nil
}
func (m *Crawlwall) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
start := time.Now()
remoteIP := remoteIPFromRequest(r)
identifiedBot := m.bots.Identify(r.UserAgent())
// Only GET and HEAD are answered here; anything else at this path is not a
// crawler reading policy, so it goes through normal handling.
if m.robotsTxt != nil && r.URL.Path == robotsPath && (r.Method == http.MethodGet || r.Method == http.MethodHead) {
m.serveRobots(w, r, start, remoteIP, identifiedBot)
return nil
}
verification, verifyErr := m.verifier.Verify(r.Context(), verify.Input{
Bot: identifiedBot,
RemoteIP: remoteIP,
Headers: r.Header,
})
// observe and shadow are non-enforcing modes; only enforce may affect
// real traffic, including the verifier fail-closed path below.
enforce := m.config.Site.Mode == config.SiteModeEnforce
if verifyErr != nil {
m.logger.Warn("crawlwall verifier error",
zap.String("bot_id", identifiedBot.ID),
zap.String("remote_ip", remoteIP.String()),
zap.Error(verifyErr),
)
if enforce && m.config.Runtime.FailMode == config.FailModeBlock {
event := ledger.EventFromRequest(start, r, remoteIP, identifiedBot, verification, m.policy.DefaultDecision(), m.config.Site.ID)
event.Action = string(config.ActionBlock)
event.ActionReason = "verification_failed"
event.RuleID = "runtime.verifier_error"
event.Status = http.StatusServiceUnavailable
event.Enforced = true
event.DurationMS = time.Since(start).Milliseconds()
m.writeLedgerAndReceipt(r.Context(), &event)
http.Error(w, "crawlwall verifier unavailable", http.StatusServiceUnavailable)
return nil
}
}
input := policy.Input{
Bot: policy.BotInput{
ID: identifiedBot.ID,
Name: identifiedBot.Name,
Class: identifiedBot.Class,
Claimed: identifiedBot.Claimed,
Verified: verification.Verified,
Operator: identifiedBot.Operator,
},
Request: policy.RequestInput{
Host: r.Host,
Method: r.Method,
Path: r.URL.Path,
Query: r.URL.RawQuery,
IP: remoteIP.String(),
UserAgent: r.UserAgent(),
Headers: headersToMap(r.Header),
},
Site: m.policy.SiteInput(),
Sets: m.policy.SetsInput(),
Labels: m.policy.LabelsInput(identifiedBot, r),
}
decision, evalErr := m.policy.Evaluate(input)
if evalErr != nil {
m.logger.Warn("crawlwall policy evaluation error",
zap.String("bot_id", identifiedBot.ID),
zap.String("remote_ip", remoteIP.String()),
zap.Error(evalErr),
)
decision = m.policy.EvaluationErrorDecision(m.config.Runtime.FailMode)
}
if decision.Action.Type == config.ActionRateLimit && decision.Action.Limit != nil {
decision.Action.Limit.ResolvedKey = policy.ResolvePath(input.Vars(), decision.Action.Limit.Key)
}
event := ledger.EventFromRequest(start, r, remoteIP, identifiedBot, verification, decision, m.config.Site.ID)
switch decision.Action.Type {
case config.ActionBlock:
if enforce {
status := decision.Action.Status
if status == 0 {
status = http.StatusForbidden
}
event.Status = status
event.Enforced = true
event.DurationMS = time.Since(start).Milliseconds()
m.writeLedgerAndReceipt(r.Context(), &event)
http.Error(w, decision.Action.Reason, status)
return nil
}
case config.ActionRateLimit:
// The limiter runs in shadow mode too. Its whole purpose is to answer
// "what would enforcing do", and skipping it would report every
// over-limit request as allowed.
if decision.Action.Limit != nil && !m.limiter.Allow(decision.Action.Limit.ResolvedKey, decision.Action.Limit.RPM) {
event.Action = actionRateLimitExceeded
event.ActionReason = actionRateLimitExceeded
if enforce {
event.Status = http.StatusTooManyRequests
event.Enforced = true
event.DurationMS = time.Since(start).Milliseconds()
m.writeLedgerAndReceipt(r.Context(), &event)
w.Header().Set("Retry-After", retryAfterSeconds(decision.Action.Limit.RPM))
http.Error(w, "rate limited by crawlwall", http.StatusTooManyRequests)
return nil
}
}
}
cw := caddyhttp.NewResponseRecorder(w, nil, nil)
err := next.ServeHTTP(cw, r)
status := cw.Status()
if status == 0 {
status = http.StatusOK
}
event.Status = status
event.BytesSent = int64(cw.Size())
event.DurationMS = time.Since(start).Milliseconds()
m.writeLedgerAndReceipt(r.Context(), &event)
return err
}
// serveRobots answers /robots.txt from the policy the edge is enforcing.
//
// It runs before verification and before policy evaluation on purpose. A
// crawler that cannot read robots.txt assumes everything is fetchable, so
// blocking this one path is self-defeating; serving it early also means a
// robots.txt fetch never triggers a DNS lookup. The fetch is still recorded,
// because knowing which crawlers read the file is useful signal.
func (m *Crawlwall) serveRobots(w http.ResponseWriter, r *http.Request, start time.Time, remoteIP net.IP, identifiedBot bot.Identified) {
verification := verify.Result{Type: "none", Reason: "robots_txt"}
decision := policy.Decision{
RuleID: "runtime.robots_txt",
Action: config.Action{Type: config.ActionAllow, Reason: "robots_txt"},
}
event := ledger.EventFromRequest(start, r, remoteIP, identifiedBot, verification, decision, m.config.Site.ID)
event.Status = http.StatusOK
event.BytesSent = int64(len(m.robotsTxt))
event.DurationMS = time.Since(start).Milliseconds()
m.writeLedgerAndReceipt(r.Context(), &event)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Length", strconv.Itoa(len(m.robotsTxt)))
w.WriteHeader(http.StatusOK)
if r.Method != http.MethodHead {
_, _ = w.Write(m.robotsTxt)
}
}
// retryAfterSeconds is how long a limited client should wait for its next
// token, rounded up so a compliant crawler does not come back early.
func retryAfterSeconds(rpm int) string {
seconds := 1
if rpm > 0 && rpm < 60 {
seconds = (60 + rpm - 1) / rpm
}
return strconv.Itoa(seconds)
}
func (m *Crawlwall) Cleanup() error {
if m.verifier != nil {
m.verifier.Stop()
}
if m.ledger != nil {
return m.ledger.Close()
}
return nil
}
func (m *Crawlwall) writeLedgerAndReceipt(ctx context.Context, event *ledger.Event) {
if m.ledger == nil {
return
}
if m.signer.Enabled() && (event.Action == string(config.ActionAllowMetered) || event.ReceiptRequested) {
envelope, err := m.signer.Sign(event.ReceiptPayload())
if err != nil {
m.logger.Warn("crawlwall receipt signing failed", zap.Error(err))
} else {
event.ReceiptID = envelope.ReceiptID
event.ReceiptSignature = envelope.Signature
}
}
// The audit write must outlive the request. A crawler that hangs up
// mid-response is exactly the traffic worth recording, and inheriting the
// request's cancellation would drop that event.
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), ledgerWriteTimeout)
defer cancel()
if err := m.ledger.WriteEvent(ctx, *event); err != nil {
m.logger.Warn("crawlwall ledger write failed", zap.Error(err))
}
}
func remoteIPFromRequest(r *http.Request) net.IP {
if clientIP, ok := caddyhttp.GetVar(r.Context(), caddyhttp.ClientIPVarKey).(string); ok {
if ip := parseIP(clientIP); ip != nil {
return ip
}
}
if ip := parseIP(r.RemoteAddr); ip != nil {
return ip
}
return net.IPv4zero
}
func parseIP(value string) net.IP {
host := strings.TrimSpace(value)
if host == "" {
return nil
}
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
host = parsedHost
}
ip := net.ParseIP(strings.Trim(host, "[]"))
if ip == nil {
return nil
}
return ip
}
func headersToMap(headers http.Header) map[string]string {
out := make(map[string]string, len(headers))
for key, values := range headers {
out[strings.ToLower(key)] = strings.Join(values, ", ")
}
return out
}
var (
_ caddy.Provisioner = (*Crawlwall)(nil)
_ caddy.CleanerUpper = (*Crawlwall)(nil)
_ caddyhttp.MiddlewareHandler = (*Crawlwall)(nil)
)