Files
coredns-web-ui/auth_test.go
T
bryanpedini 99fa5de747 feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders
- feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders
- feat(cli): add check and audit commands
- feat(api): add api framework, login, page routes and account, user, delegation and audit handlers
- test(auth): cover passwords, sessions, rate limiter, authorization and audit builders
- test(api): cover the api framework, sessions, client origin, headers and cross-origin refusal
- test(api): cover account, user, delegation and audit handlers and the authorization matrix
- test(ui): cover login, logout, page routes and the page authorization matrix
2026-11-19 15:46:12 +01:00

314 lines
11 KiB
Go
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"bytes"
"crypto/sha256"
"database/sql"
"encoding/base64"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestHashAndVerifyPassword(t *testing.T) {
salt := bytes.Repeat([]byte{7}, 16)
h, err := hashPasswordWith(bytes.NewReader(salt), "correct horse battery")
if err != nil {
t.Fatal(err)
}
want := "$argon2id$v=19$m=65536,t=3,p=2$" + base64.RawStdEncoding.EncodeToString(salt) + "$"
if !strings.HasPrefix(h, want) || len(h) != len(want)+43 {
t.Fatalf("hash %q", h)
}
parsed, err := parsePHC(h)
if err != nil || parsed.memory != argon2Memory || parsed.iterations != argon2Iterations || parsed.parallelism != argon2Parallelism || len(parsed.key) != argon2KeyBytes || !bytes.Equal(parsed.salt, salt) {
t.Fatalf("%+v %v", parsed, err)
}
if !verifyPassword("correct horse battery", h) {
t.Fatal("correct password refused")
}
if verifyPassword("correct horse batterz", h) {
t.Fatal("wrong password accepted")
}
if _, err := hashPasswordWith(failingReader{}, "x"); err == nil {
t.Fatal("salt failure ignored")
}
}
func TestVerifyPasswordInvalidHashUsesDummy(t *testing.T) {
if verifyPassword("anything", "not a hash") {
t.Fatal("invalid hash accepted")
}
if verifyPassword("anything", dummyPasswordHash) {
t.Fatal("dummy hash accepted a password")
}
}
func TestDummyHashHasProductionCost(t *testing.T) {
if dummyPHC.memory != argon2Memory || dummyPHC.iterations != argon2Iterations || dummyPHC.parallelism != argon2Parallelism || len(dummyPHC.key) != argon2KeyBytes || len(dummyPHC.salt) != argon2SaltBytes {
t.Fatalf("%+v", dummyPHC)
}
defer func() {
if recover() == nil {
t.Fatal("mustParsePHC accepted garbage")
}
}()
mustParsePHC("garbage")
}
func TestParsePHCRejects(t *testing.T) {
salt := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 16))
key := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{2}, 32))
valid := "$argon2id$v=19$m=65536,t=3,p=2$" + salt + "$" + key
if _, err := parsePHC(valid); err != nil {
t.Fatal(err)
}
cases := []string{
"",
"argon2id$v=19$m=65536,t=3,p=2$" + salt + "$" + key,
"$argon2i$v=19$m=65536,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=18$m=65536,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=65536,t=3$" + salt + "$" + key,
"$argon2id$v=19$t=3,m=65536,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=065536,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=0,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=65536,t=0,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=65536,t=3,p=0$" + salt + "$" + key,
"$argon2id$v=19$m=65536,t=3,p=17$" + salt + "$" + key,
"$argon2id$v=19$m=2097152,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=65536,t=65,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=15,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=+65536,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=99999999999,t=3,p=2$" + salt + "$" + key,
"$argon2id$v=19$m=65536,t=3,p=2$" + salt + "=$" + key,
"$argon2id$v=19$m=65536,t=3,p=2$" + salt + "$" + key + "$",
"$argon2id$v=19$m=65536,t=3,p=2$c2hvcnQ$" + key,
"$argon2id$v=19$m=65536,t=3,p=2$" + salt + "$" + base64.RawStdEncoding.EncodeToString(make([]byte, 65)),
"$argon2id$v=19$m=65536,t=3,p=2$" + salt + "$!!!!",
}
for _, c := range cases {
if _, err := parsePHC(c); !errors.Is(err, errInvalidPasswordHash) {
t.Errorf("%q: %v", c, err)
}
}
}
func TestHashConcurrencyLimit(t *testing.T) {
cheap := phcHash{memory: 8, iterations: 1, parallelism: 1, salt: make([]byte, 8), key: make([]byte, 8)}
for range maxConcurrentHashes {
hashSlots <- struct{}{}
}
done := make(chan struct{})
go func() {
argon2Key("x", cheap)
close(done)
}()
select {
case <-done:
t.Fatal("a fifth hash ran while four were running")
case <-time.After(100 * time.Millisecond):
}
<-hashSlots
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("hash did not run after a slot was freed")
}
for range maxConcurrentHashes - 1 {
<-hashSlots
}
if cap(hashSlots) != 4 || len(hashSlots) != 0 {
t.Fatal(cap(hashSlots), len(hashSlots))
}
}
func TestVerifyLoginUsesDummyForUnknownAndDeleted(t *testing.T) {
var seen []string
verify := func(password, encoded string) bool {
seen = append(seen, encoded)
return password == "right"
}
active := &userRow{ID: 1, PasswordHash: "$stored"}
deleted := &userRow{ID: 2, PasswordHash: "$stored", DeletedAt: sql.NullTime{Time: webNow, Valid: true}}
if !verifyLogin(verify, active, "right") || verifyLogin(verify, active, "wrong") {
t.Fatal("active user")
}
if verifyLogin(verify, nil, "right") || verifyLogin(verify, deleted, "right") {
t.Fatal("unknown or deleted user accepted")
}
want := []string{"$stored", "$stored", dummyPasswordHash, dummyPasswordHash}
if strings.Join(seen, ",") != strings.Join(want, ",") {
t.Fatal(seen)
}
}
func TestUsernameRules(t *testing.T) {
for _, u := range []string{"a", "alice", "a.b-c_d", "0x", strings.Repeat("z", 64)} {
if err := checkUsername(u); err != nil {
t.Errorf("%q: %v", u, err)
}
}
for _, u := range []string{"", "Alice", "-a", "a b", strings.Repeat("z", 65), "é"} {
if err := checkUsername(u); err == nil || err.Error() != "username must be 1 to 64 characters of lowercase letters, digits, dots, underscores and hyphens, starting with a letter or digit" {
t.Errorf("%q: %v", u, err)
}
}
if err := checkUsername("cli"); err == nil || err.Error() != "username is reserved" {
t.Fatal(err)
}
}
func TestPasswordRules(t *testing.T) {
for _, p := range []string{strings.Repeat("a", 12), strings.Repeat("a", 256), "pässwörd-long", "spaces are fine ok"} {
if err := checkPasswordRules(p); err != nil {
t.Errorf("%q: %v", p, err)
}
}
cases := map[string]string{
strings.Repeat("a", 11): "password must be 12 to 256 bytes",
strings.Repeat("a", 257): "password must be 12 to 256 bytes",
"long-enough-\xff-password": "password must be valid UTF-8",
"long-enough-\tpassword": "password must not contain control characters",
"long-enough-\x00password": "password must not contain control characters",
"long-enough-\u0085password": "password must not contain control characters",
strings.Repeat("ä", 6): "",
strings.Repeat("ä", 129): "password must be 12 to 256 bytes",
"long-enough-password\n": "password must not contain control characters",
"long-enough-password\u007f": "password must not contain control characters",
"shortä": "password must be 12 to 256 bytes",
"​zero-width-is-printable-ok": "",
}
for p, want := range cases {
err := checkPasswordRules(p)
if (want == "" && err != nil) || (want != "" && (err == nil || err.Error() != want)) {
t.Errorf("%q: %v, want %q", p, err, want)
}
}
}
func TestRoles(t *testing.T) {
if !validRole("admin") || !validRole("user") || validRole("Admin") || validRole("") || validRole("root") {
t.Fatal("role rules")
}
}
func TestSessionTokens(t *testing.T) {
raw := bytes.Repeat([]byte{0xfb}, 32)
token, hash, err := newSessionToken(bytes.NewReader(raw))
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256([]byte(token))
if token != base64.RawURLEncoding.EncodeToString(raw) || !bytes.Equal(hash, sum[:]) || len(token) != 43 || strings.ContainsAny(token, "+/=") {
t.Fatal(token)
}
if !validSessionToken(token) || validSessionToken(token+"A") || validSessionToken(token[:42]) || validSessionToken(strings.Repeat("!", 43)) {
t.Fatal("token syntax")
}
if _, _, err := newSessionToken(failingReader{}); err == nil {
t.Fatal("entropy failure ignored")
}
other, _, _ := newSessionToken(bytes.NewReader(bytes.Repeat([]byte{1}, 32)))
if other == token {
t.Fatal("tokens repeat")
}
}
func TestSessionValidity(t *testing.T) {
idle, maxAge := time.Hour, 12*time.Hour
s := newSessionRow([]byte("h"), 3, webNow, maxAge, "192.0.2.1", "Agent\x00\n"+strings.Repeat("x", 300))
if !s.ExpiresAt.Equal(webNow.Add(maxAge)) || s.UserAgent != "Agent "+strings.Repeat("x", 248) || s.UserID != 3 || s.Origin != "192.0.2.1" {
t.Fatalf("%+v", s)
}
u := userRow{ID: 3}
cases := []struct {
now time.Time
lastSeen time.Time
deleted bool
valid bool
}{
{webNow, webNow, false, true},
{webNow.Add(59 * time.Minute), webNow, false, true},
{webNow.Add(time.Hour), webNow, false, false},
{webNow.Add(11 * time.Hour), webNow.Add(11*time.Hour - time.Minute), false, true},
{webNow.Add(12 * time.Hour), webNow.Add(12*time.Hour - time.Minute), false, false},
{webNow, webNow, true, false},
}
for i, c := range cases {
row := s
row.LastSeenAt = c.lastSeen
user := u
if c.deleted {
user.DeletedAt = sql.NullTime{Time: webNow, Valid: true}
}
if got := sessionValid(row, user, c.now, idle, maxAge); got != c.valid {
t.Errorf("case %d: %v", i, got)
}
}
row := s
row.ExpiresAt = webNow.Add(time.Minute)
if sessionValid(row, u, webNow.Add(time.Minute), idle, maxAge) {
t.Fatal("expires_at ignored")
}
if sessionTouchDue(s, webNow.Add(59*time.Second)) || !sessionTouchDue(s, webNow.Add(time.Minute)) {
t.Fatal("touch interval")
}
}
func TestSessionCookies(t *testing.T) {
c := sessionCookie("tok", true)
if c.Name != "coredns_webui_session" || c.Value != "tok" || c.Path != "/" || !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteStrictMode || c.MaxAge != 0 {
t.Fatalf("%+v", c)
}
if sessionCookie("tok", false).Secure {
t.Fatal("secure flag")
}
e := expiredSessionCookie(false)
if e.Value != "" || e.MaxAge != -1 || e.Secure || !e.HttpOnly {
t.Fatalf("%+v", e)
}
token, _, _ := newSessionToken(bytes.NewReader(bytes.Repeat([]byte{9}, 32)))
r := httptest.NewRequest("GET", "/", nil)
if _, ok := requestSessionToken(r); ok {
t.Fatal("no cookie")
}
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "short"})
if _, ok := requestSessionToken(r); ok {
t.Fatal("malformed cookie accepted")
}
r = httptest.NewRequest("GET", "/", nil)
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
if got, ok := requestSessionToken(r); !ok || got != token {
t.Fatal(got)
}
}
func TestPrintableText(t *testing.T) {
cases := []struct {
in string
max int
want string
}{
{"alice", 64, "alice"},
{"a\x00b\nc\td", 64, "a b c d"},
{"bad\xffbyte", 64, "bad byte"},
{"keep�replacement", 64, "keep�replacement"},
{"‮evil", 64, " evil"},
{strings.Repeat("é", 70), 64, strings.Repeat("é", 64)},
{"abc", 0, ""},
{"abc", -1, "abc"},
}
for _, c := range cases {
if got := printableText(c.in, c.max); got != c.want {
t.Errorf("%q: %q", c.in, got)
}
}
}