Move upload auth from nginx into the app
Add HTTP Basic auth on /upload, reading an Apache htpasswd file (bcrypt only, `htpasswd -B`) via a new -htpasswd flag. This lets nginx drop to a plain TLS-terminating reverse proxy with no auth of its own; the existing bcrypt htpasswd file is reused unchanged. auth.go: - LoadHtpasswd parses user:hash lines, keeps bcrypt entries ($2a/$2b/$2y, so Apache's $2y$ works), skips MD5/SHA/crypt with a warning. - Unknown users still pay for one bcrypt comparison against a dummy hash, so response timing can't enumerate valid usernames. - Failed attempts draw from a token-bucket limiter (x/time/rate, ~1/s, burst 10) returning 429 once drained; successful and bulk uploads never touch it. server.go guards both /upload routes (nil authenticator = passthrough for local --serve). /health stays open. Empty -htpasswd disables auth and logs a warning. module.nix: new top-level services.photogallery.htpasswdFile, delivered to the service via systemd LoadCredential (so a root-owned 0400 secret works). Removed nginx.htpasswdFile and basic_auth from the vhost. Both uploader apps already send Basic credentials, so no client change. Deps: golang.org/x/crypto/bcrypt, golang.org/x/time/rate (vendorHash bump).
This commit is contained in:
1 parent
3291ed67d5
commit
434d2437bf
9 files changed
+342
-27
No files matched your search
+144
@@ -0,0 +1,144 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
// bcryptHash returns a cost-10 hash of pw, matching `htpasswd -B`'s default.
|
||||
func bcryptHash(t *testing.T, pw string) string {
|
||||
t.Helper()
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(pw), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateFromPassword: %v", err)
|
||||
}
|
||||
return string(h)
|
||||
}
|
||||
|
||||
func TestLoadHtpasswdAndCheck(t *testing.T) {
|
||||
// alice's hash is rewritten to the $2y$ variant that Apache's htpasswd -B
|
||||
// emits, to prove it is accepted. $2a$ and $2y$ are the same algorithm, so
|
||||
// swapping the prefix on a valid hash yields a valid hash for the same
|
||||
// password. bob keeps the $2a$ form.
|
||||
aliceHash := bcryptHash(t, "s3cret")
|
||||
if !strings.HasPrefix(aliceHash, "$2a$") {
|
||||
t.Fatalf("expected $2a$ prefix, got %q", aliceHash[:4])
|
||||
}
|
||||
aliceHashY := "$2y$" + strings.TrimPrefix(aliceHash, "$2a$")
|
||||
bobHash := bcryptHash(t, "hunter2")
|
||||
|
||||
file := filepath.Join(t.TempDir(), "htpasswd")
|
||||
content := strings.Join([]string{
|
||||
"# a comment",
|
||||
"",
|
||||
"alice:" + aliceHashY,
|
||||
"bob:" + bobHash,
|
||||
"legacy:$apr1$abcd$0123456789", // MD5 — must be skipped
|
||||
}, "\n") + "\n"
|
||||
if err := os.WriteFile(file, []byte(content), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
a, err := LoadHtpasswd(file)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadHtpasswd: %v", err)
|
||||
}
|
||||
if _, ok := a.creds["legacy"]; ok {
|
||||
t.Error("MD5 entry should have been skipped")
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
user, pass string
|
||||
want bool
|
||||
}{
|
||||
{"alice", "s3cret", true}, // $2y$ accepted
|
||||
{"bob", "hunter2", true}, // $2a$ accepted
|
||||
{"alice", "wrong", false}, // wrong password
|
||||
{"bob", "s3cret", false}, // right password, wrong user
|
||||
{"nobody", "s3cret", false}, // unknown user
|
||||
{"legacy", "whatever", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := a.check(c.user, c.pass); got != c.want {
|
||||
t.Errorf("check(%q, %q) = %v, want %v", c.user, c.pass, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicAuthMiddleware(t *testing.T) {
|
||||
a := &Authenticator{creds: map[string][]byte{"alice": []byte(bcryptHash(t, "s3cret"))}}
|
||||
a.dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy"), 10)
|
||||
|
||||
var reached bool
|
||||
// Burst of 2 failures before throttling, so the 429 path is reachable.
|
||||
limiter := rate.NewLimiter(rate.Every(time.Hour), 2)
|
||||
h := a.basicAuth(limiter, func(w http.ResponseWriter, r *http.Request) {
|
||||
reached = true
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
})
|
||||
|
||||
do := func(user, pass string, withCreds bool) *httptest.ResponseRecorder {
|
||||
reached = false
|
||||
req := httptest.NewRequest(http.MethodPost, "/upload", nil)
|
||||
if withCreds {
|
||||
req.SetBasicAuth(user, pass)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// Good credentials pass through.
|
||||
if rec := do("alice", "s3cret", true); rec.Code != http.StatusCreated || !reached {
|
||||
t.Fatalf("valid creds: code=%d reached=%v", rec.Code, reached)
|
||||
}
|
||||
|
||||
// No credentials → 401 with a challenge.
|
||||
rec := do("", "", false)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("missing creds: code=%d, want 401", rec.Code)
|
||||
}
|
||||
if !strings.HasPrefix(rec.Header().Get("WWW-Authenticate"), "Basic ") {
|
||||
t.Errorf("missing WWW-Authenticate challenge: %q", rec.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
if reached {
|
||||
t.Error("handler reached despite missing creds")
|
||||
}
|
||||
|
||||
// Wrong password burns the limiter (burst 2: one above + this one), then
|
||||
// the next failure is throttled to 429.
|
||||
if rec := do("alice", "nope", true); rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("wrong pass #2: code=%d, want 401", rec.Code)
|
||||
}
|
||||
if rec := do("alice", "nope", true); rec.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("wrong pass #3: code=%d, want 429", rec.Code)
|
||||
}
|
||||
|
||||
// A valid request still succeeds while failures are throttled — the
|
||||
// limiter only gates failures.
|
||||
if rec := do("alice", "s3cret", true); rec.Code != http.StatusCreated {
|
||||
t.Fatalf("valid creds under throttle: code=%d, want 201", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadHtpasswdErrors(t *testing.T) {
|
||||
if _, err := LoadHtpasswd(filepath.Join(t.TempDir(), "does-not-exist")); err == nil {
|
||||
t.Error("expected error for missing file")
|
||||
}
|
||||
|
||||
empty := filepath.Join(t.TempDir(), "htpasswd")
|
||||
if err := os.WriteFile(empty, []byte("# only comments\n\nlegacy:$apr1$x$y\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadHtpasswd(empty); err == nil {
|
||||
t.Error("expected error when no bcrypt entries are usable")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user