This upgrades the Masyunis fork from Anubis v1.25.0 to the latest stable release, **v1.28.2** (“Wuk Lamat Echo 2”), while keeping the fork’s custom styling and removals. ## Approach The Gitea repo is a tree snapshot of v1.25.0, not a git-level fork of [TecharoHQ/anubis](https://github.com/TecharoHQ/anubis). The histories share no commits, so a merge or rebase onto the upstream tag is not usable. The first commit on this branch replaces the tree with a snapshot of the **v1.28.2** tag (`git rm -r` plus `git checkout v1.28.2 -- .`; the import tree is identical to the tag). A short patch series on top restores the Masyunis customizations. ## Customizations kept - Masyunya mascots (`web/static/img/{happy,pensive,reject}.webp`), hashes match current `master`. - `web/static/img/ATTRIBUTIONS.txt` stays deleted. - Challenge footer: drop the `made_with` (Canada / maple-leaf) line and the CELPHASE mascot credit; keep “Protected by Anubis from Techaro”. The generated `web/index_templ.go` matches `go generate ./web`. - Short README (the old `anubisc` typo is fixed). - Version stamped `v1.28.2/masyunis` via Makefile ldflags. `anubis.go` `init()` does not overwrite a link-time version; `go run` / `go test` still report `devel` on purpose. - Upstream `.github`, `.devcontainer`, `.husky`, and `.vscode` stay deleted. - `"uk"` is removed from `lib/localization/locales/manifest.json` **on purpose**, because of Alpine locale problems. `uk.json` and its test entry stay; the served manifest lists 27 languages. - `package.json` `prepare` no longer runs `husky` (the hooks directory is gone). The rest of the script is unchanged. `husky` remains in devDependencies, as upstream left it. ## Deploy notes - **Cookie rename (v1.27):** with the default `DYNAMIC_COOKIE_SUFFIX=true`, cookie names become e.g. `techaro.lol-anubis-auth-<hash>`. Existing clients get a **one-time re-challenge**. That is expected, not a loop. - **Docker / ko / yeet builds** skip the Makefile ldflags, so the displayed version is `<git-version>/masyunis`. It is `v1.28.2/masyunis` only when built from a `v1.28.2` tag (or via `make build` / `make prebaked-build`). - Go 1.27.3 is required (upstream bump in v1.28.2). Thoth (`THOTH_URL` / `THOTH_TOKEN`) was removed upstream; those settings now warn and do nothing. New WASM challenge methods stay disabled unless opted in. ## Verification - `make build` succeeds. `./var/anubis --version` prints `Anubis v1.28.2/masyunis`. - `SKIP_INTEGRATION=1 go test ./...` passes (unit tests; integration package is skipped). - Local challenge/reject pages (en and ru) show Masyunya, version `v1.28.2/masyunis`, and no Canada / CELPHASE / mascot-credit text. Screenshots:   - Upstream Playwright tests (`make test` without `SKIP_INTEGRATION`) fail on this box because the browser download fails. A clean v1.28.2 tree fails the same three Playwright tests here, so this is not a fork regression. - `npm audit` reports **4** findings in upstream’s lockfile (2 moderate, 2 high: `brace-expansion`, `fast-uri`, `lodash.trim`, `source-map-js`). Left alone. Please review and merge when ready. I will not merge this myself. Reviewed-on: #1 Co-authored-by: Lead <3+lead_bot@noreply.git.unvr.site>
546 lines
16 KiB
Go
546 lines
16 KiB
Go
package lib
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"math/rand"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/TecharoHQ/anubis"
|
|
"github.com/TecharoHQ/anubis/internal"
|
|
"github.com/TecharoHQ/anubis/internal/glob"
|
|
"github.com/TecharoHQ/anubis/lib/challenge"
|
|
"github.com/TecharoHQ/anubis/lib/challenge/extension"
|
|
"github.com/TecharoHQ/anubis/lib/localization"
|
|
"github.com/TecharoHQ/anubis/lib/policy"
|
|
"github.com/TecharoHQ/anubis/web"
|
|
"github.com/TecharoHQ/anubis/xess"
|
|
"github.com/a-h/templ"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"golang.org/x/net/publicsuffix"
|
|
)
|
|
|
|
var domainMatchRegexp = regexp.MustCompile(`^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$`)
|
|
|
|
var (
|
|
ErrActualAnubisBug = errors.New("this is an actual bug in Anubis, please file an issue with the magic string 'taco bell'")
|
|
)
|
|
|
|
// matchRedirectDomain returns true if host matches any of the allowed redirect
|
|
// domain patterns. Patterns may contain '*' which are matched using the
|
|
// internal glob matcher. Matching is case-insensitive on hostnames.
|
|
func matchRedirectDomain(allowed []string, host string) bool {
|
|
h := strings.ToLower(strings.TrimSpace(host))
|
|
for _, pat := range allowed {
|
|
p := strings.ToLower(strings.TrimSpace(pat))
|
|
if strings.Contains(p, glob.GLOB) {
|
|
if glob.Glob(p, h) {
|
|
return true
|
|
}
|
|
continue
|
|
}
|
|
if p == h {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
var (
|
|
ErrInvalidRedirect = errors.New("invalid redirect")
|
|
ErrRedirectDomainNotAllowed = errors.New("redirect domain not allowed")
|
|
ErrUnknownChallengeExtension = errors.New("unknown challenge extension")
|
|
)
|
|
|
|
// validateRedirect validates the form-decoded target without changing its escaping.
|
|
func (s *Server) validateRedirect(redir string) (*url.URL, error) {
|
|
if strings.HasPrefix(redir, " ") || strings.ContainsAny(redir, "\\") {
|
|
return nil, ErrInvalidRedirect
|
|
}
|
|
for _, c := range redir {
|
|
if c < 0x20 || c == 0x7f {
|
|
return nil, ErrInvalidRedirect
|
|
}
|
|
}
|
|
u, err := url.Parse(redir)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%w: %w", ErrInvalidRedirect, err)
|
|
}
|
|
if u.Opaque != "" {
|
|
return nil, ErrInvalidRedirect
|
|
}
|
|
switch u.Scheme {
|
|
case "":
|
|
if u.Host != "" || strings.HasPrefix(u.Path, "//") || strings.ContainsAny(u.Path, "\\") {
|
|
return nil, ErrInvalidRedirect
|
|
}
|
|
case "http", "https":
|
|
if u.Hostname() == "" {
|
|
return nil, ErrInvalidRedirect
|
|
}
|
|
default:
|
|
return nil, ErrInvalidRedirect
|
|
}
|
|
if u.Host != "" && len(s.opts.RedirectDomains) != 0 && !matchRedirectDomain(s.opts.RedirectDomains, u.Host) {
|
|
return nil, ErrRedirectDomainNotAllowed
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
func (s *Server) rejectRedirect(w http.ResponseWriter, r *http.Request, err error) {
|
|
lg, _ := s.getRequestLogger(r)
|
|
localizer := localization.GetLocalizer(r)
|
|
message := "invalid_redirect"
|
|
if errors.Is(err, ErrRedirectDomainNotAllowed) {
|
|
message = "redirect_domain_not_allowed"
|
|
}
|
|
lg.DebugContext(r.Context(), "invalid redirect", "err", err)
|
|
s.respondWithStatus(w, r, localizer.T(message), "", http.StatusBadRequest)
|
|
}
|
|
|
|
type CookieOpts struct {
|
|
Value string
|
|
Host string
|
|
Path string
|
|
Name string
|
|
Expiry time.Duration
|
|
}
|
|
|
|
func (s *Server) cookieName(base string) string {
|
|
if s.opts.DynamicCookieSuffix {
|
|
h := sha256.Sum256(fmt.Appendf(nil, "%t|%t|%t|%d|%s|%t|%s",
|
|
s.opts.CookieHttpOnly, s.opts.CookieSecure, s.opts.CookiePartitioned,
|
|
s.opts.CookieSameSite, s.opts.CookieDomain, s.opts.CookieDynamicDomain,
|
|
anubis.BasePrefix))
|
|
return base + "-" + hex.EncodeToString(h[:4])
|
|
}
|
|
return base
|
|
}
|
|
|
|
// getCookie reads the cookie named base from the request. It applies the same
|
|
// settings suffix that SetCookie applies, so that cookies written with other
|
|
// settings are ignored.
|
|
func (s *Server) getCookie(r *http.Request, base string) (*http.Cookie, error) {
|
|
return r.Cookie(s.cookieName(base))
|
|
}
|
|
|
|
func (s *Server) SetCookie(w http.ResponseWriter, cookieOpts CookieOpts) {
|
|
var domain = s.opts.CookieDomain
|
|
var name = anubis.CookieName
|
|
var path = "/"
|
|
var sameSite = s.opts.CookieSameSite
|
|
|
|
if cookieOpts.Name != "" {
|
|
name = cookieOpts.Name
|
|
}
|
|
if cookieOpts.Path != "" {
|
|
path = cookieOpts.Path
|
|
}
|
|
if s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {
|
|
if etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {
|
|
domain = etld
|
|
}
|
|
}
|
|
|
|
if cookieOpts.Expiry == 0 {
|
|
cookieOpts.Expiry = s.opts.CookieExpiration
|
|
}
|
|
|
|
if s.opts.CookieSameSite == http.SameSiteNoneMode && !s.opts.CookieSecure {
|
|
sameSite = http.SameSiteLaxMode
|
|
}
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: s.cookieName(name),
|
|
Value: cookieOpts.Value,
|
|
Expires: time.Now().Add(cookieOpts.Expiry),
|
|
SameSite: sameSite,
|
|
Domain: domain,
|
|
HttpOnly: s.opts.CookieHttpOnly,
|
|
Secure: s.opts.CookieSecure,
|
|
Partitioned: s.opts.CookiePartitioned,
|
|
Path: path,
|
|
})
|
|
}
|
|
|
|
func (s *Server) ClearCookie(w http.ResponseWriter, cookieOpts CookieOpts) {
|
|
var domain = s.opts.CookieDomain
|
|
var name = anubis.CookieName
|
|
var path = "/"
|
|
var sameSite = s.opts.CookieSameSite
|
|
|
|
if cookieOpts.Name != "" {
|
|
name = cookieOpts.Name
|
|
}
|
|
if cookieOpts.Path != "" {
|
|
path = cookieOpts.Path
|
|
}
|
|
if s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {
|
|
if etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {
|
|
domain = etld
|
|
}
|
|
}
|
|
if s.opts.CookieSameSite == http.SameSiteNoneMode && !s.opts.CookieSecure {
|
|
sameSite = http.SameSiteLaxMode
|
|
}
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: s.cookieName(name),
|
|
Value: "",
|
|
MaxAge: -1,
|
|
Expires: time.Now().Add(-1 * time.Minute),
|
|
SameSite: sameSite,
|
|
Partitioned: s.opts.CookiePartitioned,
|
|
Domain: domain,
|
|
HttpOnly: s.opts.CookieHttpOnly,
|
|
Secure: s.opts.CookieSecure,
|
|
Path: path,
|
|
})
|
|
}
|
|
|
|
// https://github.com/oauth2-proxy/oauth2-proxy/blob/master/pkg/upstream/http.go#L124
|
|
type UnixRoundTripper struct {
|
|
Transport *http.Transport
|
|
}
|
|
|
|
// set bare minimum stuff
|
|
func (t UnixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
req = req.Clone(req.Context())
|
|
if req.Host == "" {
|
|
req.Host = "localhost"
|
|
}
|
|
req.URL.Host = req.Host // proxy error: no Host in request URL
|
|
req.URL.Scheme = "http" // make http.Transport happy and avoid an infinite recursion
|
|
return t.Transport.RoundTrip(req)
|
|
}
|
|
|
|
func randomChance(n int) bool {
|
|
return rand.Intn(n) == 0
|
|
}
|
|
|
|
// XXX(Xe): generated by ChatGPT
|
|
func rot13(s string) string {
|
|
rotated := make([]rune, len(s))
|
|
for i, c := range s {
|
|
switch {
|
|
case c >= 'A' && c <= 'Z':
|
|
rotated[i] = 'A' + ((c - 'A' + 13) % 26)
|
|
case c >= 'a' && c <= 'z':
|
|
rotated[i] = 'a' + ((c - 'a' + 13) % 26)
|
|
default:
|
|
rotated[i] = c
|
|
}
|
|
}
|
|
return string(rotated)
|
|
}
|
|
|
|
func makeCode(err error) string {
|
|
var buf bytes.Buffer
|
|
gzw := gzip.NewWriter(&buf)
|
|
errStr := fmt.Sprintf("internal error: %v", err)
|
|
|
|
fmt.Fprintln(gzw, rot13(errStr)) //nolint:errcheck
|
|
if err := gzw.Close(); err != nil {
|
|
panic("can't write to gzip in ram buffer")
|
|
}
|
|
const width = 16
|
|
|
|
enc := base64.StdEncoding.EncodeToString(buf.Bytes())
|
|
var builder strings.Builder
|
|
for i := 0; i < len(enc); i += width {
|
|
end := min(i+width, len(enc))
|
|
builder.WriteString(enc[i:end])
|
|
builder.WriteByte('\n')
|
|
}
|
|
return builder.String()
|
|
}
|
|
|
|
func mergeExtensions(r *http.Request, chall *challenge.Challenge, component templ.Component) (templ.Component, error) {
|
|
if len(chall.Extensions) == 0 {
|
|
return component, nil
|
|
}
|
|
|
|
result := make([]templ.Component, 0, len(chall.Extensions)+1) // add a part for the base <head> template
|
|
for _, name := range chall.Extensions {
|
|
ext, ok := extension.Get(name)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%w: %q", ErrUnknownChallengeExtension, name)
|
|
}
|
|
result = append(result, ext.Head(r, chall))
|
|
}
|
|
result = append(result, component)
|
|
|
|
return templ.Join(result...), nil
|
|
}
|
|
|
|
func (s *Server) RenderIndex(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, rule *policy.Bot, returnHTTPStatusOnly bool) {
|
|
localizer := localization.GetLocalizer(r)
|
|
|
|
if returnHTTPStatusOnly {
|
|
if s.opts.PublicUrl == "" {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
w.Write([]byte(localizer.T("authorization_required"))) //nolint:errcheck
|
|
} else {
|
|
redirectURL, err := s.constructRedirectURL(r)
|
|
if err != nil {
|
|
s.respondWithStatus(w, r, err.Error(), "", http.StatusBadRequest)
|
|
return
|
|
}
|
|
http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
|
|
}
|
|
return
|
|
}
|
|
|
|
lg, r := s.getRequestLogger(r)
|
|
|
|
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && randomChance(64) {
|
|
lg.InfoContext(r.Context(), "client was given a challenge but does not in fact support gzip compression")
|
|
s.respondWithStatus(w, r, localizer.T("client_error_browser"), "", s.policy.StatusCodes.Deny)
|
|
return
|
|
}
|
|
|
|
{
|
|
asn, asnDesc := asnFromContext(r.Context())
|
|
challengesIssued.WithLabelValues("embedded", asn, asnDesc).Add(1)
|
|
}
|
|
chall, err := s.issueChallenge(r.Context(), r, lg, cr, rule)
|
|
if err != nil {
|
|
lg.ErrorContext(r.Context(), "can't get challenge", "err", err)
|
|
algorithm := "unknown"
|
|
if rule.Challenge != nil {
|
|
algorithm = rule.Challenge.Algorithm
|
|
}
|
|
s.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})
|
|
s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), algorithm), makeCode(err))
|
|
return
|
|
}
|
|
|
|
lg = lg.With("challenge", chall.ID)
|
|
|
|
var ogTags map[string]string = nil
|
|
if s.opts.OpenGraph.Enabled {
|
|
var err error
|
|
ogTags, err = s.OGTags.GetOGTags(r.Context(), r.URL, r.Host)
|
|
if err != nil {
|
|
lg.ErrorContext(r.Context(), "failed to get OG tags", "err", err)
|
|
}
|
|
}
|
|
|
|
s.SetCookie(w, CookieOpts{
|
|
Value: chall.ID,
|
|
Host: r.Host,
|
|
Path: "/",
|
|
Name: anubis.TestCookieName,
|
|
Expiry: 30 * time.Minute,
|
|
})
|
|
|
|
impl, ok := challenge.Get(chall.Method)
|
|
if !ok {
|
|
algorithm := "unknown"
|
|
if rule.Challenge != nil {
|
|
algorithm = rule.Challenge.Algorithm
|
|
}
|
|
lg.ErrorContext(r.Context(), "check failed", "err", "can't get algorithm", "algorithm", algorithm)
|
|
s.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})
|
|
s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), algorithm), makeCode(err))
|
|
return
|
|
}
|
|
|
|
in := &challenge.IssueInput{
|
|
Impressum: s.policy.Impressum,
|
|
Rule: rule,
|
|
Challenge: chall,
|
|
OGTags: ogTags,
|
|
Store: s.store,
|
|
}
|
|
|
|
component, err := impl.Issue(w, r, lg, in)
|
|
if err != nil {
|
|
lg.ErrorContext(r.Context(), "[unexpected] challenge component render failed, please open an issue", "err", err) // This is likely a bug in the template. Should never be triggered as CI tests for this.
|
|
s.respondWithError(w, r, fmt.Sprintf("%s \"RenderIndex\"", localizer.T("internal_server_error")), makeCode(err))
|
|
return
|
|
}
|
|
|
|
component, err = mergeExtensions(r, chall, component)
|
|
if err != nil {
|
|
lg.ErrorContext(r.Context(), "can't render challenge extensions", "err", err, "note", ErrActualAnubisBug)
|
|
s.respondWithError(w, r, fmt.Sprintf(`%s "RenderIndex"`, localizer.T("internal_server_error")), makeCode(err))
|
|
return
|
|
}
|
|
|
|
page := web.BaseWithChallengeAndOGTags(
|
|
localizer.T("making_sure_not_bot"),
|
|
component,
|
|
s.policy.Impressum,
|
|
s.policy.Honeypot,
|
|
chall,
|
|
in.Rule.Challenge,
|
|
in.OGTags,
|
|
localizer,
|
|
)
|
|
|
|
handler := internal.GzipMiddleware(1, internal.NoStoreCache(templ.Handler(
|
|
page,
|
|
templ.WithStatus(s.opts.Policy.StatusCodes.Challenge),
|
|
)))
|
|
handler.ServeHTTP(w, r)
|
|
}
|
|
|
|
func (s *Server) constructRedirectURL(r *http.Request) (string, error) {
|
|
proto := r.Header.Get("X-Forwarded-Proto")
|
|
host := r.Header.Get("X-Forwarded-Host")
|
|
uri := r.Header.Get("X-Forwarded-Uri")
|
|
|
|
localizer := localization.GetLocalizer(r)
|
|
|
|
if proto == "" || host == "" || uri == "" {
|
|
return "", errors.New(localizer.T("missing_required_forwarded_headers"))
|
|
}
|
|
|
|
switch proto {
|
|
case "http", "https":
|
|
// allowed
|
|
default:
|
|
lg, _ := s.getRequestLogger(r)
|
|
lg.WarnContext(r.Context(), "invalid protocol in X-Forwarded-Proto", "proto", proto)
|
|
return "", errors.New(localizer.T("invalid_redirect"))
|
|
}
|
|
|
|
// Check if host is allowed in RedirectDomains (supports '*' via glob)
|
|
if len(s.opts.RedirectDomains) > 0 && !matchRedirectDomain(s.opts.RedirectDomains, host) {
|
|
lg, _ := s.getRequestLogger(r)
|
|
lg.DebugContext(r.Context(), "domain not allowed", "domain", host)
|
|
return "", errors.New(localizer.T("redirect_domain_not_allowed"))
|
|
}
|
|
|
|
redir := proto + "://" + host + uri
|
|
escapedURL := url.QueryEscape(redir)
|
|
return fmt.Sprintf("%s/.within.website/?redir=%s", s.opts.PublicUrl, escapedURL), nil
|
|
}
|
|
|
|
func (s *Server) RenderBench(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
localizer := localization.GetLocalizer(r)
|
|
|
|
templ.Handler(
|
|
web.Base(localizer.T("benchmarking_anubis"), web.Bench(localizer), s.policy.Impressum, s.policy.Honeypot, localizer),
|
|
).ServeHTTP(w, r)
|
|
}
|
|
|
|
func (s *Server) respondWithError(w http.ResponseWriter, r *http.Request, message, code string) {
|
|
s.respondWithStatus(w, r, message, code, http.StatusInternalServerError)
|
|
}
|
|
|
|
func (s *Server) respondWithStatus(w http.ResponseWriter, r *http.Request, msg, code string, status int) {
|
|
localizer := localization.GetLocalizer(r)
|
|
|
|
component := web.Base(
|
|
localizer.T("oh_noes"),
|
|
web.ErrorPage(msg, s.opts.WebmasterEmail, code, localizer),
|
|
s.policy.Impressum,
|
|
s.policy.Honeypot,
|
|
localizer,
|
|
)
|
|
handler := internal.NoStoreCache(templ.Handler(component, templ.WithStatus(status)))
|
|
handler.ServeHTTP(w, r)
|
|
}
|
|
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if strings.HasPrefix(r.URL.Path, anubis.BasePrefix+anubis.StaticPath) {
|
|
s.mux.ServeHTTP(w, r)
|
|
return
|
|
} else if strings.HasPrefix(r.URL.Path, anubis.BasePrefix+xess.BasePrefix) {
|
|
s.mux.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Forward robots.txt requests to mux when ServeRobotsTXT is enabled
|
|
if s.opts.ServeRobotsTXT {
|
|
path := strings.TrimPrefix(r.URL.Path, anubis.BasePrefix)
|
|
if path == "/robots.txt" || path == "/.well-known/robots.txt" {
|
|
s.mux.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
}
|
|
|
|
s.maybeReverseProxyOrPage(w, r)
|
|
}
|
|
|
|
func (s *Server) stripBasePrefixFromRequest(r *http.Request) *http.Request {
|
|
if !s.opts.StripBasePrefix || s.opts.BasePrefix == "" {
|
|
return r
|
|
}
|
|
|
|
basePrefix := strings.TrimSuffix(s.opts.BasePrefix, "/")
|
|
path := r.URL.Path
|
|
|
|
if !strings.HasPrefix(path, basePrefix) {
|
|
return r
|
|
}
|
|
|
|
trimmedPath := strings.TrimPrefix(path, basePrefix)
|
|
if trimmedPath == "" {
|
|
trimmedPath = "/"
|
|
}
|
|
|
|
// Clone the request and URL
|
|
reqCopy := r.Clone(r.Context())
|
|
urlCopy := *r.URL
|
|
urlCopy.Path = trimmedPath
|
|
reqCopy.URL = &urlCopy
|
|
|
|
return reqCopy
|
|
}
|
|
|
|
func (s *Server) ServeHTTPNext(w http.ResponseWriter, r *http.Request) {
|
|
if s.next == nil {
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
if !prepareChallengeForm(w, r) {
|
|
return
|
|
}
|
|
defer cleanupChallengeForm(r)
|
|
localizer := localization.GetLocalizer(r)
|
|
|
|
redir := r.FormValue("redir")
|
|
if _, err := s.validateRedirect(redir); err != nil {
|
|
s.rejectRedirect(w, r, err)
|
|
return
|
|
}
|
|
|
|
if redir != "" {
|
|
http.Redirect(w, r, redir, http.StatusFound)
|
|
return
|
|
}
|
|
|
|
templ.Handler(
|
|
web.Base(localizer.T("you_are_not_a_bot"), web.StaticHappy(localizer), s.policy.Impressum, s.policy.Honeypot, localizer),
|
|
).ServeHTTP(w, r)
|
|
} else {
|
|
asn, asnDesc := asnFromContext(r.Context())
|
|
requestsProxied.WithLabelValues(proxiedHostLabels.label(r.Host), asn, asnDesc).Inc()
|
|
r = s.stripBasePrefixFromRequest(r)
|
|
s.next.ServeHTTP(w, r)
|
|
}
|
|
}
|
|
|
|
func (s *Server) signJWT(claims jwt.MapClaims) (string, error) {
|
|
claims["iat"] = time.Now().Unix()
|
|
claims["nbf"] = time.Now().Add(-1 * time.Minute).Unix()
|
|
claims["exp"] = time.Now().Add(s.opts.CookieExpiration).Unix()
|
|
|
|
if len(s.hs512Secret) == 0 {
|
|
return jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(s.ed25519Priv)
|
|
} else {
|
|
return jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString(s.hs512Secret)
|
|
}
|
|
}
|