Реализовать lab3 на оценку 4: балансировка и отказ API

This commit is contained in:
Daria0w0
2026-10-23 17:14:32 +03:00
parent 0ab3a341aa
commit a67e7996ec
88 changed files with 5105 additions and 21 deletions
+76
View File
@@ -0,0 +1,76 @@
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"unicode/utf8"
"golang.org/x/crypto/argon2"
)
const (
memoryKiB uint32 = 64 * 1024
iterations uint32 = 3
parallelism uint8 = 4
saltLength = 16
keyLength uint32 = 32
)
var (
ErrInvalidPassword = errors.New("password must contain 12 to 128 UTF-8 code points and a non-whitespace character")
ErrInvalidHash = errors.New("invalid or unsupported password hash")
encoding = base64.RawStdEncoding.Strict()
profile = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$",
argon2.Version, memoryKiB, iterations, parallelism)
)
func Validate(value string) error {
if !utf8.ValidString(value) {
return ErrInvalidPassword
}
length := utf8.RuneCountInString(value)
if length < 12 || length > 128 || strings.TrimSpace(value) == "" {
return ErrInvalidPassword
}
return nil
}
func Hash(value string) (string, error) {
if err := Validate(value); err != nil {
return "", err
}
salt := make([]byte, saltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
key := argon2.IDKey([]byte(value), salt, iterations, memoryKiB, parallelism, keyLength)
return profile + encoding.EncodeToString(salt) + "$" + encoding.EncodeToString(key), nil
}
func Verify(value, encoded string) (bool, error) {
if len(encoded) != len(profile)+encoding.EncodedLen(saltLength)+1+encoding.EncodedLen(int(keyLength)) ||
!strings.HasPrefix(encoded, profile) {
return false, ErrInvalidHash
}
parts := strings.Split(strings.TrimPrefix(encoded, profile), "$")
if len(parts) != 2 {
return false, ErrInvalidHash
}
salt, err := encoding.DecodeString(parts[0])
if err != nil || len(salt) != saltLength {
return false, ErrInvalidHash
}
expected, err := encoding.DecodeString(parts[1])
if err != nil || len(expected) != int(keyLength) {
return false, ErrInvalidHash
}
if err := Validate(value); err != nil {
return false, nil
}
actual := argon2.IDKey([]byte(value), salt, iterations, memoryKiB, parallelism, keyLength)
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
}
+98
View File
@@ -0,0 +1,98 @@
package password
import (
"errors"
"strings"
"testing"
)
func TestValidate(t *testing.T) {
for _, tc := range []struct {
name string
value string
valid bool
}{
{"empty", "", false},
{"11 characters", strings.Repeat("a", 11), false},
{"12 characters", strings.Repeat("a", 12), true},
{"128 Unicode characters", strings.Repeat("я", 128), true},
{"129 Unicode characters", strings.Repeat("я", 129), false},
{"invalid UTF-8", strings.Repeat("a", 12) + string([]byte{0xff}), false},
{"only spaces", strings.Repeat(" ", 12), false},
{"only Unicode whitespace", strings.Repeat("\u00a0\u2003\t\n", 3), false},
{"spaces preserved", " пароль:секрет ", true},
{"colon allowed", "пароль:секрет", true},
} {
t.Run(tc.name, func(t *testing.T) {
err := Validate(tc.value)
if (err == nil) != tc.valid {
t.Fatalf("valid=%v, error=%v", tc.valid, err)
}
if !tc.valid {
if _, err := Hash(tc.value); !errors.Is(err, ErrInvalidPassword) {
t.Fatalf("Hash error=%v", err)
}
}
})
}
}
func TestHashAndVerify(t *testing.T) {
value := " пароль:секрет "
first, err := Hash(value)
if err != nil {
t.Fatal(err)
}
second, err := Hash(value)
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("independent salts produced identical records")
}
for _, encoded := range []string{first, second} {
ok, err := Verify(value, encoded)
if err != nil || !ok {
t.Fatalf("correct password: match=%v error=%v", ok, err)
}
}
for _, wrong := range []string{"другой:пароль", strings.TrimSpace(value), "short"} {
ok, err := Verify(wrong, first)
if err != nil || ok {
t.Fatalf("wrong password: match=%v error=%v", ok, err)
}
}
}
func TestLongUnicodePasswordIsNotTruncated(t *testing.T) {
value := strings.Repeat("я", 128)
encoded, err := Hash(value)
if err != nil {
t.Fatal(err)
}
ok, err := Verify(value, encoded)
if err != nil || !ok {
t.Fatalf("match=%v error=%v", ok, err)
}
ok, err = Verify(strings.Repeat("я", 127)+"ю", encoded)
if err != nil || ok {
t.Fatalf("last character ignored: match=%v error=%v", ok, err)
}
}
func TestVerifyRejectsMalformedHash(t *testing.T) {
encoded := profile + encoding.EncodeToString(make([]byte, saltLength)) + "$" + encoding.EncodeToString(make([]byte, keyLength))
for _, broken := range []string{
"", "plaintext", encoded[:len(encoded)-1], encoded + "$extra",
strings.Replace(encoded, "v=19", "v=18", 1),
strings.Replace(encoded, "m=65536", "m=999999999", 1),
strings.Replace(encoded, "t=3", "t=0", 1),
strings.Replace(encoded, "p=4", "p=0", 1),
profile + "!" + encoded[len(profile)+1:],
} {
ok, err := Verify("пароль:секрет", broken)
if ok || !errors.Is(err, ErrInvalidHash) {
t.Fatalf("match=%v error=%v", ok, err)
}
}
}