Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages

This commit is contained in:
Ivan Melnikov
2026-12-02 18:22:57 +03:00
parent 0ab3a341aa
commit e9bf138053
474 changed files with 206416 additions and 16 deletions
+156
View File
@@ -0,0 +1,156 @@
package auth
import (
"encoding/base64"
"strings"
"testing"
)
func TestHashAndVerify(t *testing.T) {
password := "correct horse battery staple"
encoded, err := Hash(password)
if err != nil {
t.Fatalf("Hash: %v", err)
}
if !strings.HasPrefix(encoded, "$argon2id$v=19$m=19456,t=2,p=1$") {
t.Fatalf("unexpected PHC prefix: %q", encoded)
}
match, err := Verify(password, encoded)
if err != nil || !match {
t.Fatalf("Verify(correct) = %v, %v", match, err)
}
match, err = Verify(password+"x", encoded)
if err != nil || match {
t.Fatalf("Verify(wrong) = %v, %v", match, err)
}
}
func TestHashUnicodeAndMaximumLength(t *testing.T) {
for _, password := range []string{
"pässwörd:12✓",
strings.Repeat("界", 128),
" leading and trailing spaces ",
} {
encoded, err := Hash(password)
if err != nil {
t.Fatalf("Hash(%q): %v", password, err)
}
if match, err := Verify(password, encoded); err != nil || !match {
t.Fatalf("Verify(%q) = %v, %v", password, match, err)
}
}
}
func TestHashUsesRandomSalt(t *testing.T) {
first, err := Hash("same-password-twice")
if err != nil {
t.Fatal(err)
}
second, err := Hash("same-password-twice")
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("two hashes of the same password are identical")
}
}
func TestVerifyRejectsMalformedHashes(t *testing.T) {
for _, encoded := range []string{
"",
"plaintext",
"$2a$10$abcdefghijklmnopqrstuv",
"$argon2id$v=19$m=19456,t=2,p=1$not-base64$hash",
"$argon2id$v=19$m=1,t=3,p=2$c2FsdHNhbHQ$aGFzaGhhc2hoYXNoaGFzaA",
"$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA",
} {
if _, err := Verify("password", encoded); err == nil {
t.Fatalf("Verify accepted malformed hash %q", encoded)
}
}
}
func TestParseBasic(t *testing.T) {
cases := []struct {
name string
raw string
username string
password string
ok bool
}{
{
name: "ordinary",
raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:secret")),
username: "alice",
password: "secret",
ok: true,
},
{
name: "password contains colon and UTF-8",
raw: "bAsIc " + base64.StdEncoding.EncodeToString([]byte("alice:pässwörd:with:colons")),
username: "alice",
password: "pässwörd:with:colons",
ok: true,
},
{
name: "unpadded base64",
raw: "Basic " + base64.RawStdEncoding.EncodeToString([]byte("alice:secret")),
username: "alice",
password: "secret",
ok: true,
},
{name: "no scheme", raw: "alice:secret"},
{name: "wrong scheme", raw: "Bearer abc"},
{name: "no space", raw: "Basic" + base64.StdEncoding.EncodeToString([]byte("alice:secret"))},
{name: "bad base64", raw: "Basic !!!"},
{name: "no separator", raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice"))},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
username, password, err := ParseBasic(tc.raw)
if !tc.ok {
if err == nil {
t.Fatalf("ParseBasic accepted %q", tc.raw)
}
return
}
if err != nil {
t.Fatalf("ParseBasic: %v", err)
}
if username != tc.username || password != tc.password {
t.Fatalf("got %q/%q, want %q/%q", username, password, tc.username, tc.password)
}
})
}
}
func TestTokenProperties(t *testing.T) {
first, err := NewToken()
if err != nil {
t.Fatal(err)
}
second, err := NewToken()
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("tokens are not unique")
}
if len(first) != 43 {
t.Fatalf("token length = %d, want 43 (256 bits)", len(first))
}
if !ValidTokenShape(first) {
t.Fatal("issued token fails its own shape check")
}
if TokenHash(first) == TokenHash(second) {
t.Fatal("token hashes collide")
}
if len(TokenHash(first)) != 64 {
t.Fatalf("token hash length = %d", len(TokenHash(first)))
}
for _, bad := range []string{"", "short", "has space in it", strings.Repeat("a", 129), "abc+/="} {
if ValidTokenShape(bad) {
t.Fatalf("ValidTokenShape accepted %q", bad)
}
}
}
+90
View File
@@ -0,0 +1,90 @@
// Package auth implements the lab3 credential primitives: a library password
// KDF (Argon2id), opaque session tokens and RFC 7617 Basic parsing. None of
// these helpers log or serialise the secret material they receive.
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// Argon2id parameters. 19 MiB / 2 passes / 1 lane is the OWASP password
// storage minimum for Argon2id, chosen so eight concurrent registrations fit
// inside the 256 MiB API container limit. The parameters are stored in every
// PHC string, so a future change remains backward compatible.
const (
argonMemory uint32 = 19 * 1024 // KiB
argonIterations uint32 = 2
argonParallelism uint8 = 1
argonSaltLength = 16
argonKeyLength uint32 = 32
)
// ErrInvalidHash means a stored PHC string is malformed or uses unsupported
// parameters. It is an internal error, never shown to a client.
var ErrInvalidHash = errors.New("invalid password hash")
// Hash derives an Argon2id PHC string for password. Callers must validate the
// password policy before calling; the KDF itself accepts arbitrary UTF-8.
func Hash(password string) (string, error) {
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonIterations, argonParallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
), nil
}
// Verify checks password against a PHC string in constant time and reports
// whether the encoded hash was structurally valid. A malformed hash is not a
// password mismatch and should be treated as an internal error by the caller.
func Verify(password, encoded string) (match bool, err error) {
params, salt, key, err := parse(encoded)
if err != nil {
return false, err
}
candidate := argon2.IDKey([]byte(password), salt, params.iterations, params.memory, params.parallelism, uint32(len(key)))
return subtle.ConstantTimeCompare(candidate, key) == 1, nil
}
type params struct {
memory uint32
iterations uint32
parallelism uint8
}
func parse(encoded string) (params, []byte, []byte, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
return params{}, nil, nil, ErrInvalidHash
}
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
return params{}, nil, nil, ErrInvalidHash
}
var p params
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism); err != nil {
return params{}, nil, nil, ErrInvalidHash
}
if p.memory < 8*1024 || p.memory > 256*1024 || p.iterations < 1 || p.iterations > 10 || p.parallelism < 1 || p.parallelism > 16 {
return params{}, nil, nil, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 8 || len(salt) > 64 {
return params{}, nil, nil, ErrInvalidHash
}
key, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(key) < 16 || len(key) > 64 {
return params{}, nil, nil, ErrInvalidHash
}
return p, salt, key, nil
}
+102
View File
@@ -0,0 +1,102 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
)
// tokenBytes gives 256 bits of entropy, the contract minimum. The token is an
// opaque value: it is not a username, a UUID or a JWT.
const tokenBytes = 32
// NewToken returns a URL-safe opaque session token.
func NewToken() (string, error) {
raw := make([]byte, tokenBytes)
if _, err := rand.Read(raw); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(raw), nil
}
// TokenHash is the only representation of a token that is persisted. A cache
// dump therefore does not contain bearer credentials usable against the API.
func TokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// ValidTokenShape rejects absurd header values before hashing. The check is a
// superset of the 43-character tokens this server issues, so token rotation
// remains possible without rejecting old values early.
func ValidTokenShape(token string) bool {
if len(token) < 16 || len(token) > 128 {
return false
}
for i := 0; i < len(token); i++ {
c := token[i]
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
continue
}
return false
}
return true
}
// ErrMalformedBasic is returned for anything that is not a well-formed
// RFC 7617 Basic credential. Callers must answer with the same 401 as a
// wrong password.
var ErrMalformedBasic = errors.New("malformed basic credentials")
// ParseBasic decodes an Authorization header of the form "Basic base64(user:pass)".
// The password may contain colons and arbitrary UTF-8; only the first colon
// separates the username.
func ParseBasic(header string) (username, password string, err error) {
const scheme = "basic"
trimmed := header
if len(trimmed) < len(scheme)+1 || !equalFoldASCII(trimmed[:len(scheme)], scheme) || trimmed[len(scheme)] != ' ' {
return "", "", ErrMalformedBasic
}
encoded := trimmed[len(scheme)+1:]
if encoded == "" || len(encoded) > 1024 {
return "", "", ErrMalformedBasic
}
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
// Some clients omit the RFC 4648 padding. Accept the unpadded form as
// well, but never fall back to a different alphabet.
decoded, err = base64.RawStdEncoding.DecodeString(encoded)
if err != nil {
return "", "", ErrMalformedBasic
}
}
separator := -1
for i := 0; i < len(decoded); i++ {
if decoded[i] == ':' {
separator = i
break
}
}
if separator < 0 {
return "", "", ErrMalformedBasic
}
return string(decoded[:separator]), string(decoded[separator+1:]), nil
}
func equalFoldASCII(value, lower string) bool {
if len(value) != len(lower) {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if c >= 'A' && c <= 'Z' {
c += 'a' - 'A'
}
if c != lower[i] {
return false
}
}
return true
}