Compare commits
3 Commits
f5bcfdccb1
...
issue-108-
| Author | SHA1 | Date | |
|---|---|---|---|
| 618b07ca0f | |||
| d19e33671c | |||
| aab448b076 |
36
README.md
36
README.md
@@ -100,9 +100,10 @@ TTY detection, and security headers are always applied.
|
|||||||
#### Trusted proxies
|
#### Trusted proxies
|
||||||
|
|
||||||
`TRUSTED_PROXIES` is a comma-separated list of CIDR blocks (a bare
|
`TRUSTED_PROXIES` is a comma-separated list of CIDR blocks (a bare
|
||||||
address such as `10.0.0.1` is accepted and treated as a single host),
|
address such as `192.168.1.7` is accepted and treated as a single
|
||||||
for example `10.0.0.0/8, 192.168.1.7, 2001:db8::/32`. It decides whose
|
host), for example `192.168.1.7, 2001:db8::5`. It decides whose
|
||||||
`X-Forwarded-For` header the rate limiters believe.
|
`X-Forwarded-For` header the rate limiters believe, so it should name
|
||||||
|
the addresses of your reverse proxies and nothing else.
|
||||||
|
|
||||||
`X-Forwarded-For` is honoured **only** when the connecting peer is
|
`X-Forwarded-For` is honoured **only** when the connecting peer is
|
||||||
inside one of these blocks; for every other peer the client identity is
|
inside one of these blocks; for every other peer the client identity is
|
||||||
@@ -125,7 +126,8 @@ hop that is not itself a trusted proxy is taken as the client. A hop
|
|||||||
that is not a bare IP address — `ip:port`, a bracketed IPv6 literal,
|
that is not a bare IP address — `ip:port`, a bracketed IPv6 literal,
|
||||||
the token `unknown` — ends the walk and the peer address is used
|
the token `unknown` — ends the walk and the peer address is used
|
||||||
instead, since past such an entry the chain is not the shape assumed
|
instead, since past such an entry the chain is not the shape assumed
|
||||||
here.
|
here. The peer address is likewise used when the header is absent or
|
||||||
|
every hop in it is a trusted proxy.
|
||||||
|
|
||||||
Two operator requirements follow:
|
Two operator requirements follow:
|
||||||
|
|
||||||
@@ -133,12 +135,14 @@ Two operator requirements follow:
|
|||||||
(nginx `$proxy_add_x_forwarded_for`, HAProxy `option forwardfor`,
|
(nginx `$proxy_add_x_forwarded_for`, HAProxy `option forwardfor`,
|
||||||
Caddy and AWS ALB by default), and must append a bare address with
|
Caddy and AWS ALB by default), and must append a bare address with
|
||||||
no port.
|
no port.
|
||||||
- Keep the list narrow. A client whose own address falls inside a
|
- List proxy hosts **only**. Any address inside `TRUSTED_PROXIES`
|
||||||
broad block such as `10.0.0.0/8` is treated as a proxy: its address
|
chooses its own rate-limit key: its `X-Forwarded-For` is walked, so
|
||||||
is skipped during the walk, so it shares the bucket of whatever lies
|
it can name a different address on every request to get a fresh
|
||||||
further left rather than getting one of its own. That is safe — the
|
bucket each time, or name another client's address to drain that
|
||||||
block is trusted by definition — but surprising if the block covers
|
client's bucket. Never list a block that also covers clients — a
|
||||||
ordinary clients as well as proxies.
|
broad `10.0.0.0/8` on a network where clients live in the same range
|
||||||
|
makes all three limits, including the unauthenticated webhook
|
||||||
|
receiver, silently bypassable by every client in the block.
|
||||||
|
|
||||||
Sessions are bounded by two independent clocks, and end at whichever
|
Sessions are bounded by two independent clocks, and end at whichever
|
||||||
one runs out first:
|
one runs out first:
|
||||||
@@ -146,9 +150,10 @@ one runs out first:
|
|||||||
- **Idle expiry** (`SESSION_IDLE_TIMEOUT`, default `24h`) is a sliding
|
- **Idle expiry** (`SESSION_IDLE_TIMEOUT`, default `24h`) is a sliding
|
||||||
window. Every authenticated request pushes it forward, so a session
|
window. Every authenticated request pushes it forward, so a session
|
||||||
in continuous use never hits it, while an abandoned one expires a day
|
in continuous use never hits it, while an abandoned one expires a day
|
||||||
after its last use. Set it to `0` to disable idle expiry entirely;
|
after its last use. Any non-positive value (`0`, or a negative
|
||||||
the absolute cap below still applies. A set-but-unparseable value
|
duration such as `-1s`) disables idle expiry entirely; the absolute
|
||||||
aborts startup rather than silently falling back to the default.
|
cap below still applies. A set-but-unparseable value aborts startup
|
||||||
|
rather than silently falling back to the default.
|
||||||
- **Absolute expiry** is a fixed 7 days from login. Activity does
|
- **Absolute expiry** is a fixed 7 days from login. Activity does
|
||||||
**not** extend it: after a week, every session ends and the user
|
**not** extend it: after a week, every session ends and the user
|
||||||
authenticates again.
|
authenticates again.
|
||||||
@@ -160,6 +165,11 @@ idle window rather than on every request, which means a session may
|
|||||||
expire up to 10% early relative to the user's true last request, but
|
expire up to 10% early relative to the user's true last request, but
|
||||||
never late.
|
never late.
|
||||||
|
|
||||||
|
Both clocks are anchored by timestamps stored in the session cookie.
|
||||||
|
Sessions issued before this feature existed carry neither, so they are
|
||||||
|
treated as expired: upgrading to a build that has it logs every
|
||||||
|
existing session out once, and those users sign in again.
|
||||||
|
|
||||||
#### Invalid values abort startup
|
#### Invalid values abort startup
|
||||||
|
|
||||||
The defaults above apply **only** to variables that are unset (or set
|
The defaults above apply **only** to variables that are unset (or set
|
||||||
|
|||||||
4
TODO.md
4
TODO.md
@@ -26,6 +26,10 @@ capability in the README rationale).
|
|||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
|
- 2026-08-11 Web UI cleanup: nav terminology unified on Webhooks, the
|
||||||
|
Profile settings placeholder removed, a progressive-enhancement copy
|
||||||
|
button for the entrypoint URL, and retention form copy that states the
|
||||||
|
actual policy (deletion by the reaper, 0 retains forever) (#57)
|
||||||
- 2026-08-09 Inactivity-based session timeout: sliding idle expiry
|
- 2026-08-09 Inactivity-based session timeout: sliding idle expiry
|
||||||
(`SESSION_IDLE_TIMEOUT`, default `24h`) refreshed on authenticated
|
(`SESSION_IDLE_TIMEOUT`, default `24h`) refreshed on authenticated
|
||||||
requests, with the 7-day absolute cap kept as an independent
|
requests, with the 7-day absolute cap kept as an independent
|
||||||
|
|||||||
@@ -103,11 +103,14 @@ type Config struct {
|
|||||||
ReceiverRateLimit int
|
ReceiverRateLimit int
|
||||||
|
|
||||||
// TrustedProxies is the set of networks whose members are
|
// TrustedProxies is the set of networks whose members are
|
||||||
// allowed to speak for the client with forwarded headers
|
// allowed to speak for the client with X-Forwarded-For, the
|
||||||
// (X-Forwarded-For, X-Real-IP, True-Client-IP). It is empty
|
// only forwarded header read. It is empty unless
|
||||||
// unless TRUSTED_PROXIES is set, and empty means no peer is
|
// TRUSTED_PROXIES is set, and empty means no peer is
|
||||||
// trusted: forwarded headers are then ignored entirely and
|
// trusted: forwarded headers are then ignored entirely and
|
||||||
// clients are identified by the connection's own address.
|
// clients are identified by the connection's own address.
|
||||||
|
// Members can choose their own rate-limit key, so this must
|
||||||
|
// name proxy hosts only, never a block that also covers
|
||||||
|
// clients.
|
||||||
TrustedProxies []netip.Prefix
|
TrustedProxies []netip.Prefix
|
||||||
|
|
||||||
params *ConfigParams
|
params *ConfigParams
|
||||||
|
|||||||
299
internal/handlers/ui_copy_test.go
Normal file
299
internal/handlers/ui_copy_test.go
Normal file
@@ -0,0 +1,299 @@
|
|||||||
|
package handlers_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"sneak.berlin/go/webhooker/internal/database"
|
||||||
|
"sneak.berlin/go/webhooker/internal/delivery"
|
||||||
|
"sneak.berlin/go/webhooker/internal/handlers"
|
||||||
|
"sneak.berlin/go/webhooker/internal/session"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Template data keys the page templates read. The handlers package has
|
||||||
|
// its own unexported constants for these; this is the external test
|
||||||
|
// package, so it needs its own.
|
||||||
|
const (
|
||||||
|
dataKeyWebhook = "Webhook"
|
||||||
|
dataKeyError = "Error"
|
||||||
|
)
|
||||||
|
|
||||||
|
// testWebhookID is the identifier given to the webhook under test on
|
||||||
|
// pages that render one.
|
||||||
|
const testWebhookID = "wh-1"
|
||||||
|
|
||||||
|
// renderPage renders a page template through the real template set as
|
||||||
|
// an authenticated user and returns the resulting HTML.
|
||||||
|
func renderPage(
|
||||||
|
t *testing.T,
|
||||||
|
h *handlers.Handlers,
|
||||||
|
sess *session.Session,
|
||||||
|
page string,
|
||||||
|
data map[string]any,
|
||||||
|
) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
cookies := authenticatedCookies(t, sess, "test-user-id", "testuser")
|
||||||
|
|
||||||
|
req := httptest.NewRequestWithContext(
|
||||||
|
context.Background(), http.MethodGet, "/", nil,
|
||||||
|
)
|
||||||
|
for _, c := range cookies {
|
||||||
|
req.AddCookie(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.RenderTemplateForTest(w, req, page, data)
|
||||||
|
|
||||||
|
return w.Body.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNavbarUsesWebhookTerminology pins the user-visible navigation
|
||||||
|
// label to "Webhooks". The /sources route is deliberately unchanged, so
|
||||||
|
// the assertion targets the link text rather than the href.
|
||||||
|
func TestNavbarUsesWebhookTerminology(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var h *handlers.Handlers
|
||||||
|
|
||||||
|
var sess *session.Session
|
||||||
|
|
||||||
|
app := newTestApp(t, &h, &sess)
|
||||||
|
app.RequireStart()
|
||||||
|
|
||||||
|
t.Cleanup(app.RequireStop)
|
||||||
|
|
||||||
|
// One item, so the list body renders too: it calls
|
||||||
|
// WebhookListItem.RetentionLabel, promoted from the embedded
|
||||||
|
// Webhook and therefore a pointer method. An empty list would
|
||||||
|
// skip that call and hide a template error behind the
|
||||||
|
// navigation assertions below.
|
||||||
|
item := handlers.WebhookListItem{}
|
||||||
|
item.Name = "wh"
|
||||||
|
item.ID = testWebhookID
|
||||||
|
item.RetentionDays = 14
|
||||||
|
|
||||||
|
body := renderPage(t, h, sess, "sources_list.html", map[string]any{
|
||||||
|
"Webhooks": []handlers.WebhookListItem{item},
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Contains(t, body, "Retention: 14 days")
|
||||||
|
assert.Contains(t, body, `class="btn-text">Webhooks</a>`)
|
||||||
|
assert.Contains(
|
||||||
|
t, body, `class="btn-text w-full text-left">Webhooks</a>`,
|
||||||
|
)
|
||||||
|
assert.Contains(
|
||||||
|
t, body,
|
||||||
|
`<h1 class="text-2xl font-medium text-gray-900">Webhooks</h1>`,
|
||||||
|
)
|
||||||
|
assert.NotContains(
|
||||||
|
t, body, ">Sources<",
|
||||||
|
"no user-visible element may still be labelled Sources",
|
||||||
|
)
|
||||||
|
assert.Contains(
|
||||||
|
t, body, `href="/sources"`,
|
||||||
|
"the /sources route itself must not change",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEditPageUsesWebhookTerminology pins the edit page's heading and
|
||||||
|
// its back link. The link's href still points at /source/{id}, which is
|
||||||
|
// intentional: only user-visible copy changes.
|
||||||
|
func TestEditPageUsesWebhookTerminology(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var h *handlers.Handlers
|
||||||
|
|
||||||
|
var sess *session.Session
|
||||||
|
|
||||||
|
app := newTestApp(t, &h, &sess)
|
||||||
|
app.RequireStart()
|
||||||
|
|
||||||
|
t.Cleanup(app.RequireStop)
|
||||||
|
|
||||||
|
// The webhook goes in as a pointer because source_edit.html calls
|
||||||
|
// Webhook.RetentionLabel, a pointer method: a map element is not
|
||||||
|
// addressable, so a value here renders an error instead of the
|
||||||
|
// page.
|
||||||
|
webhook := &database.Webhook{Name: "wh", RetentionDays: 14}
|
||||||
|
webhook.ID = testWebhookID
|
||||||
|
|
||||||
|
body := renderPage(t, h, sess, "source_edit.html", map[string]any{
|
||||||
|
dataKeyWebhook: webhook,
|
||||||
|
dataKeyError: "",
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Contains(t, body, "Edit Webhook")
|
||||||
|
assert.NotContains(t, body, ">Sources<")
|
||||||
|
assert.Contains(t, body, `href="/source/wh-1"`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCreateFormRetentionCopyMatchesBehaviour pins the create form's
|
||||||
|
// retention copy to what the code does: the reaper permanently deletes
|
||||||
|
// events past the cutoff, an empty field falls back to
|
||||||
|
// DefaultRetentionDays, and 0 is rewritten to the retain-forever
|
||||||
|
// sentinel by Webhook.BeforeSave.
|
||||||
|
func TestCreateFormRetentionCopyMatchesBehaviour(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var h *handlers.Handlers
|
||||||
|
|
||||||
|
var sess *session.Session
|
||||||
|
|
||||||
|
app := newTestApp(t, &h, &sess)
|
||||||
|
app.RequireStart()
|
||||||
|
|
||||||
|
t.Cleanup(app.RequireStop)
|
||||||
|
|
||||||
|
body := renderPage(t, h, sess, "sources_new.html", map[string]any{
|
||||||
|
"Name": "",
|
||||||
|
"Description": "",
|
||||||
|
"DefaultRetentionDays": database.DefaultRetentionDays,
|
||||||
|
dataKeyError: "",
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Contains(
|
||||||
|
t, body,
|
||||||
|
"permanently deletes events older than this",
|
||||||
|
"the form must say retention is enforced by deletion",
|
||||||
|
)
|
||||||
|
assert.Contains(t, body, "Enter 0 to retain events forever")
|
||||||
|
assert.Contains(
|
||||||
|
t, body,
|
||||||
|
"leave blank to use the default of "+
|
||||||
|
strconv.Itoa(database.DefaultRetentionDays)+" days",
|
||||||
|
"blank means the default, not forever",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEditFormRetentionCopyMatchesBehaviour pins the edit form's
|
||||||
|
// retention copy, including that it states the stored policy via
|
||||||
|
// RetentionLabel and that an empty field leaves that policy unchanged
|
||||||
|
// rather than meaning forever.
|
||||||
|
func TestEditFormRetentionCopyMatchesBehaviour(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var h *handlers.Handlers
|
||||||
|
|
||||||
|
var sess *session.Session
|
||||||
|
|
||||||
|
app := newTestApp(t, &h, &sess)
|
||||||
|
app.RequireStart()
|
||||||
|
|
||||||
|
t.Cleanup(app.RequireStop)
|
||||||
|
|
||||||
|
finite := &database.Webhook{Name: "wh", RetentionDays: 14}
|
||||||
|
finite.ID = testWebhookID
|
||||||
|
|
||||||
|
body := renderPage(t, h, sess, "source_edit.html", map[string]any{
|
||||||
|
dataKeyWebhook: finite,
|
||||||
|
dataKeyError: "",
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Contains(t, body, "Currently 14 days.")
|
||||||
|
assert.Contains(
|
||||||
|
t, body,
|
||||||
|
"permanently deletes events older than this",
|
||||||
|
)
|
||||||
|
assert.Contains(t, body, "Enter 0 to retain events forever")
|
||||||
|
assert.Contains(
|
||||||
|
t, body,
|
||||||
|
"leave blank to keep the current setting",
|
||||||
|
"blank means unchanged, not forever",
|
||||||
|
)
|
||||||
|
|
||||||
|
forever := &database.Webhook{
|
||||||
|
Name: "wh",
|
||||||
|
RetentionDays: database.RetentionForeverDays,
|
||||||
|
}
|
||||||
|
forever.ID = "wh-2"
|
||||||
|
|
||||||
|
foreverBody := renderPage(
|
||||||
|
t, h, sess, "source_edit.html", map[string]any{
|
||||||
|
dataKeyWebhook: forever,
|
||||||
|
dataKeyError: "",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert.Contains(
|
||||||
|
t, foreverBody, "Currently forever.",
|
||||||
|
"a retain-forever webhook must not read as a day count",
|
||||||
|
)
|
||||||
|
assert.Contains(
|
||||||
|
t, foreverBody,
|
||||||
|
"No events are deleted while retention is set to forever",
|
||||||
|
)
|
||||||
|
assert.NotContains(
|
||||||
|
t, foreverBody,
|
||||||
|
"permanently deletes events older than this",
|
||||||
|
"the reaper skips retain-forever webhooks, so the form "+
|
||||||
|
"must not claim it deletes their events",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntrypointCopyButtonIsProgressiveEnhancement proves the copy
|
||||||
|
// affordance degrades: the button ships with the hidden attribute, so a
|
||||||
|
// browser that never runs app.js shows no dead control, and the URL is
|
||||||
|
// rendered as ordinary selectable text either way.
|
||||||
|
func TestEntrypointCopyButtonIsProgressiveEnhancement(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var h *handlers.Handlers
|
||||||
|
|
||||||
|
var sess *session.Session
|
||||||
|
|
||||||
|
app := newTestApp(t, &h, &sess)
|
||||||
|
app.RequireStart()
|
||||||
|
|
||||||
|
t.Cleanup(app.RequireStop)
|
||||||
|
|
||||||
|
entrypoint := database.Entrypoint{Path: "abc123"}
|
||||||
|
entrypoint.ID = "ep-1"
|
||||||
|
|
||||||
|
// The webhook goes in as a pointer because source_detail.html
|
||||||
|
// calls Webhook.RetentionLabel, a pointer method: a map element
|
||||||
|
// is not addressable, so a value here aborts execution partway
|
||||||
|
// down the page, after the copy button has already been flushed
|
||||||
|
// to the response.
|
||||||
|
webhook := &database.Webhook{Name: "wh", RetentionDays: 14}
|
||||||
|
webhook.ID = testWebhookID
|
||||||
|
webhook.CreatedAt = time.Date(
|
||||||
|
2026, time.January, 2, 3, 4, 5, 0, time.UTC,
|
||||||
|
)
|
||||||
|
|
||||||
|
body := renderPage(t, h, sess, "source_detail.html", map[string]any{
|
||||||
|
dataKeyWebhook: webhook,
|
||||||
|
"Entrypoints": []database.Entrypoint{entrypoint},
|
||||||
|
// The handler passes delivery.NewTargetViews(targets), never
|
||||||
|
// raw targets, so the test data has to have that same shape.
|
||||||
|
"Targets": delivery.NewTargetViews(nil),
|
||||||
|
"Events": []database.Event{},
|
||||||
|
"BaseURL": "https://hooks.example.com",
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Contains(
|
||||||
|
t, body,
|
||||||
|
`<code id="entrypoint-url-ep-1"`,
|
||||||
|
)
|
||||||
|
assert.Contains(t, body, "https://hooks.example.com/webhook/abc123")
|
||||||
|
assert.Contains(
|
||||||
|
t, body,
|
||||||
|
`hidden data-copy-target="entrypoint-url-ep-1"`,
|
||||||
|
"the button must start hidden and be revealed by script",
|
||||||
|
)
|
||||||
|
|
||||||
|
// renderTemplate streams to the ResponseWriter, so an abort
|
||||||
|
// midway still leaves everything above it in the body. This pins
|
||||||
|
// content from the last line of the template, which is below the
|
||||||
|
// assertions above: without it, a page that renders the copy
|
||||||
|
// button and then 500s passes.
|
||||||
|
assert.Contains(
|
||||||
|
t, body, "Retention: 14 days",
|
||||||
|
"the page must render to completion, not abort partway",
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -214,11 +214,11 @@ func (s *Middleware) RequireAuth() func(http.Handler) http.Handler {
|
|||||||
// handler runs, while the headers are still ours to
|
// handler runs, while the headers are still ours to
|
||||||
// write.
|
// write.
|
||||||
if s.session.Touch(sess) {
|
if s.session.Touch(sess) {
|
||||||
err = s.session.Save(r, w, sess)
|
saveErr := s.session.Save(r, w, sess)
|
||||||
if err != nil {
|
if saveErr != nil {
|
||||||
s.log.Error(
|
s.log.Error(
|
||||||
"auth middleware: failed to refresh session",
|
"auth middleware: failed to refresh session",
|
||||||
"error", err,
|
"error", saveErr,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
150
internal/session/codec_test.go
Normal file
150
internal/session/codec_test.go
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
package session_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/sessions"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/webhooker/internal/session"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The tests below exercise the securecookie codecs underneath the
|
||||||
|
// store and nothing else: Session.Get only decodes, so no server-side
|
||||||
|
// expiry check takes part in the result. They exist because
|
||||||
|
// NewCookieStore gives its codecs a 30-day max age that assigning
|
||||||
|
// store.Options does not override, which would let the codec accept a
|
||||||
|
// cookie weeks past the cap the cookie attribute advertises.
|
||||||
|
|
||||||
|
// issuedCookie returns a session cookie the store itself wrote.
|
||||||
|
func issuedCookie(t *testing.T, s *session.Session) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
req := httptest.NewRequestWithContext(
|
||||||
|
context.Background(), http.MethodGet, "/", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
sess, err := s.Get(req)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
sess.Values["probe"] = "value"
|
||||||
|
require.NoError(t, s.Save(req, w, sess))
|
||||||
|
|
||||||
|
cookies := w.Result().Cookies()
|
||||||
|
require.Len(t, cookies, 1)
|
||||||
|
|
||||||
|
return cookies[0].Value
|
||||||
|
}
|
||||||
|
|
||||||
|
// restamp rewrites the timestamp inside an encoded session cookie and
|
||||||
|
// re-signs it, yielding the cookie the store would have written at
|
||||||
|
// that instant. securecookie stamps the encoding time itself and
|
||||||
|
// exposes no seam to move it, so its wire format is reproduced here:
|
||||||
|
// the base64url payload is "date|value|mac", where mac is HMAC-SHA256
|
||||||
|
// of "name|date|value" under the store's key.
|
||||||
|
func restamp(
|
||||||
|
t *testing.T,
|
||||||
|
encoded string,
|
||||||
|
at time.Time,
|
||||||
|
) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
raw, err := base64.URLEncoding.DecodeString(encoded)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
parts := strings.SplitN(string(raw), "|", 3)
|
||||||
|
require.Len(t, parts, 3)
|
||||||
|
|
||||||
|
stamped := fmt.Sprintf("%d|%s", at.Unix(), parts[1])
|
||||||
|
|
||||||
|
mac := hmac.New(sha256.New, testKey())
|
||||||
|
_, err = mac.Write([]byte(session.SessionName + "|" + stamped))
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
payload := append([]byte(stamped+"|"), mac.Sum(nil)...)
|
||||||
|
|
||||||
|
return base64.URLEncoding.EncodeToString(payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeCookie feeds value back through the store's decode path.
|
||||||
|
func decodeCookie(
|
||||||
|
t *testing.T,
|
||||||
|
s *session.Session,
|
||||||
|
value string,
|
||||||
|
) (*sessions.Session, error) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
req := httptest.NewRequestWithContext(
|
||||||
|
context.Background(), http.MethodGet, "/", nil)
|
||||||
|
req.AddCookie(&http.Cookie{
|
||||||
|
Name: session.SessionName,
|
||||||
|
Value: value,
|
||||||
|
Path: "/",
|
||||||
|
HttpOnly: true,
|
||||||
|
Secure: true,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
})
|
||||||
|
|
||||||
|
sess, err := s.Get(req)
|
||||||
|
require.NotNil(t, sess)
|
||||||
|
|
||||||
|
return sess, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCodec_AcceptsCookieInsideAbsoluteCap(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
s := testSession(t)
|
||||||
|
|
||||||
|
sess, err := decodeCookie(t, s, restamp(
|
||||||
|
t,
|
||||||
|
issuedCookie(t, s),
|
||||||
|
time.Now().Add(-(testAbsoluteMaxAge-time.Hour)),
|
||||||
|
))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.False(
|
||||||
|
t, sess.IsNew,
|
||||||
|
"a cookie inside the cap must still decode",
|
||||||
|
)
|
||||||
|
assert.Equal(
|
||||||
|
t, "value", sess.Values["probe"],
|
||||||
|
"decoding must yield the values that were saved",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCodec_RejectsCookiePastAbsoluteCap(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
s := testSession(t)
|
||||||
|
|
||||||
|
sess, err := decodeCookie(t, s, restamp(
|
||||||
|
t,
|
||||||
|
issuedCookie(t, s),
|
||||||
|
time.Now().Add(-(testAbsoluteMaxAge+time.Hour)),
|
||||||
|
))
|
||||||
|
require.Error(
|
||||||
|
t, err,
|
||||||
|
"the codec must refuse a cookie older than the cap",
|
||||||
|
)
|
||||||
|
assert.Contains(
|
||||||
|
t, err.Error(), "expired timestamp",
|
||||||
|
"rejection must come from the codec's age check",
|
||||||
|
)
|
||||||
|
assert.True(
|
||||||
|
t, sess.IsNew,
|
||||||
|
"a cookie past the cap must not populate a session",
|
||||||
|
)
|
||||||
|
assert.Nil(
|
||||||
|
t, sess.Values["probe"],
|
||||||
|
"a cookie past the cap must not yield its values",
|
||||||
|
)
|
||||||
|
}
|
||||||
10
internal/session/export_test.go
Normal file
10
internal/session/export_test.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package session
|
||||||
|
|
||||||
|
import "github.com/gorilla/sessions"
|
||||||
|
|
||||||
|
// NewStore exposes the production cookie-store constructor so tests
|
||||||
|
// exercise the store the application actually runs with, rather than a
|
||||||
|
// lookalike assembled in the test.
|
||||||
|
func NewStore(key []byte, secure bool) *sessions.CookieStore {
|
||||||
|
return newStore(key, secure)
|
||||||
|
}
|
||||||
@@ -100,6 +100,35 @@ type Session struct {
|
|||||||
now func() time.Time
|
now func() time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cookieOptions returns the cookie attributes used for every session
|
||||||
|
// cookie. MaxAge is deliberately left at its zero value: for a store
|
||||||
|
// it is set through CookieStore.MaxAge (see newStore), and for a
|
||||||
|
// single session it is copied from the store's options.
|
||||||
|
func cookieOptions(secure bool) *sessions.Options {
|
||||||
|
return &sessions.Options{
|
||||||
|
Path: "/",
|
||||||
|
HttpOnly: true,
|
||||||
|
Secure: secure,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newStore builds the session cookie store.
|
||||||
|
//
|
||||||
|
// The absolute cap MUST be applied with store.MaxAge and not by
|
||||||
|
// assigning store.Options.MaxAge. NewCookieStore gives the underlying
|
||||||
|
// securecookie codecs a 30-day max age of their own, and assigning
|
||||||
|
// Options never touches Codecs -- so a store configured that way still
|
||||||
|
// decodes a 30-day-old cookie, leaving the cookie attribute and the
|
||||||
|
// codec disagreeing about the same policy. store.MaxAge sets both.
|
||||||
|
func newStore(key []byte, secure bool) *sessions.CookieStore {
|
||||||
|
store := sessions.NewCookieStore(key)
|
||||||
|
store.Options = cookieOptions(secure)
|
||||||
|
store.MaxAge(secondsPerDay * sessionMaxAgeDays)
|
||||||
|
|
||||||
|
return store
|
||||||
|
}
|
||||||
|
|
||||||
// New creates a new session manager. The cookie store is
|
// New creates a new session manager. The cookie store is
|
||||||
// initialized during the fx OnStart phase after the database is
|
// initialized during the fx OnStart phase after the database is
|
||||||
// connected, using a session key that is auto-generated and stored
|
// connected, using a session key that is auto-generated and stored
|
||||||
@@ -142,19 +171,8 @@ func New(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
store := sessions.NewCookieStore(keyBytes)
|
|
||||||
|
|
||||||
// Configure cookie options for security
|
|
||||||
store.Options = &sessions.Options{
|
|
||||||
Path: "/",
|
|
||||||
MaxAge: secondsPerDay * sessionMaxAgeDays,
|
|
||||||
HttpOnly: true,
|
|
||||||
Secure: !params.Config.IsDev(),
|
|
||||||
SameSite: http.SameSiteLaxMode,
|
|
||||||
}
|
|
||||||
|
|
||||||
s.key = keyBytes
|
s.key = keyBytes
|
||||||
s.store = store
|
s.store = newStore(keyBytes, !params.Config.IsDev())
|
||||||
s.log.Info("session manager initialized")
|
s.log.Info("session manager initialized")
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -350,13 +368,8 @@ func (s *Session) Regenerate(
|
|||||||
// Apply the standard session options (the destroyed old
|
// Apply the standard session options (the destroyed old
|
||||||
// session had MaxAge = -1, which store.New might inherit
|
// session had MaxAge = -1, which store.New might inherit
|
||||||
// from the cookie).
|
// from the cookie).
|
||||||
newSess.Options = &sessions.Options{
|
newSess.Options = cookieOptions(!s.config.IsDev())
|
||||||
Path: "/",
|
newSess.Options.MaxAge = secondsPerDay * sessionMaxAgeDays
|
||||||
MaxAge: secondsPerDay * sessionMaxAgeDays,
|
|
||||||
HttpOnly: true,
|
|
||||||
Secure: !s.config.IsDev(),
|
|
||||||
SameSite: http.SameSiteLaxMode,
|
|
||||||
}
|
|
||||||
|
|
||||||
return newSess, nil
|
return newSess, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,19 @@ func (c *fakeClock) Advance(d time.Duration) {
|
|||||||
c.t = c.t.Add(d)
|
c.t = c.t.Add(d)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// testKey returns the fixed session key the tests sign with. The
|
||||||
|
// codec tests re-sign cookies with it, so it must be the same key the
|
||||||
|
// store was built from.
|
||||||
|
func testKey() []byte {
|
||||||
|
key := make([]byte, testKeySize)
|
||||||
|
|
||||||
|
for i := range key {
|
||||||
|
key[i] = byte(i + 42)
|
||||||
|
}
|
||||||
|
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
|
||||||
// testSession creates a Session with a real cookie store and the
|
// testSession creates a Session with a real cookie store and the
|
||||||
// real clock.
|
// real clock.
|
||||||
func testSession(t *testing.T) *session.Session {
|
func testSession(t *testing.T) *session.Session {
|
||||||
@@ -59,20 +72,8 @@ func testSessionWithClock(
|
|||||||
) (*session.Session, *fakeClock) {
|
) (*session.Session, *fakeClock) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
key := make([]byte, testKeySize)
|
key := testKey()
|
||||||
|
store := session.NewStore(key, false)
|
||||||
for i := range key {
|
|
||||||
key[i] = byte(i + 42)
|
|
||||||
}
|
|
||||||
|
|
||||||
store := sessions.NewCookieStore(key)
|
|
||||||
store.Options = &sessions.Options{
|
|
||||||
Path: "/",
|
|
||||||
MaxAge: 86400 * 7,
|
|
||||||
HttpOnly: true,
|
|
||||||
Secure: false,
|
|
||||||
SameSite: http.SameSiteLaxMode,
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := &config.Config{
|
cfg := &config.Config{
|
||||||
Environment: config.EnvironmentDev,
|
Environment: config.EnvironmentDev,
|
||||||
@@ -645,6 +646,34 @@ func TestTouch_LazyBelowRefreshThreshold(t *testing.T) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTouch_RefreshThresholdIsOneTenthOfIdleWindow(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// testRefreshDivisor restates the documented bound independently
|
||||||
|
// of the implementation constant: the idle timestamp is rewritten
|
||||||
|
// once it is a tenth of the idle window old, which is what makes
|
||||||
|
// "expires up to 10% early, never late" true. Both assertions are
|
||||||
|
// needed to pin it -- a larger divisor fails the first, a smaller
|
||||||
|
// one fails the second.
|
||||||
|
const testRefreshDivisor = 10
|
||||||
|
|
||||||
|
threshold := testIdleTimeout / testRefreshDivisor
|
||||||
|
|
||||||
|
s, sess, clock := authenticatedSession(t, testIdleTimeout)
|
||||||
|
|
||||||
|
clock.Advance(threshold - time.Second)
|
||||||
|
assert.False(
|
||||||
|
t, s.Touch(sess),
|
||||||
|
"Touch must not rewrite the session below a tenth of the window",
|
||||||
|
)
|
||||||
|
|
||||||
|
clock.Advance(time.Second)
|
||||||
|
assert.True(
|
||||||
|
t, s.Touch(sess),
|
||||||
|
"Touch must rewrite the session at a tenth of the window",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
func TestTouch_UnauthenticatedSessionIsNotRefreshed(t *testing.T) {
|
func TestTouch_UnauthenticatedSessionIsNotRefreshed(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
@@ -1,2 +1,60 @@
|
|||||||
// Webhooker client-side JavaScript
|
// Webhooker client-side JavaScript
|
||||||
console.log("Webhooker loaded");
|
console.log("Webhooker loaded");
|
||||||
|
|
||||||
|
// Copy-to-clipboard, as progressive enhancement.
|
||||||
|
//
|
||||||
|
// Markup renders each copy button with the `hidden` attribute and a
|
||||||
|
// `data-copy-target` pointing at the id of the element holding the
|
||||||
|
// text. This script reveals a button only once it has both a resolvable
|
||||||
|
// target and a usable Clipboard API, so a browser without either shows
|
||||||
|
// no button at all and the text stays selectable.
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const revertDelayMs = 2000;
|
||||||
|
|
||||||
|
function flash(button, message) {
|
||||||
|
const original = button.getAttribute("data-copy-label");
|
||||||
|
button.textContent = message;
|
||||||
|
window.setTimeout(function () {
|
||||||
|
button.textContent = original;
|
||||||
|
}, revertDelayMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function wire(button) {
|
||||||
|
const target = document.getElementById(
|
||||||
|
button.getAttribute("data-copy-target")
|
||||||
|
);
|
||||||
|
if (!target) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
button.setAttribute("data-copy-label", button.textContent);
|
||||||
|
button.addEventListener("click", function () {
|
||||||
|
navigator.clipboard.writeText(target.textContent.trim()).then(
|
||||||
|
function () {
|
||||||
|
flash(button, "Copied");
|
||||||
|
},
|
||||||
|
function () {
|
||||||
|
flash(button, "Copy failed");
|
||||||
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
button.removeAttribute("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
if (!navigator.clipboard || !navigator.clipboard.writeText) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const buttons = document.querySelectorAll("[data-copy-target]");
|
||||||
|
buttons.forEach(wire);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.readyState === "loading") {
|
||||||
|
document.addEventListener("DOMContentLoaded", init);
|
||||||
|
} else {
|
||||||
|
init();
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
<!-- Desktop navigation -->
|
<!-- Desktop navigation -->
|
||||||
<div class="hidden md:flex items-center gap-4">
|
<div class="hidden md:flex items-center gap-4">
|
||||||
{{if .User}}
|
{{if .User}}
|
||||||
<a href="/sources" class="btn-text">Sources</a>
|
<a href="/sources" class="btn-text">Webhooks</a>
|
||||||
<a href="/user/{{.User.Username}}" class="btn-text">
|
<a href="/user/{{.User.Username}}" class="btn-text">
|
||||||
<svg class="w-5 h-5 mr-1" fill="currentColor" viewBox="0 0 16 16">
|
<svg class="w-5 h-5 mr-1" fill="currentColor" viewBox="0 0 16 16">
|
||||||
<path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"/>
|
<path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"/>
|
||||||
@@ -38,7 +38,7 @@
|
|||||||
<div x-show="open" x-cloak x-transition class="md:hidden mt-4 pt-4 border-t border-gray-200">
|
<div x-show="open" x-cloak x-transition class="md:hidden mt-4 pt-4 border-t border-gray-200">
|
||||||
<div class="flex flex-col gap-2">
|
<div class="flex flex-col gap-2">
|
||||||
{{if .User}}
|
{{if .User}}
|
||||||
<a href="/sources" class="btn-text w-full text-left">Sources</a>
|
<a href="/sources" class="btn-text w-full text-left">Webhooks</a>
|
||||||
<a href="/user/{{.User.Username}}" class="btn-text w-full text-left">Profile</a>
|
<a href="/user/{{.User.Username}}" class="btn-text w-full text-left">Profile</a>
|
||||||
<form method="POST" action="/pages/logout">
|
<form method="POST" action="/pages/logout">
|
||||||
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
||||||
|
|||||||
@@ -34,7 +34,6 @@
|
|||||||
|
|
||||||
<hr class="border-gray-200 mb-6">
|
<hr class="border-gray-200 mb-6">
|
||||||
|
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
|
|
||||||
<div>
|
<div>
|
||||||
<h3 class="text-lg font-medium text-gray-900 mb-3">Account Information</h3>
|
<h3 class="text-lg font-medium text-gray-900 mb-3">Account Information</h3>
|
||||||
<dl class="space-y-3">
|
<dl class="space-y-3">
|
||||||
@@ -48,11 +47,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</dl>
|
</dl>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<h3 class="text-lg font-medium text-gray-900 mb-3">Settings</h3>
|
|
||||||
<p class="text-sm text-gray-500">Profile settings and preferences will be available here.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card p-6 mt-6">
|
<div class="card p-6 mt-6">
|
||||||
|
|||||||
@@ -69,7 +69,12 @@
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<code class="text-xs text-gray-500 break-all block mt-1">{{$.BaseURL}}/webhook/{{.Path}}</code>
|
<div class="flex items-start gap-2 mt-1">
|
||||||
|
<code id="entrypoint-url-{{.ID}}" class="text-xs text-gray-500 break-all block flex-1">{{$.BaseURL}}/webhook/{{.Path}}</code>
|
||||||
|
<!-- Hidden until app.js reveals it; without the
|
||||||
|
script the URL above stays selectable. -->
|
||||||
|
<button type="button" hidden data-copy-target="entrypoint-url-{{.ID}}" class="text-xs text-gray-500 hover:text-primary-600">Copy</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{{else}}
|
{{else}}
|
||||||
<div class="p-4 text-sm text-gray-500">No entrypoints configured.</div>
|
<div class="p-4 text-sm text-gray-500">No entrypoints configured.</div>
|
||||||
|
|||||||
@@ -29,7 +29,7 @@
|
|||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="retention_days" class="label">Retention (days)</label>
|
<label for="retention_days" class="label">Retention (days)</label>
|
||||||
<input type="number" id="retention_days" name="retention_days" value="{{.Webhook.RetentionDays}}" min="0" class="input">
|
<input type="number" id="retention_days" name="retention_days" value="{{.Webhook.RetentionDays}}" min="0" class="input">
|
||||||
<p class="text-xs text-gray-500 mt-1">Currently {{.Webhook.RetentionLabel}}. Enter 0 to retain events forever.</p>
|
<p class="text-xs text-gray-500 mt-1">Currently {{.Webhook.RetentionLabel}}.{{if .Webhook.RetainsForever}} No events are deleted while retention is set to forever.{{else}} A periodic cleanup permanently deletes events older than this, along with their delivery records.{{end}} Enter 0 to retain events forever; leave blank to keep the current setting.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex gap-3">
|
<div class="flex gap-3">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{{template "base" .}}
|
{{template "base" .}}
|
||||||
|
|
||||||
{{define "title"}}Sources - Webhooker{{end}}
|
{{define "title"}}Webhooks - Webhooker{{end}}
|
||||||
|
|
||||||
{{define "content"}}
|
{{define "content"}}
|
||||||
<div class="max-w-6xl mx-auto px-6 py-8">
|
<div class="max-w-6xl mx-auto px-6 py-8">
|
||||||
|
|||||||
@@ -29,7 +29,7 @@
|
|||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="retention_days" class="label">Retention (days)</label>
|
<label for="retention_days" class="label">Retention (days)</label>
|
||||||
<input type="number" id="retention_days" name="retention_days" value="{{.DefaultRetentionDays}}" min="0" class="input">
|
<input type="number" id="retention_days" name="retention_days" value="{{.DefaultRetentionDays}}" min="0" class="input">
|
||||||
<p class="text-xs text-gray-500 mt-1">How long to keep event data. Enter 0 to retain events forever.</p>
|
<p class="text-xs text-gray-500 mt-1">A periodic cleanup permanently deletes events older than this, along with their delivery records. Enter 0 to retain events forever; leave blank to use the default of {{.DefaultRetentionDays}} days.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex gap-3">
|
<div class="flex gap-3">
|
||||||
|
|||||||
Reference in New Issue
Block a user