Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lx9FNLG2CqeBbVGGd9bFsP
151 lines
5.6 KiB
Go
151 lines
5.6 KiB
Go
package auth_test
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/v10networks/nmon/internal/auth"
|
|
"github.com/v10networks/nmon/internal/auth/oidctest"
|
|
)
|
|
|
|
func TestCookieMutationsNeedTheCSRFToken(t *testing.T) {
|
|
e := newEnv(t, envOpts{})
|
|
c := e.login(oidctest.User{Sub: "a1", Groups: []string{"nmon-admins"}})
|
|
url := e.srv.URL + "/api/v1/things"
|
|
if code, _ := call(t, c, http.MethodPut, url, nil, "{}"); code != http.StatusForbidden {
|
|
t.Fatalf("PUT without CSRF token: %d", code)
|
|
}
|
|
if code, _ := call(t, c, http.MethodPut, url, map[string]string{auth.CSRFHeader: "wrong"}, "{}"); code != http.StatusForbidden {
|
|
t.Fatalf("PUT with wrong CSRF token: %d", code)
|
|
}
|
|
if code, _ := call(t, c, http.MethodPut, url, map[string]string{auth.CSRFHeader: e.csrfOf(c)}, "{}"); code != http.StatusOK {
|
|
t.Fatalf("PUT with CSRF token: %d", code)
|
|
}
|
|
for _, m := range []string{http.MethodGet, http.MethodHead, http.MethodOptions} {
|
|
if code, _ := call(t, c, m, url, nil, ""); code == http.StatusForbidden {
|
|
t.Errorf("%s must be CSRF-exempt, got 403", m)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestOneSessionsCSRFTokenDoesNotWorkForAnother(t *testing.T) {
|
|
e := newEnv(t, envOpts{})
|
|
a := e.login(oidctest.User{Sub: "a1", Groups: []string{"nmon-admins"}})
|
|
b := e.login(oidctest.User{Sub: "a2", Groups: []string{"nmon-admins"}})
|
|
if code, _ := call(t, a, http.MethodPut, e.srv.URL+"/api/v1/things", map[string]string{auth.CSRFHeader: e.csrfOf(b)}, "{}"); code != http.StatusForbidden {
|
|
t.Fatalf("CSRF token of another session accepted: %d", code)
|
|
}
|
|
}
|
|
|
|
func TestSessionCookieAttributes(t *testing.T) {
|
|
e := newEnv(t, envOpts{})
|
|
secure, err := auth.New(context.Background(), auth.Options{Store: e.st, Clock: e.clk})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ck, err := secure.Sessions.Create(context.Background(), auth.Identity{Subject: "oidc:x", Role: auth.RoleViewer}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !ck.HttpOnly || !ck.Secure || ck.SameSite != http.SameSiteLaxMode || ck.Path != "/" {
|
|
t.Fatalf("cookie attributes: %+v", ck)
|
|
}
|
|
parts := strings.Split(ck.Value, ".")
|
|
if len(parts) != 3 {
|
|
t.Fatalf("cookie %q is not version.payload.mac", ck.Value)
|
|
}
|
|
// The payload is a 256-bit random id.
|
|
if got := len(parts[1]); got != 43 {
|
|
t.Fatalf("session id is %d base64 chars, want 43 (256 bits)", got)
|
|
}
|
|
}
|
|
|
|
func TestForgedAndTamperedCookiesAreRejected(t *testing.T) {
|
|
e := newEnv(t, envOpts{})
|
|
c := e.login(oidctest.User{Sub: "v1"})
|
|
good := c.Jar.Cookies(mustURL(t, e.srv.URL))[0]
|
|
for name, val := range map[string]string{
|
|
"flipped mac": good.Value[:len(good.Value)-2] + "AA",
|
|
"no signature": strings.Join(strings.Split(good.Value, ".")[:2], "."),
|
|
"random": "AAAA",
|
|
"unknown key": "99." + strings.Split(good.Value, ".")[1] + "." + strings.Split(good.Value, ".")[2],
|
|
"payload swap": strings.Split(good.Value, ".")[0] + ".AAAA." + strings.Split(good.Value, ".")[2],
|
|
"empty payload": "1..",
|
|
} {
|
|
r := httptest.NewRequest(http.MethodGet, "/api/v1/whoami", nil)
|
|
r.AddCookie(&http.Cookie{Name: auth.DefaultCookieName, Value: val})
|
|
w := httptest.NewRecorder()
|
|
e.auth.Middleware(http.NotFoundHandler()).ServeHTTP(w, r)
|
|
if w.Code != http.StatusUnauthorized {
|
|
t.Errorf("%s: %d", name, w.Code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSessionsExpireWhenIdleAndAtTheAbsoluteLimit(t *testing.T) {
|
|
e := newEnv(t, envOpts{session: auth.SessionConfig{Idle: 10 * time.Minute, Absolute: time.Hour}})
|
|
c := e.login(oidctest.User{Sub: "v1"})
|
|
for i := 0; i < 5; i++ { // activity keeps it alive past the idle limit...
|
|
e.clk.Advance(8 * time.Minute)
|
|
if code, _ := whoami(t, e, c); code != http.StatusOK {
|
|
t.Fatalf("active session died at step %d: %d", i, code)
|
|
}
|
|
}
|
|
e.clk.Advance(30 * time.Minute) // ...but at 70 minutes the absolute limit has passed
|
|
if code, _ := whoami(t, e, c); code != http.StatusUnauthorized {
|
|
t.Fatalf("absolute timeout: %d", code)
|
|
}
|
|
c2 := e.login(oidctest.User{Sub: "v2"})
|
|
e.clk.Advance(11 * time.Minute)
|
|
if code, _ := whoami(t, e, c2); code != http.StatusUnauthorized {
|
|
t.Fatalf("idle timeout: %d", code)
|
|
}
|
|
}
|
|
|
|
func TestSigningKeyRotationKeepsExistingSessionsValid(t *testing.T) {
|
|
e := newEnv(t, envOpts{})
|
|
c := e.login(oidctest.User{Sub: "v1"})
|
|
before := c.Jar.Cookies(mustURL(t, e.srv.URL))[0].Value
|
|
if err := e.auth.RotateSigningKey(context.Background()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, _ := whoami(t, e, c); code != http.StatusOK {
|
|
t.Fatalf("session signed with the previous key: %d", code)
|
|
}
|
|
fresh := e.login(oidctest.User{Sub: "v2"})
|
|
after := fresh.Jar.Cookies(mustURL(t, e.srv.URL))[0].Value
|
|
if strings.Split(before, ".")[0] == strings.Split(after, ".")[0] {
|
|
t.Fatalf("new sessions must be signed with the new key (both v%s)", strings.Split(after, ".")[0])
|
|
}
|
|
// Once the absolute lifetime has passed, housekeeping drops the old key and its cookies with it.
|
|
e.clk.Advance(13 * time.Hour)
|
|
if err := e.auth.RotateSigningKey(context.Background()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, _ := whoami(t, e, c); code != http.StatusUnauthorized {
|
|
t.Fatalf("cookie of a dropped key: %d", code)
|
|
}
|
|
}
|
|
|
|
func TestRunRotatesAnOldSigningKey(t *testing.T) {
|
|
e := newEnv(t, envOpts{})
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
done := make(chan struct{})
|
|
go func() { e.auth.Run(ctx); close(done) }()
|
|
t.Cleanup(func() { cancel(); <-done })
|
|
c := e.login(oidctest.User{Sub: "v1"})
|
|
first := c.Jar.Cookies(mustURL(t, e.srv.URL))[0].Value
|
|
for e.clk.Waiters() == 0 { // Run is parked on its hourly ticker
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
e.clk.Advance(31 * 24 * time.Hour)
|
|
eventually(t, func() bool {
|
|
n := e.login(oidctest.User{Sub: "v2"})
|
|
return strings.Split(n.Jar.Cookies(mustURL(t, e.srv.URL))[0].Value, ".")[0] != strings.Split(first, ".")[0]
|
|
})
|
|
}
|