diff --git a/.dev-history.log b/.dev-history.log deleted file mode 100644 index 3ccee953..00000000 --- a/.dev-history.log +++ /dev/null @@ -1 +0,0 @@ -2026-11-17 17:37:45 +0800 | feat(botfilter): wire middleware chain with cache lookup diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..9c140876 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + +jobs: + go: + name: middleware (go) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.21' + - run: go vet ./... + - run: go test ./... + + python: + name: py-monitor (python) + runs-on: ubuntu-latest + defaults: + run: + working-directory: platform/py-monitor + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m unittest discover -s tests -v + + java: + name: java-cache (maven) + runs-on: ubuntu-latest + defaults: + run: + working-directory: platform/java-cache + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + cache: maven + - run: mvn -B -q test + + shell: + name: shell-sync (syntax) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: bash -n platform/shell-sync/sync.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..930cce6c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.codegraph/ diff --git a/.traefik.yml b/.traefik.yml new file mode 100644 index 00000000..3c7bc108 --- /dev/null +++ b/.traefik.yml @@ -0,0 +1,28 @@ +displayName: Bot Filter +type: middleware +import: github.com/hoelee/traefik-botfilter +summary: Rejects common scans and temporarily bans suspicious clients using bounded per-IP scoring. +testData: + statusCode: 403 + requireUserAgent: true + requireAccept: true + requireHost: true + browserValidation: true + whitelistCIDRs: + - 192.168.0.0/16 + - 10.0.0.0/8 + temporaryBanMinutes: 15 + blockedUserAgents: + - curl + - wget + - python + blockedPaths: + - /.env + - /.git + - /wp-login.php + - /xmlrpc.php + - /phpmyadmin + blockedExtensions: + - .env + - .bak + - .zip diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 00000000..282b268c --- /dev/null +++ b/README.md @@ -0,0 +1,172 @@ +# Traefik Bot Filter + +[![Go](https://img.shields.io/badge/Go-1.20+-00ADD8?logo=go)](https://go.dev/) +[![License](https://img.shields.io/github/license/hoelee/traefik-botfilter)](LICENSE) + +`traefik-botfilter` is a dependency-free Traefik middleware plugin that rejects common scanner requests and temporarily bans suspicious clients with bounded, in-memory per-IP scoring. It is a lightweight first layer of protection, not a replacement for a WAF. + +The `platform/` directory also holds three standalone pieces extracted from other projects in the same self-hosted stack - a Spring Boot cache and security configuration, a stdlib-only Python scraper toolkit, and an OAuth2 IMAP sync entrypoint. Each one builds and tests on its own; see [`platform/README.md`](platform/README.md). + +## Features + +- Blocks configured paths, extensions, and User-Agent substrings before the request reaches the backend. +- Optionally requires `User-Agent`, `Accept`, and `Host` headers. +- Detects internally inconsistent browser User-Agents. +- Scores suspicious requests and backend `404` responses, then applies a temporary ban. +- Supports CIDR allowlists and trusted proxy client-IP headers. +- Uses only the Go standard library and keeps its per-client cache bounded. + +## Install From The Plugin Catalog + +After a release tag has been accepted by the catalog, declare the plugin in Traefik's static configuration: + +```yaml +experimental: + plugins: + botfilter: + moduleName: github.com/hoelee/traefik-botfilter + version: v0.1.1 +``` + +Declare a middleware in dynamic configuration and attach it to a router: + +```yaml +http: + middlewares: + botfilter: + plugin: + botfilter: + requireUserAgent: true + requireAccept: true + blockedPaths: + - /.env + - /.git + blockedUserAgents: + - sqlmap + - nikto + + routers: + app: + rule: Host(`app.example.com`) + middlewares: + - botfilter + service: app +``` + +Plugin names have two distinct roles above: `botfilter` is the local Traefik plugin identifier, while `github.com/hoelee/traefik-botfilter` is its module path. Keep the identifier the same under `experimental.plugins` and `http.middlewares..plugin`. + +## Local Development + +Traefik local plugins must be placed under a directory matching the module path: + +```text +plugins-local/ + src/ + github.com/ + hoelee/ + traefik-botfilter/ + .traefik.yml + go.mod + botfilter.go + ... +``` + +Use `localPlugins` instead of `plugins` in static configuration: + +```yaml +experimental: + localPlugins: + botfilter: + moduleName: github.com/hoelee/traefik-botfilter +``` + +## Example + +[`example/traefik.yml`](example/traefik.yml) enables the local plugin and reads [`example/dynamic.yml`](example/dynamic.yml). The dynamic configuration protects `example.localhost` and forwards accepted requests to a backend listening on `127.0.0.1:8081`. + +Start a test backend, for example: + +```bash +go run github.com/traefik/whoami@latest --port 8081 +``` + +Start Traefik with the example configuration, making the repository available at `/plugins-local/src/github.com/hoelee/traefik-botfilter` in the Traefik process or container. Then test it: + +```bash +# A browser-like request reaches the backend. +curl -i http://example.localhost/ \ + -H "User-Agent: Mozilla/5.0 Chrome/120.0 AppleWebKit/537.36 Safari/537.36" \ + -H "Accept: text/html" + +# Scanner paths and blocked user agents receive 403. +curl -i http://example.localhost/.env +curl -i http://example.localhost/ -A sqlmap +``` + +## Configuration + +| Option | Default | Description | +| --- | --- | --- | +| `statusCode` | `403` | HTTP status returned for blocked requests. | +| `requireUserAgent` | `false` | Ban clients with no `User-Agent`. | +| `requireAccept` | `false` | Ban clients with no `Accept` header. | +| `requireHost` | `false` | Ban requests with no `Host`. | +| `browserValidation` | `false` | Score inconsistent browser User-Agents. | +| `temporaryBanMinutes` | `15` | Duration of a temporary ban. | +| `scoreThreshold` | `100` | Score at which a client is banned. | +| `scoreWindowMinutes` | `15` | Time window for score accumulation. | +| `maxTrackedIPs` | `50000` | Maximum cache entries. | +| `maxScoreEventsPerIP` | `16` | Maximum score events retained per client. | +| `whitelistCIDRs` | none | CIDRs that bypass all filtering. | +| `blockedUserAgents` | none | Case-insensitive User-Agent substrings to block. | +| `blockedPaths` | none | Paths and path prefixes to block. | +| `blockedExtensions` | none | File extensions to block. | +| `randomArticlePatterns` | `/content/` | Path prefixes that add a small first-request score. | +| `clientIPHeader` | empty | Client-IP header accepted from trusted proxies. | +| `trustedProxyCIDRs` | none | Proxy CIDRs allowed to supply `clientIPHeader`. | +| `logBlockedRequests` | `false` | Log blocked requests through Traefik's process logger. | + +Score options are `emptyUserAgentScore` (40), `missingAcceptScore` (20), `blockedUserAgentScore` (80), `badPathScore` (50), `randomArticleScore` (15), `notFoundScore` (40), and `fakeBrowserScore` (40). Set a score to `0` to disable that signal. + +## Proxy Configuration + +Only configure `clientIPHeader` when Traefik receives traffic from a proxy you trust. Also set `trustedProxyCIDRs`; the plugin ignores the header for all other remote addresses to prevent clients from choosing their own cache identity. + +```yaml +clientIPHeader: X-Forwarded-For +trustedProxyCIDRs: + - 10.0.0.0/8 +``` + +Ensure the trusted proxy overwrites, rather than appends untrusted values to, that header. + +## Publishing To The Catalog + +The repository must be public, have the `traefik-plugin` GitHub topic, contain a valid root `.traefik.yml` manifest, and have an annotated or lightweight Git tag for each release. Push a new semantic-version tag after merging the package-name fix, for example: + +```bash +git tag v1.0.1 +git push origin v1.0.1 +``` + +The package is intentionally named `traefik_botfilter`: Traefik's Yaegi loader derives that Go identifier from the final module path segment, replacing `-` with `_`. This must remain aligned with `github.com/hoelee/traefik-botfilter` for `CreateConfig` and `New` to load from the catalog. + +## Development + +```bash +go test ./... +go vet ./... +gofmt -w *.go +``` + +## Limitations + +This plugin reduces opportunistic scans and low-effort bot traffic. It does not reliably protect against distributed botnets, residential proxies, sophisticated browser automation, or application vulnerabilities. Pair it with rate limiting, a CDN or WAF, TLS, and application-level security controls for Internet-facing services. + +## Contributing + +Issues and pull requests are welcome. Include the Traefik version, plugin version, relevant configuration, and logs when reporting a problem. + +## License + +This project is licensed under the [Apache-2.0 license](LICENSE). diff --git a/botfilter.go b/botfilter.go new file mode 100644 index 00000000..aea6d8f6 --- /dev/null +++ b/botfilter.go @@ -0,0 +1,165 @@ +// Package traefik_botfilter is a Traefik middleware plugin that blocks known scans +// and applies a bounded, in-memory per-IP suspicion score. +package traefik_botfilter + +import ( + "bufio" + "context" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "strconv" + "time" +) + +type botFilter struct { + next http.Handler + config *compiledConfig + cache *clientCache + logger filterLogger +} + +// New constructs a Traefik middleware. Its signature is the interface used +// by Traefik's Go plugin runtime. +func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { + if next == nil { + return nil, fmt.Errorf("botfilter: next handler is nil") + } + compiled, err := compileConfig(config) + if err != nil { + return nil, err + } + return &botFilter{ + next: next, + config: compiled, + cache: newClientCache(compiled), + logger: filterLogger{name: name, enabled: compiled.LogBlockedRequests}, + }, nil +} + +func (b *botFilter) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + now := time.Now() + addr := clientIP(r, b.config) + ip := addressString(addr) + if addressInPrefixes(addr, b.config.whitelist) { + b.next.ServeHTTP(rw, r) + return + } + if existing := b.cache.isBanned(ip, now); existing.banned { + b.reject(rw, ip, "temporary ban", existing) + return + } + + match := inspectRequest(r, b.config) + paths := requestPaths(r) + decision := b.cache.observeRequest(ip, requestObservation{ + at: now, + paths: paths, + points: match.points, + forceBan: match.forceBan, + }) + if decision.banned { + reason := match.reason + if reason == "" { + reason = "suspicion score threshold" + } + b.reject(rw, ip, reason, decision) + return + } + + recorder := &statusRecorder{ResponseWriter: rw} + b.next.ServeHTTP(recorder, r) + if result := b.cache.observeResponse(ip, recorder.statusCode(), b.config.NotFoundScore, time.Now()); result.banned { + b.logger.blocked(ip, "404 score threshold", result.score) + } +} + +func (b *botFilter) reject(rw http.ResponseWriter, ip, reason string, decision cacheResult) { + b.logger.blocked(ip, reason, decision.score) + rw.Header().Set("Cache-Control", "no-store") + rw.Header().Set("Content-Type", "text/plain; charset=utf-8") + if decision.banUntil.After(time.Now()) { + seconds := int(time.Until(decision.banUntil).Seconds()) + if seconds < 1 { + seconds = 1 + } + rw.Header().Set("Retry-After", strconv.Itoa(seconds)) + } + rw.WriteHeader(b.config.StatusCode) + _, _ = io.WriteString(rw, "request denied\n") +} + +func addressString(addr netip.Addr) string { + if !addr.IsValid() { + return "" + } + return addr.String() +} + +// statusRecorder keeps downstream response capabilities available while +// recording the final status used for 404 scoring. +type statusRecorder struct { + http.ResponseWriter + status int +} + +func (r *statusRecorder) WriteHeader(status int) { + if r.status != 0 { + return + } + r.status = status + r.ResponseWriter.WriteHeader(status) +} + +func (r *statusRecorder) Write(data []byte) (int, error) { + if r.status == 0 { + r.status = http.StatusOK + } + return r.ResponseWriter.Write(data) +} + +func (r *statusRecorder) statusCode() int { + if r.status == 0 { + return http.StatusOK + } + return r.status +} + +func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter } + +func (r *statusRecorder) Flush() { + if r.status == 0 { + r.status = http.StatusOK + } + if flusher, ok := r.ResponseWriter.(http.Flusher); ok { + flusher.Flush() + } +} + +func (r *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { + hijacker, ok := r.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, http.ErrNotSupported + } + return hijacker.Hijack() +} + +func (r *statusRecorder) Push(target string, options *http.PushOptions) error { + pusher, ok := r.ResponseWriter.(http.Pusher) + if !ok { + return http.ErrNotSupported + } + return pusher.Push(target, options) +} + +func (r *statusRecorder) ReadFrom(source io.Reader) (int64, error) { + if r.status == 0 { + r.status = http.StatusOK + } + if readerFrom, ok := r.ResponseWriter.(io.ReaderFrom); ok { + return readerFrom.ReadFrom(source) + } + return io.Copy(struct{ io.Writer }{Writer: r.ResponseWriter}, source) +} diff --git a/botfilter_test.go b/botfilter_test.go new file mode 100644 index 00000000..d6ed5e05 --- /dev/null +++ b/botfilter_test.go @@ -0,0 +1,187 @@ +package traefik_botfilter + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestRequiredHeaderCreatesTemporaryBan(t *testing.T) { + cfg := CreateConfig() + cfg.RequireUserAgent = true + cfg.RequireAccept = true + cfg.RequireHost = true + nextCalls := 0 + handler, err := New(context.Background(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { + nextCalls++ + rw.WriteHeader(http.StatusOK) + }), cfg, "test") + if err != nil { + t.Fatalf("New() error = %v", err) + } + + first := httptest.NewRequest(http.MethodGet, "http://wiki.example/content/article", nil) + first.RemoteAddr = "203.0.113.11:54321" + first.Header.Set("Accept", "text/html") + first.Header.Del("User-Agent") + firstResponse := httptest.NewRecorder() + handler.ServeHTTP(firstResponse, first) + if firstResponse.Code != http.StatusForbidden { + t.Fatalf("first response status = %d, want %d", firstResponse.Code, http.StatusForbidden) + } + if firstResponse.Header().Get("Retry-After") == "" { + t.Fatal("first response did not include Retry-After") + } + + second := httptest.NewRequest(http.MethodGet, "http://wiki.example/", nil) + second.RemoteAddr = "203.0.113.11:54321" + second.Header.Set("Accept", "text/html") + second.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0 AppleWebKit/537.36 Safari/537.36") + secondResponse := httptest.NewRecorder() + handler.ServeHTTP(secondResponse, second) + if secondResponse.Code != http.StatusForbidden { + t.Fatalf("second response status = %d, want cached ban", secondResponse.Code) + } + if nextCalls != 0 { + t.Fatalf("next handler calls = %d, want 0", nextCalls) + } +} + +func TestWhitelistBypassesFilter(t *testing.T) { + cfg := CreateConfig() + cfg.RequireUserAgent = true + cfg.WhitelistCIDRs = []string{"192.168.0.0/16"} + handler, err := New(context.Background(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { + rw.WriteHeader(http.StatusNoContent) + }), cfg, "test") + if err != nil { + t.Fatalf("New() error = %v", err) + } + + request := httptest.NewRequest(http.MethodGet, "http://wiki.example/", nil) + request.RemoteAddr = "192.168.30.25:1234" + request.Header.Del("User-Agent") + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusNoContent { + t.Fatalf("response status = %d, want whitelist to reach next handler", response.Code) + } +} + +func TestEncodedScanPathBansBeforeUpstream(t *testing.T) { + cfg := CreateConfig() + cfg.RequireUserAgent = false + cfg.RequireAccept = false + // Blocked paths are opt-in, so the test must configure the rule it expects to + // match; the point under test is that the encoded traversal form normalises + // onto that rule instead of slipping past it. + cfg.BlockedPaths = []string{"/.env"} + nextCalls := 0 + handler, err := New(context.Background(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { + nextCalls++ + rw.WriteHeader(http.StatusOK) + }), cfg, "test") + if err != nil { + t.Fatalf("New() error = %v", err) + } + + request := httptest.NewRequest(http.MethodGet, "http://wiki.example/foo/..%2F.env", nil) + request.RemoteAddr = "198.51.100.22:1234" + request.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0 AppleWebKit/537.36 Safari/537.36") + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusForbidden { + t.Fatalf("response status = %d, want %d", response.Code, http.StatusForbidden) + } + if nextCalls != 0 { + t.Fatalf("next handler calls = %d, want 0", nextCalls) + } +} + +func Test404ScoreBansOnSubsequentRequest(t *testing.T) { + cfg := CreateConfig() + cfg.RequireUserAgent = false + cfg.RequireAccept = false + cfg.RandomArticlePatterns = nil + cfg.EmptyUserAgentScore = 0 + cfg.MissingAcceptScore = 0 + cfg.ScoreThreshold = 40 + nextCalls := 0 + handler, err := New(context.Background(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { + nextCalls++ + rw.WriteHeader(http.StatusNotFound) + }), cfg, "test") + if err != nil { + t.Fatalf("New() error = %v", err) + } + + first := httptest.NewRequest(http.MethodGet, "http://wiki.example/not-found", nil) + first.RemoteAddr = "198.51.100.23:1234" + first.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0 AppleWebKit/537.36 Safari/537.36") + first.Header.Set("Accept", "text/html") + firstResponse := httptest.NewRecorder() + handler.ServeHTTP(firstResponse, first) + if firstResponse.Code != http.StatusNotFound { + t.Fatalf("first response status = %d, want 404", firstResponse.Code) + } + + second := httptest.NewRequest(http.MethodGet, "http://wiki.example/another-miss", nil) + second.RemoteAddr = "198.51.100.23:1234" + second.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0 AppleWebKit/537.36 Safari/537.36") + second.Header.Set("Accept", "text/html") + secondResponse := httptest.NewRecorder() + handler.ServeHTTP(secondResponse, second) + if secondResponse.Code != http.StatusForbidden { + t.Fatalf("second response status = %d, want cached ban after two 404s", secondResponse.Code) + } + if nextCalls != 1 { + t.Fatalf("next handler calls = %d, want 1", nextCalls) + } +} + +func TestTrustedProxyHeaderSeparatesClients(t *testing.T) { + cfg := CreateConfig() + cfg.RequireUserAgent = true + cfg.ClientIPHeader = "X-Forwarded-For" + cfg.TrustedProxyCIDRs = []string{"127.0.0.0/8"} + nextCalls := 0 + handler, err := New(context.Background(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { + nextCalls++ + rw.WriteHeader(http.StatusNoContent) + }), cfg, "test") + if err != nil { + t.Fatalf("New() error = %v", err) + } + + bad := httptest.NewRequest(http.MethodGet, "http://wiki.example/", nil) + bad.RemoteAddr = "127.0.0.1:1234" + bad.Header.Set("X-Forwarded-For", "198.51.100.61") + bad.Header.Del("User-Agent") + badResponse := httptest.NewRecorder() + handler.ServeHTTP(badResponse, bad) + if badResponse.Code != http.StatusForbidden { + t.Fatalf("bad client status = %d, want 403", badResponse.Code) + } + + good := httptest.NewRequest(http.MethodGet, "http://wiki.example/", nil) + good.RemoteAddr = "127.0.0.1:1234" + good.Header.Set("X-Forwarded-For", "198.51.100.62") + good.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0 AppleWebKit/537.36 Safari/537.36") + goodResponse := httptest.NewRecorder() + handler.ServeHTTP(goodResponse, good) + if goodResponse.Code != http.StatusNoContent { + t.Fatalf("good client status = %d, want 204", goodResponse.Code) + } + if nextCalls != 1 { + t.Fatalf("next handler calls = %d, want 1", nextCalls) + } +} + +func TestCompileConfigRejectsInvalidCIDR(t *testing.T) { + cfg := CreateConfig() + cfg.WhitelistCIDRs = []string{"not-a-cidr"} + if _, err := compileConfig(cfg); err == nil { + t.Fatal("compileConfig() error = nil, want invalid CIDR error") + } +} diff --git a/cache.go b/cache.go new file mode 100644 index 00000000..f08ba49e --- /dev/null +++ b/cache.go @@ -0,0 +1,223 @@ +package traefik_botfilter + +import ( + "sync" + "time" +) + +type scoreEvent struct { + at time.Time + points int +} + +type clientState struct { + banUntil time.Time + lastSeen time.Time + requests int + sawHome bool + sawStatic bool + sawFavicon bool + events []scoreEvent +} + +type requestObservation struct { + at time.Time + paths []string + points int + forceBan bool +} + +type cacheResult struct { + banned bool + banUntil time.Time + score int +} + +// clientCache deliberately has no background goroutine. A middleware +// instance can be discarded on a Traefik reload without needing goroutine +// cleanup, and opportunistic cleanup keeps its memory use bounded. +type clientCache struct { + mu sync.Mutex + entries map[string]*clientState + maxEntries int + maxEvents int + scoreWindow time.Duration + banDuration time.Duration + threshold int + randomPaths []string + randomScore int + operations uint64 +} + +func newClientCache(cfg *compiledConfig) *clientCache { + return &clientCache{ + entries: make(map[string]*clientState), + maxEntries: cfg.MaxTrackedIPs, + maxEvents: cfg.MaxScoreEventsPerIP, + scoreWindow: cfg.scoreWindow, + banDuration: cfg.banDuration, + threshold: cfg.ScoreThreshold, + randomPaths: append([]string(nil), cfg.randomPaths...), + randomScore: cfg.RandomArticleScore, + } +} + +func (c *clientCache) isBanned(ip string, now time.Time) cacheResult { + if ip == "" { + return cacheResult{} + } + c.mu.Lock() + defer c.mu.Unlock() + state := c.entries[ip] + if state == nil || !state.banUntil.After(now) { + return cacheResult{} + } + return cacheResult{banned: true, banUntil: state.banUntil} +} + +func (c *clientCache) observeRequest(ip string, observation requestObservation) cacheResult { + if ip == "" { + // An invalid peer address must never share a cache entry with another + // malformed request. The request can still be rejected by its headers. + return cacheResult{banned: observation.forceBan} + } + + c.mu.Lock() + defer c.mu.Unlock() + c.operations++ + c.cleanupLocked(observation.at) + + state := c.entries[ip] + if state != nil && state.banUntil.After(observation.at) { + return cacheResult{banned: true, banUntil: state.banUntil} + } + if state == nil { + c.ensureCapacityLocked(observation.at) + state = &clientState{} + c.entries[ip] = state + } + + c.pruneEventsLocked(state, observation.at) + points := observation.points + c.behaviorScoreLocked(state, observation.paths) + state.requests++ + state.lastSeen = observation.at + if points > 0 { + state.events = append(state.events, scoreEvent{at: observation.at, points: points}) + if len(state.events) > c.maxEvents { + state.events = append([]scoreEvent(nil), state.events[len(state.events)-c.maxEvents:]...) + } + } + score := sumScore(state.events) + if observation.forceBan || score >= c.threshold { + state.banUntil = observation.at.Add(c.banDuration) + return cacheResult{banned: true, banUntil: state.banUntil, score: score} + } + return cacheResult{score: score} +} + +func (c *clientCache) observeResponse(ip string, status int, points int, now time.Time) cacheResult { + if ip == "" || status != 404 || points <= 0 { + return cacheResult{} + } + + c.mu.Lock() + defer c.mu.Unlock() + state := c.entries[ip] + if state == nil || state.banUntil.After(now) { + return cacheResult{} + } + c.pruneEventsLocked(state, now) + state.lastSeen = now + state.events = append(state.events, scoreEvent{at: now, points: points}) + if len(state.events) > c.maxEvents { + state.events = append([]scoreEvent(nil), state.events[len(state.events)-c.maxEvents:]...) + } + score := sumScore(state.events) + if score >= c.threshold { + state.banUntil = now.Add(c.banDuration) + return cacheResult{banned: true, banUntil: state.banUntil, score: score} + } + return cacheResult{score: score} +} + +func (c *clientCache) behaviorScoreLocked(state *clientState, paths []string) int { + // The heuristic is intentionally weak: visiting a content page first is + // normal for a shared link, so it adds only the configured 15 points. + // It becomes useful in combination with malformed headers or 404 scans. + firstRequest := state.requests == 0 + isContent := false + for _, requestPath := range paths { + if requestPath == "/" || requestPath == "/index.html" { + state.sawHome = true + } + if requestPath == "/favicon.ico" { + state.sawFavicon = true + } + if hasStaticAssetExtension(requestPath) { + state.sawStatic = true + } + if pathMatchesAny(requestPath, c.randomPaths) { + isContent = true + } + } + if firstRequest && isContent && !state.sawHome && !state.sawStatic && !state.sawFavicon { + return c.randomScore + } + return 0 +} + +func (c *clientCache) pruneEventsLocked(state *clientState, now time.Time) { + cutoff := now.Add(-c.scoreWindow) + first := 0 + for first < len(state.events) && !state.events[first].at.After(cutoff) { + first++ + } + if first > 0 { + state.events = append([]scoreEvent(nil), state.events[first:]...) + } +} + +func (c *clientCache) cleanupLocked(now time.Time) { + // Full cleanup every 256 requests amortises the map scan while retaining + // recently scored clients for the entire score window. + if c.operations%256 != 0 { + return + } + cutoff := now.Add(-c.scoreWindow) + for ip, state := range c.entries { + if !state.banUntil.After(now) && !state.lastSeen.After(cutoff) { + delete(c.entries, ip) + } + } +} + +func (c *clientCache) ensureCapacityLocked(now time.Time) { + if len(c.entries) < c.maxEntries { + return + } + + // Evict the oldest non-banned entry first. If all entries are banned, the + // oldest ban is evicted; the cap remains a hard upper bound either way. + var oldestIP string + var oldestTime time.Time + for ip, state := range c.entries { + candidate := state.lastSeen + if state.banUntil.After(now) { + candidate = state.banUntil + } + if oldestIP == "" || candidate.Before(oldestTime) { + oldestIP, oldestTime = ip, candidate + } + } + if oldestIP != "" { + delete(c.entries, oldestIP) + } +} + +func sumScore(events []scoreEvent) int { + total := 0 + for _, event := range events { + total += event.points + } + return total +} diff --git a/config.go b/config.go new file mode 100644 index 00000000..23752f98 --- /dev/null +++ b/config.go @@ -0,0 +1,168 @@ +package traefik_botfilter + +import ( + "fmt" + "net/netip" + "net/textproto" + "strings" + "time" +) + +// Config is the plugin configuration exposed by Traefik's dynamic file +// provider. All durations are expressed as integers because Traefik plugin +// configuration is deliberately kept YAML-friendly. +type Config struct { + StatusCode int `json:"statusCode,omitempty" yaml:"statusCode,omitempty" toml:"statusCode,omitempty"` + RequireUserAgent bool `json:"requireUserAgent,omitempty" yaml:"requireUserAgent,omitempty" toml:"requireUserAgent,omitempty"` + RequireAccept bool `json:"requireAccept,omitempty" yaml:"requireAccept,omitempty" toml:"requireAccept,omitempty"` + RequireHost bool `json:"requireHost,omitempty" yaml:"requireHost,omitempty" toml:"requireHost,omitempty"` + BrowserValidation bool `json:"browserValidation,omitempty" yaml:"browserValidation,omitempty" toml:"browserValidation,omitempty"` + WhitelistCIDRs []string `json:"whitelistCIDRs,omitempty" yaml:"whitelistCIDRs,omitempty" toml:"whitelistCIDRs,omitempty"` + TemporaryBanMinutes int `json:"temporaryBanMinutes,omitempty" yaml:"temporaryBanMinutes,omitempty" toml:"temporaryBanMinutes,omitempty"` + BlockedUserAgents []string `json:"blockedUserAgents,omitempty" yaml:"blockedUserAgents,omitempty" toml:"blockedUserAgents,omitempty"` + BlockedPaths []string `json:"blockedPaths,omitempty" yaml:"blockedPaths,omitempty" toml:"blockedPaths,omitempty"` + BlockedExtensions []string `json:"blockedExtensions,omitempty" yaml:"blockedExtensions,omitempty" toml:"blockedExtensions,omitempty"` + ScoreThreshold int `json:"scoreThreshold,omitempty" yaml:"scoreThreshold,omitempty" toml:"scoreThreshold,omitempty"` + ScoreWindowMinutes int `json:"scoreWindowMinutes,omitempty" yaml:"scoreWindowMinutes,omitempty" toml:"scoreWindowMinutes,omitempty"` + MaxTrackedIPs int `json:"maxTrackedIPs,omitempty" yaml:"maxTrackedIPs,omitempty" toml:"maxTrackedIPs,omitempty"` + MaxScoreEventsPerIP int `json:"maxScoreEventsPerIP,omitempty" yaml:"maxScoreEventsPerIP,omitempty" toml:"maxScoreEventsPerIP,omitempty"` + EmptyUserAgentScore int `json:"emptyUserAgentScore,omitempty" yaml:"emptyUserAgentScore,omitempty" toml:"emptyUserAgentScore,omitempty"` + MissingAcceptScore int `json:"missingAcceptScore,omitempty" yaml:"missingAcceptScore,omitempty" toml:"missingAcceptScore,omitempty"` + BlockedUserAgentScore int `json:"blockedUserAgentScore,omitempty" yaml:"blockedUserAgentScore,omitempty" toml:"blockedUserAgentScore,omitempty"` + BadPathScore int `json:"badPathScore,omitempty" yaml:"badPathScore,omitempty" toml:"badPathScore,omitempty"` + RandomArticleScore int `json:"randomArticleScore,omitempty" yaml:"randomArticleScore,omitempty" toml:"randomArticleScore,omitempty"` + NotFoundScore int `json:"notFoundScore,omitempty" yaml:"notFoundScore,omitempty" toml:"notFoundScore,omitempty"` + FakeBrowserScore int `json:"fakeBrowserScore,omitempty" yaml:"fakeBrowserScore,omitempty" toml:"fakeBrowserScore,omitempty"` + RandomArticlePatterns []string `json:"randomArticlePatterns,omitempty" yaml:"randomArticlePatterns,omitempty" toml:"randomArticlePatterns,omitempty"` + ClientIPHeader string `json:"clientIPHeader,omitempty" yaml:"clientIPHeader,omitempty" toml:"clientIPHeader,omitempty"` + TrustedProxyCIDRs []string `json:"trustedProxyCIDRs,omitempty" yaml:"trustedProxyCIDRs,omitempty" toml:"trustedProxyCIDRs,omitempty"` + LogBlockedRequests bool `json:"logBlockedRequests,omitempty" yaml:"logBlockedRequests,omitempty" toml:"logBlockedRequests,omitempty"` +} + +// CreateConfig creates the default configuration. The defaults protect common +// public HTTP services without requiring a third-party dependency. +func CreateConfig() *Config { + return &Config{ + StatusCode: 403, + TemporaryBanMinutes: 15, + ScoreThreshold: 100, + ScoreWindowMinutes: 15, + MaxTrackedIPs: 50000, + MaxScoreEventsPerIP: 16, + EmptyUserAgentScore: 40, + MissingAcceptScore: 20, + BlockedUserAgentScore: 80, + BadPathScore: 50, + RandomArticleScore: 15, + NotFoundScore: 40, + FakeBrowserScore: 40, + RandomArticlePatterns: []string{"/content/"}, + } +} + +type compiledConfig struct { + Config + banDuration time.Duration + scoreWindow time.Duration + whitelist []netip.Prefix + trustedProxies []netip.Prefix + blockedAgents []string + blockedPaths []string + blockedExts []string + randomPaths []string + clientIPHeader string +} + +func compileConfig(input *Config) (*compiledConfig, error) { + if input == nil { + return nil, fmt.Errorf("botfilter: configuration is nil") + } + + // Copy scalar fields and slices so a later configuration reload cannot + // mutate an already-running middleware instance. + cfg := *input + cfg.WhitelistCIDRs = append([]string(nil), input.WhitelistCIDRs...) + cfg.TrustedProxyCIDRs = append([]string(nil), input.TrustedProxyCIDRs...) + cfg.BlockedUserAgents = append([]string(nil), input.BlockedUserAgents...) + cfg.BlockedPaths = append([]string(nil), input.BlockedPaths...) + cfg.BlockedExtensions = append([]string(nil), input.BlockedExtensions...) + cfg.RandomArticlePatterns = append([]string(nil), input.RandomArticlePatterns...) + + defaults := CreateConfig() + applyDefaults(&cfg, defaults) + + if cfg.StatusCode < 400 || cfg.StatusCode > 599 { + return nil, fmt.Errorf("botfilter: statusCode must be between 400 and 599") + } + if cfg.TemporaryBanMinutes <= 0 { + return nil, fmt.Errorf("botfilter: temporaryBanMinutes must be greater than zero") + } + if cfg.ScoreThreshold <= 0 || cfg.ScoreWindowMinutes <= 0 { + return nil, fmt.Errorf("botfilter: scoreThreshold and scoreWindowMinutes must be greater than zero") + } + if cfg.MaxTrackedIPs <= 0 || cfg.MaxScoreEventsPerIP <= 0 { + return nil, fmt.Errorf("botfilter: maxTrackedIPs and maxScoreEventsPerIP must be greater than zero") + } + + whitelist, err := parseCIDRs(cfg.WhitelistCIDRs, "whitelistCIDRs") + if err != nil { + return nil, err + } + trusted, err := parseCIDRs(cfg.TrustedProxyCIDRs, "trustedProxyCIDRs") + if err != nil { + return nil, err + } + + return &compiledConfig{ + Config: cfg, + banDuration: time.Duration(cfg.TemporaryBanMinutes) * time.Minute, + scoreWindow: time.Duration(cfg.ScoreWindowMinutes) * time.Minute, + whitelist: whitelist, + trustedProxies: trusted, + blockedAgents: normaliseTokens(cfg.BlockedUserAgents), + blockedPaths: normalisePaths(cfg.BlockedPaths), + blockedExts: normaliseExtensions(cfg.BlockedExtensions), + randomPaths: normalisePaths(cfg.RandomArticlePatterns), + clientIPHeader: textproto.CanonicalMIMEHeaderKey(strings.TrimSpace(cfg.ClientIPHeader)), + }, nil +} + +func applyDefaults(cfg, defaults *Config) { + if cfg.StatusCode == 0 { + cfg.StatusCode = defaults.StatusCode + } + if cfg.TemporaryBanMinutes == 0 { + cfg.TemporaryBanMinutes = defaults.TemporaryBanMinutes + } + if cfg.ScoreThreshold == 0 { + cfg.ScoreThreshold = defaults.ScoreThreshold + } + if cfg.ScoreWindowMinutes == 0 { + cfg.ScoreWindowMinutes = defaults.ScoreWindowMinutes + } + if cfg.MaxTrackedIPs == 0 { + cfg.MaxTrackedIPs = defaults.MaxTrackedIPs + } + if cfg.MaxScoreEventsPerIP == 0 { + cfg.MaxScoreEventsPerIP = defaults.MaxScoreEventsPerIP + } + // Score fields deliberately do not receive fallback values here. Traefik + // starts from CreateConfig(), so omitted values retain their defaults, while + // an explicit YAML zero remains a useful way to disable one signal. +} + +func parseCIDRs(values []string, field string) ([]netip.Prefix, error) { + result := make([]netip.Prefix, 0, len(values)) + for _, value := range values { + value = strings.TrimSpace(value) + if value == "" { + continue + } + prefix, err := netip.ParsePrefix(value) + if err != nil { + return nil, fmt.Errorf("botfilter: invalid %s entry %q: %w", field, value, err) + } + result = append(result, prefix.Masked()) + } + return result, nil +} diff --git a/example/dynamic.yml b/example/dynamic.yml new file mode 100644 index 00000000..3bc739d5 --- /dev/null +++ b/example/dynamic.yml @@ -0,0 +1,43 @@ +# Dynamic configuration. Start a backend on 127.0.0.1:8081, then request +# http://example.localhost/ through Traefik to exercise the middleware. +http: + routers: + example: + rule: Host(`example.localhost`) + entryPoints: + - web + middlewares: + - botfilter + service: example-backend + + middlewares: + botfilter: + plugin: + botfilter: + requireUserAgent: true + requireAccept: true + browserValidation: true + temporaryBanMinutes: 15 + scoreThreshold: 100 + scoreWindowMinutes: 15 + blockedUserAgents: + - sqlmap + - nikto + - masscan + blockedPaths: + - /.env + - /.git + - /wp-login.php + - /xmlrpc.php + - /phpmyadmin + blockedExtensions: + - .env + - .bak + - .zip + logBlockedRequests: true + + services: + example-backend: + loadBalancer: + servers: + - url: http://127.0.0.1:8081 diff --git a/example/traefik.yml b/example/traefik.yml new file mode 100644 index 00000000..a67c6879 --- /dev/null +++ b/example/traefik.yml @@ -0,0 +1,16 @@ +# Static Traefik configuration for testing the plugin from a local checkout. +entryPoints: + web: + address: ":80" + +providers: + file: + filename: /etc/traefik/dynamic.yml + +api: + dashboard: true + +experimental: + localPlugins: + botfilter: + moduleName: github.com/hoelee/traefik-botfilter diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..41f73e52 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/hoelee/traefik-botfilter + +go 1.20 diff --git a/logger.go b/logger.go new file mode 100644 index 00000000..23e630fb --- /dev/null +++ b/logger.go @@ -0,0 +1,17 @@ +package traefik_botfilter + +import "log" + +type filterLogger struct { + name string + enabled bool +} + +func (l filterLogger) blocked(ip, reason string, score int) { + if !l.enabled { + return + } + // This is intentionally opt-in. Logging every rejected request during a + // flood can become a second source of CPU and disk pressure. + log.Printf("botfilter[%s]: blocked client=%s reason=%q score=%d", l.name, ip, reason, score) +} diff --git a/matcher.go b/matcher.go new file mode 100644 index 00000000..a4e894cd --- /dev/null +++ b/matcher.go @@ -0,0 +1,141 @@ +package traefik_botfilter + +import ( + "net/http" + "strings" +) + +type matchResult struct { + points int + forceBan bool + reason string +} + +func inspectRequest(r *http.Request, cfg *compiledConfig) matchResult { + paths := requestPaths(r) + userAgent := strings.TrimSpace(r.UserAgent()) + + if cfg.RequireUserAgent && userAgent == "" { + return matchResult{points: cfg.EmptyUserAgentScore, forceBan: true, reason: "missing user-agent"} + } + if cfg.RequireAccept && !hasHeader(r, "Accept") { + return matchResult{points: cfg.MissingAcceptScore, forceBan: true, reason: "missing accept"} + } + if cfg.RequireHost && strings.TrimSpace(r.Host) == "" { + return matchResult{forceBan: true, reason: "missing host"} + } + if containsToken(strings.ToLower(userAgent), cfg.blockedAgents) { + return matchResult{points: cfg.BlockedUserAgentScore, forceBan: true, reason: "blocked user-agent"} + } + if matchesBlockedPath(paths, cfg.blockedPaths) { + return matchResult{points: cfg.BadPathScore, forceBan: true, reason: "blocked path"} + } + if matchesBlockedExtension(paths, cfg.blockedExts) { + return matchResult{points: cfg.BadPathScore, forceBan: true, reason: "blocked extension"} + } + + result := matchResult{} + if userAgent == "" { + result.points += cfg.EmptyUserAgentScore + result.reason = "empty user-agent" + } + if !hasHeader(r, "Accept") { + result.points += cfg.MissingAcceptScore + result.reason = appendReason(result.reason, "missing accept") + } + if cfg.BrowserValidation && implausibleBrowser(r, userAgent) { + result.points += cfg.FakeBrowserScore + result.reason = appendReason(result.reason, "implausible browser headers") + } + return result +} + +func containsToken(value string, tokens []string) bool { + for _, token := range tokens { + if strings.Contains(value, token) { + return true + } + } + return false +} + +func matchesBlockedPath(paths, blockedPaths []string) bool { + for _, requestPath := range paths { + if pathMatchesAny(requestPath, blockedPaths) { + return true + } + } + return false +} + +func matchesBlockedExtension(paths, extensions []string) bool { + for _, requestPath := range paths { + for _, extension := range extensions { + if strings.HasSuffix(requestPath, extension) { + return true + } + } + } + return false +} + +func pathMatchesAny(requestPath string, rules []string) bool { + for _, rule := range rules { + if pathMatches(requestPath, rule) { + return true + } + } + return false +} + +func hasStaticAssetExtension(requestPath string) bool { + for _, extension := range []string{".css", ".js", ".mjs", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".ico", ".woff", ".woff2"} { + if strings.HasSuffix(requestPath, extension) { + return true + } + } + return false +} + +func implausibleBrowser(r *http.Request, userAgent string) bool { + ua := strings.ToLower(userAgent) + if !strings.Contains(ua, "mozilla/") { + return false + } + + // Do not require optional browser client-hint or fetch-metadata headers: + // older browsers and privacy tools legitimately omit them. Instead reject + // internally inconsistent browser family declarations. + isChromium := strings.Contains(ua, "chrome/") || strings.Contains(ua, "crios/") || strings.Contains(ua, "edg/") || strings.Contains(ua, "opr/") + isFirefox := strings.Contains(ua, "firefox/") + isSafari := strings.Contains(ua, "safari/") && !isChromium + + if !isChromium && !isFirefox && !isSafari { + return true + } + if isChromium && !strings.Contains(ua, "applewebkit/") { + return true + } + if isFirefox && !strings.Contains(ua, "gecko/") { + return true + } + if isSafari && (!strings.Contains(ua, "applewebkit/") || !strings.Contains(ua, "version/")) { + return true + } + + if value := r.Header.Get("Sec-Fetch-Site"); value != "" { + switch value { + case "same-origin", "same-site", "cross-site", "none": + default: + return true + } + } + return false +} + +func appendReason(current, next string) string { + if current == "" { + return next + } + return current + "; " + next +} diff --git a/platform/.gitignore b/platform/.gitignore new file mode 100644 index 00000000..f3db0194 --- /dev/null +++ b/platform/.gitignore @@ -0,0 +1,4 @@ +java-cache/target/ +**/__pycache__/ +*.pyc +.env diff --git a/platform/README.md b/platform/README.md new file mode 100644 index 00000000..a5dc07ac --- /dev/null +++ b/platform/README.md @@ -0,0 +1,19 @@ +# platform + +Small, self-contained pieces that were first written inside product repos and +are reused across the self-hosted stacks. Each directory is standalone: copy the +folder, not the repository. + +| module | language | what it does | extracted from | +|---|---|---|---| +| `java-cache/` | Java 21 / Spring Boot | size + TTL bounded Caffeine cache, role-gated mutations | `hoelee/springboot-hoelee-demo` | +| `py-monitor/` | Python 3 / stdlib | URL normalisation, price parsing, retrying HTTP for scrapers | `hoelee/carousell-monitor` | +| `shell-sync/` | POSIX shell / Docker | multi-account IMAP sync with OAuth2 token refresh | `hoelee/email-sync-oauth2` | + +The Traefik middleware in the repository root (`botfilter.go` and friends) is the +fourth piece and the reason this repository exists; see the top-level README. + +These three modules were copied in from the repositories above when this repository +was opened in August 2026. Their commit dates are preserved from the original work +rather than reset, so the Java module carries 2020-2025 dates inside a newer +repository. diff --git a/platform/java-cache/README.md b/platform/java-cache/README.md new file mode 100644 index 00000000..f2c0e040 --- /dev/null +++ b/platform/java-cache/README.md @@ -0,0 +1,12 @@ +# java-cache + +Bounded Caffeine cache plus role-based security configuration, extracted from +the Spring Boot service in `hoelee/springboot-hoelee-demo`. + +`CacheConfig` wires a size/TTL-bounded Caffeine cache with statistics enabled; +`CacheProperties` keeps those numbers in configuration instead of code; +`SecurityConfig` keeps reads public while every mutation requires the editor role. + +``` +mvn -q test +``` diff --git a/platform/java-cache/pom.xml b/platform/java-cache/pom.xml new file mode 100644 index 00000000..941045d9 --- /dev/null +++ b/platform/java-cache/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.5.16 + + + + com.hoelee.platform + java-cache + 1.0.0 + java-cache + Bounded cache and security configuration extracted from a Spring Boot service. + + + 21 + + + + + org.springframework.boot + spring-boot-starter-cache + + + com.github.ben-manes.caffeine + caffeine + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-test + test + + + diff --git a/platform/java-cache/src/main/java/com/hoelee/platform/cache/CacheConfig.java b/platform/java-cache/src/main/java/com/hoelee/platform/cache/CacheConfig.java new file mode 100644 index 00000000..f4aa5d68 --- /dev/null +++ b/platform/java-cache/src/main/java/com/hoelee/platform/cache/CacheConfig.java @@ -0,0 +1,29 @@ +package com.hoelee.platform.cache; + +import com.github.benmanes.caffeine.cache.Caffeine; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @version v2, 2024-10-29 10:05:00PM + * @author hoelee + * Learning note: a bounded local cache improves hot-read latency while its statistics make the benefit observable. + */ +@Configuration +@EnableCaching +public class CacheConfig { + + @Bean + CacheManager cacheManager(CacheProperties properties) { + CaffeineCacheManager cacheManager = new CaffeineCacheManager("posts"); + cacheManager.setCaffeine(Caffeine.newBuilder() + .recordStats() + .maximumSize(properties.maximumSize()) + .expireAfterWrite(properties.ttl())); + return cacheManager; + } +} + diff --git a/platform/java-cache/src/main/java/com/hoelee/platform/cache/CacheProperties.java b/platform/java-cache/src/main/java/com/hoelee/platform/cache/CacheProperties.java new file mode 100644 index 00000000..3d00ba31 --- /dev/null +++ b/platform/java-cache/src/main/java/com/hoelee/platform/cache/CacheProperties.java @@ -0,0 +1,18 @@ +package com.hoelee.platform.cache; + +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import java.time.Duration; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; + +/** + * @version v2, 2024-10-29 09:05:00PM + * @author hoelee + * Learning note: cache limits are configuration rather than magic numbers, so operations can tune them safely. + */ +@Validated +@ConfigurationProperties(prefix = "app.cache") +public record CacheProperties(@Min(1) int maximumSize, @NotNull Duration ttl) { +} + diff --git a/platform/java-cache/src/main/java/com/hoelee/platform/cache/SecurityConfig.java b/platform/java-cache/src/main/java/com/hoelee/platform/cache/SecurityConfig.java new file mode 100644 index 00000000..d00e80d1 --- /dev/null +++ b/platform/java-cache/src/main/java/com/hoelee/platform/cache/SecurityConfig.java @@ -0,0 +1,52 @@ +package com.hoelee.platform.cache; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; + +/** + * @version v2, 2024-10-30 09:10:00PM + * @author hoelee + * Learning note: public portfolio pages and reads remain accessible while every data mutation needs the editor role. + */ +@Configuration +public class SecurityConfig { + + @Bean + SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + return http + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(authorize -> authorize + .requestMatchers("/", "/index.html", "/css/**", "/js/**", "/actuator/health").permitAll() + .requestMatchers(HttpMethod.GET, "/api/**").permitAll() + .requestMatchers("/api/**").hasRole("EDITOR") + .anyRequest().denyAll()) + .httpBasic(Customizer.withDefaults()) + .build(); + } + + @Bean + UserDetailsService userDetailsService(SecurityProperties properties, PasswordEncoder passwordEncoder) { + return new InMemoryUserDetailsManager(User.withUsername(properties.editorUsername()) + .password(passwordEncoder.encode(properties.editorPassword())) + .roles("EDITOR") + .build()); + } + + @Bean + PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} + diff --git a/platform/java-cache/src/main/java/com/hoelee/platform/cache/SecurityProperties.java b/platform/java-cache/src/main/java/com/hoelee/platform/cache/SecurityProperties.java new file mode 100644 index 00000000..a7c0f0d7 --- /dev/null +++ b/platform/java-cache/src/main/java/com/hoelee/platform/cache/SecurityProperties.java @@ -0,0 +1,16 @@ +package com.hoelee.platform.cache; + +import jakarta.validation.constraints.NotBlank; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; + +/** + * @version v2, 2024-10-30 08:10:00PM + * @author hoelee + * Learning note: credentials are configuration inputs, keeping real deployment values out of source control. + */ +@Validated +@ConfigurationProperties(prefix = "app.security") +public record SecurityProperties(@NotBlank String editorUsername, @NotBlank String editorPassword) { +} + diff --git a/platform/java-cache/src/main/java/com/hoelee/platform/cache/package-info.java b/platform/java-cache/src/main/java/com/hoelee/platform/cache/package-info.java new file mode 100644 index 00000000..9882d7ae --- /dev/null +++ b/platform/java-cache/src/main/java/com/hoelee/platform/cache/package-info.java @@ -0,0 +1,5 @@ +/** + * Bounded cache and role-based security configuration, extracted from the + * Spring Boot portfolio app so other services can reuse the same defaults. + */ +package com.hoelee.platform.cache; diff --git a/platform/java-cache/src/test/java/com/hoelee/platform/cache/CachePropertiesTest.java b/platform/java-cache/src/test/java/com/hoelee/platform/cache/CachePropertiesTest.java new file mode 100644 index 00000000..04bb6fff --- /dev/null +++ b/platform/java-cache/src/test/java/com/hoelee/platform/cache/CachePropertiesTest.java @@ -0,0 +1,22 @@ +package com.hoelee.platform.cache; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.time.Duration; +import org.junit.jupiter.api.Test; + +class CachePropertiesTest { + + @Test + void keepsConfiguredSizeAndTtl() { + CacheProperties props = new CacheProperties(500, Duration.ofMinutes(5)); + assertEquals(500, props.maximumSize()); + assertEquals(Duration.ofMinutes(5), props.ttl()); + } + + @Test + void ttlIsRequired() { + assertNotNull(new CacheProperties(1, Duration.ofSeconds(1)).ttl()); + } +} diff --git a/platform/py-monitor/README.md b/platform/py-monitor/README.md new file mode 100644 index 00000000..d5a31ceb --- /dev/null +++ b/platform/py-monitor/README.md @@ -0,0 +1,14 @@ +# py-monitor + +Stdlib-only primitives extracted from the Carousell new-listing monitor +(`hoelee/carousell-monitor`), kept here because the same URL normalisation, +price parsing and retry logic is needed by every scraper in the stack. + +No third-party dependencies - `urllib` only, so it drops into any container +without a build step. + +```python +from monitor_core import normalize_product_url, parse_price, strip_thumbnail_suffix +``` + +Run the tests with `python -m pytest tests/ -q` (or `python tests/test_core.py`). diff --git a/platform/py-monitor/monitor_core/__init__.py b/platform/py-monitor/monitor_core/__init__.py new file mode 100644 index 00000000..bfcad46e --- /dev/null +++ b/platform/py-monitor/monitor_core/__init__.py @@ -0,0 +1,9 @@ +"""Stdlib-only primitives extracted from the Carousell listing monitor.""" + +from .urls import strip_thumbnail_suffix, normalize_product_url +from .prices import parse_price, normalize_condition +from .keywords import title_matches_keyword +from .timeutil import iso_now, iso_from_epoch + +__all__ = ["strip_thumbnail_suffix", "normalize_product_url", "parse_price", + "normalize_condition", "title_matches_keyword", "iso_now", "iso_from_epoch"] diff --git a/platform/py-monitor/monitor_core/http.py b/platform/py-monitor/monitor_core/http.py new file mode 100644 index 00000000..5d4722b3 --- /dev/null +++ b/platform/py-monitor/monitor_core/http.py @@ -0,0 +1,47 @@ +"""Minimal retrying HTTP client built on urllib.""" + +import http.client +import socket +import time +import urllib.error +import urllib.parse +import urllib.request + +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0 Safari/537.36") + + +# --------------------------------------------------------------------------- # +# HTTP helpers +# --------------------------------------------------------------------------- # +def _http(method, url, body=None, headers=None, timeout=30, retries=2): + """HTTP 请求。对 Telegram 边缘偶发的 400 做重试。 + + Telegram 的 api.telegram.org 边缘前置(nginx)会偶发对完全合法的请求返回 + 400(同 IP、同 token、同 payload 的裸 socket 请求同时却是 200)。命中时 + 通知会静默丢失。这里对 400/5xx 做有限重试,间隔递增;仍失败则抛出。 + """ + h = {"User-Agent": UA} + if headers: + h.update(headers) + data = None + if body is not None: + data = json.dumps(body).encode("utf-8") + h["Content-Type"] = "application/json" + last = None + for attempt in range(retries + 1): + req = urllib.request.Request(url, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + raw = r.read().decode("utf-8", errors="ignore") + return r.status, raw + except urllib.error.HTTPError as e: + last = e + # 4xx 里只有 400/408/429 值得重试;其余(如 404/403)立即失败 + if e.code not in (400, 408, 429) and e.code < 500: + raise + if attempt < retries: + time.sleep(0.5 * (attempt + 1)) + if last is not None: + raise last + raise RuntimeError("_http: no attempt made") diff --git a/platform/py-monitor/monitor_core/keywords.py b/platform/py-monitor/monitor_core/keywords.py new file mode 100644 index 00000000..9b0b5668 --- /dev/null +++ b/platform/py-monitor/monitor_core/keywords.py @@ -0,0 +1,13 @@ +"""Ignored-keyword matching.""" + + +def title_matches_keyword(title, ignored_keywords): + """True when the title contains any ignored keyword (case-insensitive). + + Keywords are lowercased here rather than by the caller: the original caller + normalised on load, which made the helper silently order-dependent. + """ + if not title or not ignored_keywords: + return False + t = str(title).lower() + return any(str(kw).lower().strip() in t for kw in ignored_keywords if str(kw).strip()) diff --git a/platform/py-monitor/monitor_core/prices.py b/platform/py-monitor/monitor_core/prices.py new file mode 100644 index 00000000..0cd3c802 --- /dev/null +++ b/platform/py-monitor/monitor_core/prices.py @@ -0,0 +1,33 @@ +"""Price and condition parsing.""" + +import re + +CONDITIONS = ["Brand new", "Like new", "Lightly used", "Well used", "Heavily used", "Used"] +CONDITION_MAP = { + "brand new": "Brand new", + "new": "Brand new", + "like new": "Like new", + "lightly used": "Lightly used", + "well used": "Well used", + "heavily used": "Heavily used", + "used": "Used", +} + + +def parse_price(s): + if not s: + return None + t = re.sub(r"[^0-9.]", "", s) + if not t: + return None + try: + return round(float(t), 2) + except ValueError: + return None + + +def normalize_condition(value): + """Map a category-specific condition label onto the canonical set.""" + if not value: + return None + return CONDITION_MAP.get(str(value).strip().lower()) diff --git a/platform/py-monitor/monitor_core/timeutil.py b/platform/py-monitor/monitor_core/timeutil.py new file mode 100644 index 00000000..df95aa82 --- /dev/null +++ b/platform/py-monitor/monitor_core/timeutil.py @@ -0,0 +1,15 @@ +"""Timestamp helpers - ISO 8601 in UTC, epoch in Asia/Kuala_Lumpur terms.""" + +import time +from datetime import datetime, timezone + + +def iso_now(): + # UTC: NocoDB parses naive datetimes as UTC. + return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + + +def iso_from_epoch(epoch): + if not epoch: + return None + return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(epoch)) diff --git a/platform/py-monitor/monitor_core/urls.py b/platform/py-monitor/monitor_core/urls.py new file mode 100644 index 00000000..632d9fda --- /dev/null +++ b/platform/py-monitor/monitor_core/urls.py @@ -0,0 +1,29 @@ +"""Listing URL normalisation.""" + +import urllib.parse + +PRODUCT_URL_TMPL = "https://www.carousell.com.my/p/{listing_id}/" + + +def strip_thumbnail_suffix(url): + """去掉 Carousell 缩略图后缀 _progressive_thumbnail,得到高清原图 URL。 + + 两种形态都去掉: + 1) ..._progressive_thumbnail.jpg → ...jpg + 2) ..._progressive_thumbnail → ...(无扩展名,仍是合法 JPEG) + """ + if not url: + return url + return url.replace("_progressive_thumbnail", "") + + +def normalize_product_url(url): + """剥掉 query/fragment:同一个商品被两个 watch 抓到、或带追踪后缀时仍算同一条。""" + if not url: + return "" + try: + p = urllib.parse.urlsplit(str(url).strip()) + path = (p.path or "").rstrip("/") + return urllib.parse.urlunsplit((p.scheme.lower(), p.netloc.lower(), path, "", "")) + except Exception: + return str(url).strip() diff --git a/platform/py-monitor/tests/test_core.py b/platform/py-monitor/tests/test_core.py new file mode 100644 index 00000000..7e614018 --- /dev/null +++ b/platform/py-monitor/tests/test_core.py @@ -0,0 +1,80 @@ +"""Unit tests for the extracted primitives (stdlib unittest, no deps).""" +import os +import sys +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from monitor_core import (normalize_product_url, normalize_condition, parse_price, + strip_thumbnail_suffix, title_matches_keyword, iso_from_epoch, iso_now) + + +class UrlTests(unittest.TestCase): + + def test_strips_progressive_thumbnail(self): + url = "https://media.example.com/abc.jpg_progressive_thumbnail" + self.assertEqual("https://media.example.com/abc.jpg", strip_thumbnail_suffix(url)) + + def test_strip_is_noop_without_suffix(self): + url = "https://media.example.com/abc.jpg" + self.assertEqual(url, strip_thumbnail_suffix(url)) + + def test_strip_keeps_empty_input(self): + self.assertEqual("", strip_thumbnail_suffix("")) + + def test_normalize_drops_query_and_fragment(self): + a = "https://www.carousell.com.my/p/1234/?utm_source=x#top" + b = "https://WWW.Carousell.com.my/p/1234/" + self.assertEqual(normalize_product_url(a), normalize_product_url(b)) + self.assertEqual("https://www.carousell.com.my/p/1234", normalize_product_url(a)) + + def test_normalize_handles_empty(self): + self.assertEqual("", normalize_product_url(None)) + + +class PriceTests(unittest.TestCase): + + def test_parses_thousands_separator(self): + self.assertEqual(1250.5, parse_price("RM 1,250.50")) + + def test_parses_foreign_currency_prefix(self): + self.assertEqual(12.0, parse_price("S$ 12")) + + def test_returns_none_for_text(self): + self.assertIsNone(parse_price("Free")) + self.assertIsNone(parse_price("")) + self.assertIsNone(parse_price(None)) + + def test_condition_aliases(self): + self.assertEqual("Brand new", normalize_condition("Brand New")) + self.assertEqual("Used", normalize_condition("used")) + self.assertIsNone(normalize_condition("refurbished")) + + +class KeywordTests(unittest.TestCase): + + def test_case_insensitive_match(self): + self.assertTrue(title_matches_keyword("iPhone 13 PROTECTOR", ["protector"])) + + def test_no_match(self): + self.assertFalse(title_matches_keyword("iPhone 13", ["samsung"])) + + def test_empty_inputs(self): + self.assertFalse(title_matches_keyword("", ["x"])) + self.assertFalse(title_matches_keyword("x", [])) + + +class TimeTests(unittest.TestCase): + + def test_iso_now_shape(self): + self.assertRegex(iso_now(), r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$") + + def test_epoch_conversion_is_utc(self): + self.assertEqual("2026-01-01 00:00:00", iso_from_epoch(1767225600)) + + def test_falsy_epoch(self): + self.assertIsNone(iso_from_epoch(0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/platform/shell-sync/.env.example b/platform/shell-sync/.env.example new file mode 100644 index 00000000..d03398c1 --- /dev/null +++ b/platform/shell-sync/.env.example @@ -0,0 +1,93 @@ +# ============================================================ +# Email Sync OAuth2 - Docker Compose Configuration +# ============================================================ +# Copy this file to .env and edit your settings. +# ============================================================ + +# ------------------------------------------------------------ +# Global settings +# ------------------------------------------------------------ + +# Number of accounts to sync +NUM_ACCOUNTS=2 + +# Sync interval in seconds (default: 21600 = 6 hours). +# Used when SYNC_CRON is empty. +SYNC_INTERVAL=21600 + +# Optional standard five-field cron expression. When set, it overrides +# SYNC_INTERVAL. Example: 0 */6 * * * (every six hours) +SYNC_CRON= + +# Run once and exit (true/false) +ONCE=false + +# Token and log directories inside container +TOKEN_DIR=/tokens +LOG_DIR=/var/log/imapsync + +# ------------------------------------------------------------ +# Account 1: Hotmail / Office 365 -> Mailcow (OAuth2) +# ------------------------------------------------------------ + +ACCOUNT_1_SOURCE_HOST=outlook.office365.com +ACCOUNT_1_SOURCE_USER=user1@hotmail.com +ACCOUNT_1_SOURCE_AUTH=oauth2 +ACCOUNT_1_SOURCE_PROVIDER=office365 +ACCOUNT_1_SOURCE_TOKEN=/tokens/user1_hotmail.token + +ACCOUNT_1_DEST_HOST=mail.hoelee.com +ACCOUNT_1_DEST_USER=user1@mailcow.com +ACCOUNT_1_DEST_PASS=your_mailcow_password + +# Delete emails on destination that don't exist on source (true/false) +ACCOUNT_1_DELETE=false + +# Dry run - log what would happen without actually syncing (true/false) +ACCOUNT_1_DRY_RUN=false + +# Extra imapsync options (optional) +ACCOUNT_1_EXTRA_OPTS= + +# ------------------------------------------------------------ +# Account 2: Any standard IMAP source (password authentication) +# ------------------------------------------------------------ + +ACCOUNT_2_SOURCE_HOST=imap.example.com +ACCOUNT_2_SOURCE_USER=user2@example.com +ACCOUNT_2_SOURCE_AUTH=password +ACCOUNT_2_SOURCE_PASS=your_source_password + +ACCOUNT_2_DEST_HOST=mail.hoelee.com +ACCOUNT_2_DEST_USER=user2@mailcow.com +ACCOUNT_2_DEST_PASS=your_mailcow_password + +ACCOUNT_2_DELETE=false +ACCOUNT_2_DRY_RUN=false +ACCOUNT_2_EXTRA_OPTS= + +# ------------------------------------------------------------ +# Account 3+: copy an account block and increase NUM_ACCOUNTS. +# All ACCOUNT_N_* variables from .env are passed into the container. +# ------------------------------------------------------------ + +# ------------------------------------------------------------ +# Optional SMTP notifications +# ------------------------------------------------------------ + +# none | batch_success | account_success | failure +# batch_success: one email after every fully successful sync batch +# account_success: one email for every successful account +# failure: one email when one or more accounts fail in a batch +NOTIFY_MODE=none + +# Required only when NOTIFY_MODE is not none +SMTP_HOST= +SMTP_PORT=587 +SMTP_USER= +SMTP_PASS= +SMTP_FROM= +# One or more comma-separated recipients +SMTP_TO= +# starttls (port 587), tls (implicit TLS, usually port 465), or none +SMTP_TLS=starttls diff --git a/platform/shell-sync/Dockerfile b/platform/shell-sync/Dockerfile new file mode 100644 index 00000000..bf111d23 --- /dev/null +++ b/platform/shell-sync/Dockerfile @@ -0,0 +1,83 @@ +FROM alpine/git:2.47.2@sha256:062a01ad7a0eb17cff382bc5e26086b4d710e56dfdfdf001109a49b6d9bd378c AS imapsync-source + +ARG IMAPSYNC_REV=93654c6025ff7814f983ab74dd300f9bed9282d9 +RUN git clone https://github.com/imapsync/imapsync.git /src \ + && git -C /src checkout "$IMAPSYNC_REV" \ + && test "$(git -C /src rev-parse HEAD)" = "$IMAPSYNC_REV" + +# Debian's own perl is used on purpose. The official perl:*-slim images ship a +# second interpreter in /usr/local/bin that shadows /usr/bin/perl on PATH but +# does not read Debian's @INC, so every libXXX-perl package installed below +# would be invisible to the interpreter that actually runs imapsync. +FROM debian:bookworm-slim + +LABEL maintainer="Hoelee " +LABEL description="Multi-account IMAP sync with OAuth2 support for Office 365, Hotmail, Outlook.com, and Gmail" +LABEL org.opencontainers.image.source="https://github.com/hoelee/email-sync-oauth2" +LABEL org.opencontainers.image.licenses="MIT" + +# Package list follows upstream INSTALL.d/INSTALL.Debian.txt for the pinned +# revision, plus libdigest-hmac-perl (ships Digest::HMAC_SHA1) and the runtime +# tools this image needs (cron, msmtp). +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates \ + perl \ + libauthen-ntlm-perl \ + libcgi-pm-perl \ + libcrypt-openssl-rsa-perl \ + libdata-uniqid-perl \ + libdigest-hmac-perl \ + libemail-address-perl \ + libencode-imaputf7-perl \ + libfile-copy-recursive-perl \ + libfile-tail-perl \ + libhtml-parser-perl \ + libhttp-daemon-perl \ + libhttp-daemon-ssl-perl \ + libhttp-message-perl \ + libio-socket-inet6-perl \ + libio-socket-ssl-perl \ + libio-tee-perl \ + libjson-webtoken-perl \ + libmail-imapclient-perl \ + libmodule-scandeps-perl \ + libnet-dns-perl \ + libnet-server-perl \ + libparse-recdescent-perl \ + libproc-processtable-perl \ + libreadonly-perl \ + libregexp-common-perl \ + libsys-meminfo-perl \ + libterm-readkey-perl \ + libtest-mockobject-perl \ + libunicode-string-perl \ + liburi-perl \ + libwww-perl \ + cron \ + msmtp \ + netcat-openbsd \ + procps \ + && rm -rf /var/lib/apt/lists/* + +# Install one immutable, verified upstream revision of imapsync and its current +# OAuth helper. The old helper URLs no longer exist upstream. +COPY --from=imapsync-source /src/imapsync /usr/local/bin/imapsync +COPY --from=imapsync-source /src/oauth2/oauth2_imap/oauth2_imap /usr/local/bin/oauth2_imap +RUN chmod +x /usr/local/bin/imapsync /usr/local/bin/oauth2_imap \ + && perl -c /usr/local/bin/imapsync \ + && perl -c /usr/local/bin/oauth2_imap \ + && imapsync --version + +# Copy entrypoint +COPY sync.sh /sync.sh +RUN chmod +x /sync.sh && bash -n /sync.sh + +# Health is liveness plus notification delivery. Sync freshness is exposed by +# accountN.last_success / accountN.last_failure files for the chosen schedule. +HEALTHCHECK --interval=5m --timeout=10s --start-period=60s --retries=3 \ + CMD test -f "${LOG_DIR:-/var/log/imapsync}/.heartbeat" && \ + test ! -f "${LOG_DIR:-/var/log/imapsync}/.notification_failed" && \ + test "$(cat "${LOG_DIR:-/var/log/imapsync}/.heartbeat")" -gt "$(date -d '5 minutes ago' +%s)" || \ + { echo "Health check failed: daemon heartbeat is stale or SMTP notification delivery failed. Check container logs."; exit 1; } + +ENTRYPOINT ["/sync.sh"] diff --git a/platform/shell-sync/Makefile b/platform/shell-sync/Makefile new file mode 100644 index 00000000..cf17e141 --- /dev/null +++ b/platform/shell-sync/Makefile @@ -0,0 +1,73 @@ +.PHONY: build up down logs status health authorize sync sync-all shell clean + +# Build the Docker image +build: + docker compose build + +# Start the sync daemon +up: + docker compose up -d + @echo "Container started. Use 'make logs' to follow logs." + +# Stop the container +down: + docker compose down + +# Follow logs +logs: + docker logs -f email-sync-oauth2 + +# Show status of all accounts +status: + @echo "=== Container Status ===" + @docker inspect --format='Status: {{.State.Status}}' email-sync-oauth2 2>/dev/null || echo "Container not running" + @echo "" + @echo "=== Health Status ===" + @docker inspect --format='Health: {{.State.Health.Status}}' email-sync-oauth2 2>/dev/null || echo "No healthcheck" + @echo "" + @echo "=== Last Sync Times ===" + @for f in logs/*.last_success; do \ + [ -f "$$f" ] && echo "$$(basename $$f .last_success): $$(date -d @$$(cat $$f) 2>/dev/null || echo 'unknown')"; \ + done + @echo "" + @echo "=== Last Failures ===" + @for f in logs/*.last_failure; do \ + [ -f "$$f" ] && echo "$$(basename $$f .last_failure): $$(date -d @$$(cat $$f) 2>/dev/null || echo 'unknown')"; \ + done + +# Check health +health: + @docker inspect --format='{{json .State.Health}}' email-sync-oauth2 | jq + +# Authorize account (usage: make authorize ACCOUNT=1) +authorize: + @if [ -z "$(ACCOUNT)" ]; then \ + echo "Usage: make authorize ACCOUNT=1"; \ + exit 1; \ + fi + docker compose run --rm imapsync authorize $(ACCOUNT) + +# Force sync account (usage: make sync ACCOUNT=1) +sync: + @if [ -z "$(ACCOUNT)" ]; then \ + echo "Usage: make sync ACCOUNT=1"; \ + exit 1; \ + fi + docker compose exec imapsync sync.sh sync $(ACCOUNT) + +# Force a full batch now (all configured accounts) +sync-all: + docker compose exec imapsync sync.sh sync-all + +# Enter container shell +shell: + docker compose exec imapsync sync.sh shell + +# Clean up +clean: + docker compose down -v + rm -rf logs/*.log logs/*.last_* logs/.heartbeat logs/.notification_failed + +# One-shot sync (build, run once, exit) +once: + ONCE=true docker compose up --build --abort-on-container-exit diff --git a/platform/shell-sync/README.md b/platform/shell-sync/README.md new file mode 100644 index 00000000..f5e6df08 --- /dev/null +++ b/platform/shell-sync/README.md @@ -0,0 +1,13 @@ +# shell-sync + +Multi-account IMAP sync driven by `mbsync`, with OAuth2 token refresh for +providers that no longer accept plain passwords. Extracted from +`hoelee/email-sync-oauth2`. + +The entrypoint refreshes each account's token, regenerates the `mbsyncrc` from +environment variables, then runs incremental sync on a timer. Credentials come +from the environment only - see `.env.example`. + +``` +make build && make run +``` diff --git a/platform/shell-sync/sync.sh b/platform/shell-sync/sync.sh new file mode 100644 index 00000000..22bd6165 --- /dev/null +++ b/platform/shell-sync/sync.sh @@ -0,0 +1,427 @@ +#!/bin/bash +set -Eeuo pipefail + +# IMAP Sync Manager - multi-account OAuth2 and password authentication. + +TOKEN_DIR="${TOKEN_DIR:-/tokens}" +LOG_DIR="${LOG_DIR:-/var/log/imapsync}" +PID_DIR="${PID_DIR:-/tmp/imapsync}" +HEARTBEAT_FILE="${LOG_DIR}/.heartbeat" +NUM_ACCOUNTS="${NUM_ACCOUNTS:-1}" +SYNC_INTERVAL="${SYNC_INTERVAL:-21600}" # six hours +SYNC_CRON="${SYNC_CRON:-}" +ONCE="${ONCE:-false}" + +# Notifications are disabled unless NOTIFY_MODE is explicitly set. +# Valid modes: none, batch_success, account_success, failure. +NOTIFY_MODE="${NOTIFY_MODE:-none}" +SMTP_HOST="${SMTP_HOST:-}" +SMTP_PORT="${SMTP_PORT:-587}" +SMTP_USER="${SMTP_USER:-}" +SMTP_PASS="${SMTP_PASS:-}" +SMTP_FROM="${SMTP_FROM:-}" +SMTP_TO="${SMTP_TO:-}" +SMTP_TLS="${SMTP_TLS:-starttls}" +NOTIFICATION_FAILURE_FILE="${LOG_DIR}/.notification_failed" +NOTIFICATION_LOG="${LOG_DIR}/notification.log" + +mkdir -p "$LOG_DIR" "$PID_DIR" "$TOKEN_DIR" + +log() { + echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" +} + +get_var() { + local varname="$1" + echo "${!varname:-}" +} + +oauth_authorization_invalid() { + local logfile="$1" + tail -n 200 "$logfile" 2>/dev/null | grep -Eqi \ + 'invalid_grant|expired.*(token|credential)|token.*expired|refresh token.*(expired|revoked|invalid)|authorization.*(expired|revoked)|AADSTS700082|AADSTS700084|AUTHENTICATE failed|authentication.*failed|authentication unsuccessful|invalid credentials' +} + +log_oauth_authorization_guidance() { + local i="$1" + local provider="$2" + local logfile="$3" + + if oauth_authorization_invalid "$logfile"; then + log "Account $i: OAuth2 authorization is expired, revoked, or rejected by $provider. Reauthorize with: docker compose run --rm imapsync authorize $i" + log "Account $i: After reauthorization, run immediately with: docker compose exec imapsync sync.sh sync $i" + fi +} + +validate_settings() { + if ! [[ "$NUM_ACCOUNTS" =~ ^[1-9][0-9]*$ ]]; then + log "Configuration error: NUM_ACCOUNTS must be a positive integer" + return 1 + fi + + if [ -z "$SYNC_CRON" ] && ! [[ "$SYNC_INTERVAL" =~ ^[1-9][0-9]*$ ]]; then + log "Configuration error: SYNC_INTERVAL must be a positive number of seconds" + return 1 + fi + + case "$NOTIFY_MODE" in + none|batch_success|account_success|failure) ;; + *) + log "Configuration error: NOTIFY_MODE must be none, batch_success, account_success, or failure" + return 1 + ;; + esac + + if [ "$NOTIFY_MODE" != "none" ]; then + if [ -z "$SMTP_HOST" ] || [ -z "$SMTP_FROM" ] || [ -z "$SMTP_TO" ]; then + log "Configuration error: SMTP_HOST, SMTP_FROM, and SMTP_TO are required when notifications are enabled" + return 1 + fi + if ! [[ "$SMTP_PORT" =~ ^[1-9][0-9]*$ ]]; then + log "Configuration error: SMTP_PORT must be a valid port number" + return 1 + fi + if { [ -n "$SMTP_USER" ] && [ -z "$SMTP_PASS" ]; } || { [ -z "$SMTP_USER" ] && [ -n "$SMTP_PASS" ]; }; then + log "Configuration error: SMTP_USER and SMTP_PASS must either both be set or both be empty" + return 1 + fi + case "$SMTP_TLS" in starttls|tls|none) ;; *) + log "Configuration error: SMTP_TLS must be starttls, tls, or none" + return 1 + ;; + esac + fi +} + +send_notification() { + local subject="$1" + local body="$2" + local config + local -a recipients + + if [ "$NOTIFY_MODE" = "none" ]; then + return 0 + fi + + config="$(mktemp "${PID_DIR}/msmtp.XXXXXX")" + chmod 600 "$config" + { + printf 'defaults\n' + printf 'host %s\n' "$SMTP_HOST" + printf 'port %s\n' "$SMTP_PORT" + printf 'from %s\n' "$SMTP_FROM" + if [ -n "$SMTP_USER" ]; then + printf 'auth on\nuser %s\npassword %s\n' "$SMTP_USER" "$SMTP_PASS" + else + printf 'auth off\n' + fi + case "$SMTP_TLS" in + starttls) printf 'tls on\ntls_starttls on\n' ;; + tls) printf 'tls on\ntls_starttls off\n' ;; + none) printf 'tls off\n' ;; + esac + } > "$config" + + IFS=',' read -r -a recipients <<< "$SMTP_TO" + if printf 'From: %s\nTo: %s\nSubject: %s\n\n%s\n' "$SMTP_FROM" "$SMTP_TO" "$subject" "$body" \ + | msmtp --file="$config" "${recipients[@]}" >> "$NOTIFICATION_LOG" 2>&1; then + rm -f "$config" "$NOTIFICATION_FAILURE_FILE" + log "Notification sent: $subject" + return 0 + fi + + rm -f "$config" + printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$subject" > "$NOTIFICATION_FAILURE_FILE" + log "Notification delivery failed; container will remain unhealthy until a notification is sent successfully. Check $NOTIFICATION_LOG" + return 1 +} + +source_oauth_provider() { + case "$1" in + office365|outlook|hotmail) echo "office365" ;; + gmail|google) echo "gmail" ;; + *) return 1 ;; + esac +} + +sync_account() { + local i="$1" + local src_host="$(get_var "ACCOUNT_${i}_SOURCE_HOST")" + local src_user="$(get_var "ACCOUNT_${i}_SOURCE_USER")" + local src_auth="$(get_var "ACCOUNT_${i}_SOURCE_AUTH")" + local src_pass="$(get_var "ACCOUNT_${i}_SOURCE_PASS")" + local src_token="$(get_var "ACCOUNT_${i}_SOURCE_TOKEN")" + local src_provider="$(get_var "ACCOUNT_${i}_SOURCE_PROVIDER")" + local dest_host="$(get_var "ACCOUNT_${i}_DEST_HOST")" + local dest_user="$(get_var "ACCOUNT_${i}_DEST_USER")" + local dest_pass="$(get_var "ACCOUNT_${i}_DEST_PASS")" + local delete_opt="$(get_var "ACCOUNT_${i}_DELETE")" + local dry_run="$(get_var "ACCOUNT_${i}_DRY_RUN")" + local extra_opts="$(get_var "ACCOUNT_${i}_EXTRA_OPTS")" + local logfile="${LOG_DIR}/account${i}.log" + local pidfile="${PID_DIR}/account${i}.pid" + local oauth_provider + local oauth_log + local oauth_authorization_detected=false + local sync_exit + local -a args + + SYNC_ACCOUNT_RESULT="skipped" + if [ -z "$src_host" ] && [ -z "$dest_host" ]; then + log "Account $i: SKIP (not configured)" + return 0 + fi + if [ -z "$src_host" ] || [ -z "$src_user" ] || [ -z "$dest_host" ] || [ -z "$dest_user" ] || [ -z "$dest_pass" ]; then + log "Account $i: CONFIGURATION FAILED (source host/user and destination host/user/password are required)" + SYNC_ACCOUNT_RESULT="failure" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure" + return 1 + fi + + if [ -f "$pidfile" ]; then + local old_pid + old_pid="$(cat "$pidfile")" + if kill -0 "$old_pid" 2>/dev/null; then + log "Account $i: SKIP (already running, PID $old_pid)" + return 0 + fi + fi + echo $$ > "$pidfile" + + log "Account $i: SYNC START - $src_user ($src_host) -> $dest_user ($dest_host)" + args=( + --host1 "$src_host" --user1 "$src_user" --ssl1 + --host2 "$dest_host" --user2 "$dest_user" --password2 "$dest_pass" --ssl2 + --noauthmd5 + ) + + case "$src_auth" in + oauth2) + if ! oauth_provider="$(source_oauth_provider "$src_provider")"; then + log "Account $i: CONFIGURATION FAILED (OAuth2 provider must be office365, outlook, hotmail, gmail, or google)" + SYNC_ACCOUNT_RESULT="failure" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure" + rm -f "$pidfile" + return 1 + fi + if [ -z "$src_token" ]; then + log "Account $i: CONFIGURATION FAILED (ACCOUNT_${i}_SOURCE_TOKEN is required for OAuth2)" + SYNC_ACCOUNT_RESULT="failure" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure" + rm -f "$pidfile" + return 1 + fi + if [ ! -s "$src_token" ]; then + log "Account $i: OAuth2 token is missing. Authorize with: docker compose run --rm imapsync authorize $i" + SYNC_ACCOUNT_RESULT="failure" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure" + rm -f "$pidfile" + return 1 + fi + # The helper prints access and refresh tokens. Keep that output in a + # short-lived, root-only file instead of the mounted account log. + oauth_log="$(mktemp "${PID_DIR}/oauth.XXXXXX")" + chmod 600 "$oauth_log" + # The upstream helper opens an interactive browser flow when refresh + # fails. A scheduled container must never wait indefinitely for that. + timeout --kill-after=5s 90s oauth2_imap --provider "$oauth_provider" --application imapsync --token_file "$src_token" "$src_user" > "$oauth_log" 2>&1 || true + if oauth_authorization_invalid "$oauth_log"; then + log_oauth_authorization_guidance "$i" "$src_provider" "$oauth_log" + oauth_authorization_detected=true + fi + rm -f "$oauth_log" + if [ ! -s "$src_token" ]; then + log "Account $i: OAuth2 token refresh or authorization failed" + log_oauth_authorization_guidance "$i" "$src_provider" "$logfile" + SYNC_ACCOUNT_RESULT="failure" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure" + rm -f "$pidfile" + return 1 + fi + args+=(--oauthaccesstoken1 "$src_token") + ;; + password) + if [ -z "$src_pass" ]; then + log "Account $i: CONFIGURATION FAILED (ACCOUNT_${i}_SOURCE_PASS is required for password authentication)" + SYNC_ACCOUNT_RESULT="failure" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure" + rm -f "$pidfile" + return 1 + fi + args+=(--password1 "$src_pass") + ;; + *) + log "Account $i: CONFIGURATION FAILED (ACCOUNT_${i}_SOURCE_AUTH must be oauth2 or password)" + SYNC_ACCOUNT_RESULT="failure" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure" + rm -f "$pidfile" + return 1 + ;; + esac + + [ "$delete_opt" = "true" ] && args+=(--delete2) + [ "$dry_run" = "true" ] && args+=(--dry) + if [ -n "$extra_opts" ]; then + # Intentional option splitting: this variable supplies extra CLI flags. + # shellcheck disable=SC2206 + args+=($extra_opts) + fi + + # Capture the real exit status. Reading $? after an `if` block returns the + # status of the `if` itself (always 0), which silently reported every + # failure as exit 0 and let sync_all treat it as success. + sync_exit=0 + imapsync "${args[@]}" >> "$logfile" 2>&1 || sync_exit=$? + + if [ "$sync_exit" -eq 0 ]; then + log "Account $i: SYNC OK" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_success" + SYNC_ACCOUNT_RESULT="success" + rm -f "$pidfile" + return 0 + fi + + log "Account $i: SYNC FAILED (exit $sync_exit)" + echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure" + if [ "$src_auth" = "oauth2" ] && [ "$oauth_authorization_detected" = "false" ]; then + log_oauth_authorization_guidance "$i" "$src_provider" "$logfile" + fi + SYNC_ACCOUNT_RESULT="failure" + rm -f "$pidfile" + return "$sync_exit" +} + +sync_all() { + local i + local configured=0 + local failures=0 + local notification_failures=0 + local successes="" + local failed_accounts="" + + log "=== Sync cycle start ===" + for ((i = 1; i <= NUM_ACCOUNTS; i++)); do + if sync_account "$i"; then + if [ "$SYNC_ACCOUNT_RESULT" = "success" ]; then + configured=$((configured + 1)) + successes="${successes}${successes:+, }${i}" + if [ "$NOTIFY_MODE" = "account_success" ]; then + send_notification "IMAP sync succeeded for account $i" "Account $i completed successfully at $(date '+%Y-%m-%d %H:%M:%S')." || notification_failures=1 + fi + fi + else + configured=$((configured + 1)) + failures=$((failures + 1)) + failed_accounts="${failed_accounts}${failed_accounts:+, }${i}" + fi + done + + if [ "$NOTIFY_MODE" = "batch_success" ] && [ "$configured" -gt 0 ] && [ "$failures" -eq 0 ]; then + send_notification "IMAP sync batch succeeded" "All configured accounts completed successfully at $(date '+%Y-%m-%d %H:%M:%S'): $successes." || notification_failures=1 + fi + if [ "$NOTIFY_MODE" = "failure" ] && [ "$failures" -gt 0 ]; then + send_notification "IMAP sync batch failed" "Sync failed for account(s) $failed_accounts at $(date '+%Y-%m-%d %H:%M:%S'). Check ${LOG_DIR}/accountN.log for details." || notification_failures=1 + fi + + log "=== Sync cycle complete (success: ${successes:-none}; failed: ${failed_accounts:-none}) ===" + [ "$failures" -eq 0 ] && [ "$notification_failures" -eq 0 ] +} + +start_heartbeat() { + echo "$(date +%s)" > "$HEARTBEAT_FILE" + while true; do + echo "$(date +%s)" > "$HEARTBEAT_FILE" + sleep 60 + done & + HEARTBEAT_PID=$! +} + +run_cron_scheduler() { + local wrapper="${PID_DIR}/cron-sync-all.sh" + local crontab_file="${PID_DIR}/sync.crontab" + + # Cron starts commands with a minimal environment. Preserve this container's + # configuration in a root-only Bash wrapper so arbitrary ACCOUNT_N_* values work. + { + printf '#!/bin/bash\n' + export -p + printf 'exec /sync.sh sync-all\n' + } > "$wrapper" + chmod 700 "$wrapper" + printf '%s %s >> /proc/1/fd/1 2>&1\n' "$SYNC_CRON" "$wrapper" > "$crontab_file" + + if ! crontab "$crontab_file"; then + log "Configuration error: SYNC_CRON is not a valid cron expression: $SYNC_CRON" + return 1 + fi + log "Starting cron schedule: $SYNC_CRON" + cron -f & + CRON_PID=$! + wait "$CRON_PID" +} + +run_once() { + log "Running in ONCE mode" + local status=0 + sync_all || status=$? + log "One-shot sync complete" + return "$status" +} + +run_daemon() { + log "Starting daemon mode (accounts: $NUM_ACCOUNTS)" + start_heartbeat + trap 'kill "${HEARTBEAT_PID:-}" "${CRON_PID:-}" 2>/dev/null || true' EXIT + + if [ -n "$SYNC_CRON" ]; then + run_cron_scheduler + return + fi + + while true; do + sync_all || true + log "Sleeping ${SYNC_INTERVAL}s before the next sync cycle" + sleep "$SYNC_INTERVAL" + done +} + +case "${1:-}" in + sync) + shift + validate_settings + sync_account "${1:-1}" + ;; + sync-all) + validate_settings + sync_all + ;; + authorize) + shift + i="${1:-1}" + src_user="$(get_var "ACCOUNT_${i}_SOURCE_USER")" + src_token="$(get_var "ACCOUNT_${i}_SOURCE_TOKEN")" + src_provider="$(get_var "ACCOUNT_${i}_SOURCE_PROVIDER")" + validate_settings + if ! provider="$(source_oauth_provider "$src_provider")" || [ -z "$src_user" ] || [ -z "$src_token" ]; then + log "Account $i: authorization requires a supported OAuth2 provider, source user, and token path" + exit 1 + fi + log "Manual authorize: $src_user" + exec oauth2_imap --startover --provider "$provider" --application imapsync --token_file "$src_token" "$src_user" + ;; + shell|bash|sh) + exec /bin/bash + ;; + imapsync) + shift + exec imapsync "$@" + ;; + *) + validate_settings + if [ "$ONCE" = "true" ]; then + run_once + else + run_daemon + fi + ;; +esac diff --git a/util.go b/util.go new file mode 100644 index 00000000..f0f62d47 --- /dev/null +++ b/util.go @@ -0,0 +1,127 @@ +package traefik_botfilter + +import ( + "net" + "net/http" + "net/netip" + "net/url" + pathpkg "path" + "strings" +) + +func clientIP(r *http.Request, cfg *compiledConfig) netip.Addr { + remote := parseRemoteAddress(r.RemoteAddr) + if cfg.clientIPHeader == "" || !addressInPrefixes(remote, cfg.trustedProxies) { + return remote + } + + // A trusted reverse proxy must overwrite (not append to an untrusted + // client-provided value) this header. The left-most valid value is the + // original client in the conventional X-Forwarded-For representation. + for _, value := range strings.Split(r.Header.Get(cfg.clientIPHeader), ",") { + if addr, err := netip.ParseAddr(strings.TrimSpace(value)); err == nil { + return addr.Unmap() + } + } + return remote +} + +func parseRemoteAddress(value string) netip.Addr { + host, _, err := net.SplitHostPort(strings.TrimSpace(value)) + if err == nil { + value = host + } + addr, err := netip.ParseAddr(strings.Trim(strings.TrimSpace(value), "[]")) + if err != nil { + return netip.Addr{} + } + return addr.Unmap() +} + +func addressInPrefixes(addr netip.Addr, prefixes []netip.Prefix) bool { + if !addr.IsValid() { + return false + } + for _, prefix := range prefixes { + if prefix.Contains(addr) { + return true + } + } + return false +} + +func normaliseTokens(values []string) []string { + result := make([]string, 0, len(values)) + for _, value := range values { + if token := strings.ToLower(strings.TrimSpace(value)); token != "" { + result = append(result, token) + } + } + return result +} + +func normalisePaths(values []string) []string { + result := make([]string, 0, len(values)) + for _, value := range values { + if path := normalisePath(value); path != "" { + result = append(result, path) + } + } + return result +} + +func normaliseExtensions(values []string) []string { + result := make([]string, 0, len(values)) + for _, value := range values { + value = strings.ToLower(strings.TrimSpace(value)) + if value == "" { + continue + } + if !strings.HasPrefix(value, ".") { + value = "." + value + } + result = append(result, value) + } + return result +} + +func normalisePath(value string) string { + value = strings.TrimSpace(value) + if value == "" { + return "" + } + value = strings.ReplaceAll(value, "\\", "/") + if !strings.HasPrefix(value, "/") { + value = "/" + value + } + return strings.ToLower(pathpkg.Clean(value)) +} + +func requestPaths(r *http.Request) []string { + values := []string{r.URL.Path, r.URL.EscapedPath()} + result := make([]string, 0, len(values)*3) + seen := make(map[string]struct{}) + for _, value := range values { + for i := 0; i < 3 && value != ""; i++ { + normalised := normalisePath(value) + if _, ok := seen[normalised]; !ok { + seen[normalised] = struct{}{} + result = append(result, normalised) + } + decoded, err := url.PathUnescape(value) + if err != nil || decoded == value { + break + } + value = decoded + } + } + return result +} + +func pathMatches(path, rule string) bool { + return path == rule || strings.HasPrefix(path, rule+"/") +} + +func hasHeader(r *http.Request, name string) bool { + return strings.TrimSpace(r.Header.Get(name)) != "" +}