fix backend audit findings (auth, upload, sync, data, ocr, contract)
CI / lint-backend (push) Failing after 1m39s
CI / lint-mobile (push) Canceled after 11m8s
CI / test-backend (push) Canceled after 0s
CI / test-mobile (push) Canceled after 0s
CI / build-backend (push) Canceled after 0s
CI / docker (push) Canceled after 0s
CI / lint-backend (push) Failing after 1m39s
CI / lint-mobile (push) Canceled after 11m8s
CI / test-backend (push) Canceled after 0s
CI / test-mobile (push) Canceled after 0s
CI / build-backend (push) Canceled after 0s
CI / docker (push) Canceled after 0s
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
package api
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const NotImplementedCode = "NOT_IMPLEMENTED"
|
||||
|
||||
@@ -22,6 +26,14 @@ func OKList(c *gin.Context, data any, page, pageSize, total int) {
|
||||
}
|
||||
|
||||
func Error(c *gin.Context, status int, code, message string) {
|
||||
// LOT 6 §5 : le client ne reçoit que l'enveloppe générique (code +
|
||||
// message sans détail interne — jamais de err.Error() brut). Le détail
|
||||
// va au log serveur pour le diagnostic.
|
||||
path := ""
|
||||
if c.Request != nil && c.Request.URL != nil {
|
||||
path = c.Request.URL.Path
|
||||
}
|
||||
log.Printf("api error: status=%d code=%s message=%s path=%s", status, code, message, path)
|
||||
c.JSON(status, gin.H{
|
||||
"error": gin.H{"code": code, "message": message},
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ package auth
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"aidanwoods.dev/go-paseto"
|
||||
@@ -14,6 +15,8 @@ const TokenTTL = 7 * 24 * time.Hour
|
||||
|
||||
var ErrInvalidToken = errors.New("invalid token")
|
||||
|
||||
var hex32Pattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
||||
|
||||
// Identity est le résultat de Verify : l'utilisateur (sujet du token, autorisant)
|
||||
// et le device (claim secondaire, porté mais NON autorisant seul).
|
||||
type Identity struct {
|
||||
@@ -39,29 +42,40 @@ func NewManager(secret string) (*Manager, error) {
|
||||
|
||||
// Issue émet un token lié à un utilisateur ET à un device.
|
||||
func (m *Manager) Issue(userID, deviceID string) (string, error) {
|
||||
token, _, err := m.IssueWithExpiry(userID, deviceID)
|
||||
return token, err
|
||||
}
|
||||
|
||||
// IssueWithExpiry émet un token et retourne son expiration réelle (le `exp`
|
||||
// embarqué). Les appelants doivent exposer expiresAt, jamais le recalculer
|
||||
// via Now()+TTL (dérive d'horloge, cf. FEEDBACK A7).
|
||||
func (m *Manager) IssueWithExpiry(userID, deviceID string) (string, time.Time, error) {
|
||||
now := time.Now()
|
||||
expiresAt := now.Add(TokenTTL)
|
||||
token := paseto.NewToken()
|
||||
token.SetIssuedAt(now)
|
||||
token.SetNotBefore(now)
|
||||
token.SetExpiration(now.Add(TokenTTL))
|
||||
token.SetExpiration(expiresAt)
|
||||
token.SetSubject(userID)
|
||||
// v1.6.0 : SetString n'expose pas d'erreur (panic si non sérialisable).
|
||||
token.SetString("device_id", deviceID)
|
||||
return token.V4Encrypt(m.key, nil), nil
|
||||
return token.V4Encrypt(m.key, nil), expiresAt, nil
|
||||
}
|
||||
|
||||
// Verify décode et contrôle le token, retourne l'identité (user + device).
|
||||
// Les deux identifiants doivent être 32-hex (cf. docs/api-v1.md) — rejet
|
||||
// sinon pour préserver les invariants UNIQUE(device_id,operation_id)/CHECK.
|
||||
func (m *Manager) Verify(signed string) (Identity, error) {
|
||||
parsed, err := paseto.NewParserForValidNow().ParseV4Local(m.key, signed, nil)
|
||||
if err != nil {
|
||||
return Identity{}, ErrInvalidToken
|
||||
}
|
||||
userID, err := parsed.GetSubject()
|
||||
if err != nil || userID == "" {
|
||||
if err != nil || !hex32Pattern.MatchString(userID) {
|
||||
return Identity{}, ErrInvalidToken
|
||||
}
|
||||
deviceID, err := parsed.GetString("device_id")
|
||||
if err != nil || deviceID == "" {
|
||||
if err != nil || !hex32Pattern.MatchString(deviceID) {
|
||||
return Identity{}, ErrInvalidToken
|
||||
}
|
||||
return Identity{UserID: userID, DeviceID: deviceID}, nil
|
||||
|
||||
@@ -96,6 +96,44 @@ func TestVerifyRequiresDeviceClaim(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRejectsNonHex32IDs(t *testing.T) {
|
||||
m, _ := NewManager("test-secret")
|
||||
|
||||
issueWith := func(userID, deviceID string) string {
|
||||
token := paseto.NewToken()
|
||||
now := time.Now()
|
||||
token.SetIssuedAt(now)
|
||||
token.SetNotBefore(now)
|
||||
token.SetExpiration(now.Add(TokenTTL))
|
||||
token.SetSubject(userID)
|
||||
token.SetString("device_id", deviceID)
|
||||
return token.V4Encrypt(m.key, nil)
|
||||
}
|
||||
|
||||
cases := map[string][2]string{
|
||||
"subject vide": {"", testDeviceID},
|
||||
"subject non-hex": {"not-hex-at-all-!!!!!!!!!!!!!!!!", testDeviceID},
|
||||
"subject majuscules": {"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", testDeviceID},
|
||||
"subject trop court": {"abc123", testDeviceID},
|
||||
"device vide": {testUserID, ""},
|
||||
"device non-hex": {testUserID, "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"},
|
||||
"device majuscules": {testUserID, "0123456789ABCDEF0123456789ABCDEF"},
|
||||
"device trop long": {testUserID, testDeviceID + "00"},
|
||||
"device avec tirets": {testUserID, "01234567-89ab-cdef-0123-456789abcdef"},
|
||||
}
|
||||
for name, ids := range cases {
|
||||
signed := issueWith(ids[0], ids[1])
|
||||
if _, err := m.Verify(signed); err == nil {
|
||||
t.Errorf("%s: token accepté (user=%q device=%q), attendu rejet", name, ids[0], ids[1])
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity : les IDs 32-hex valides passent toujours.
|
||||
if _, err := m.Verify(issueWith(testUserID, testDeviceID)); err != nil {
|
||||
t.Errorf("IDs valides rejetés: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueSetsExpiration(t *testing.T) {
|
||||
m, _ := NewManager("test-secret")
|
||||
before := time.Now()
|
||||
@@ -118,3 +156,25 @@ func TestIssueSetsExpiration(t *testing.T) {
|
||||
t.Errorf("expiration = %v, attendu ≈ now+%v (fenêtre [%v, %v])", exp, TokenTTL, lower, upper)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueWithExpiryMatchesTokenExp(t *testing.T) {
|
||||
m, _ := NewManager("test-secret")
|
||||
signed, expiresAt, err := m.IssueWithExpiry(testUserID, testDeviceID)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueWithExpiry: %v", err)
|
||||
}
|
||||
parsed, err := paseto.NewParserForValidNow().ParseV4Local(m.key, signed, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
exp, err := parsed.GetExpiration()
|
||||
if err != nil {
|
||||
t.Fatalf("GetExpiration: %v", err)
|
||||
}
|
||||
// L'expiresAt retourné doit être le exp embarqué (pas un Now()+TTL
|
||||
// recalculé — cf. FEEDBACK A7). Comparaison à la seconde : le token
|
||||
// sérialise sans lecture monotonique ni sous-seconde.
|
||||
if exp.Unix() != expiresAt.Unix() {
|
||||
t.Errorf("expiresAt = %v, exp token = %v", expiresAt, exp)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,12 +30,17 @@ var (
|
||||
ErrMalformed = errors.New("malformed password hash")
|
||||
)
|
||||
|
||||
// dummyHash est un hash argon2id valide d'un mot de passe aléatoire fixe.
|
||||
// Il sert d'égalisation de timing : quand le username est inconnu, on vérifie
|
||||
// quand même contre ce hash pour que le délai de réponse soit identique à un
|
||||
// « mauvais mot de passe ».
|
||||
// dummyHash est un hash argon2id valide d'un mot de passe aléatoire généré
|
||||
// au boot. Il sert d'égalisation de timing : quand le username est inconnu,
|
||||
// on vérifie quand même contre ce hash pour que le délai de réponse soit
|
||||
// identique à un « mauvais mot de passe ». Aléatoire par boot pour éviter
|
||||
// toute préimage hardcodée (cf. FEEDBACK A1).
|
||||
var dummyHash = func() string {
|
||||
h, err := Hash("kazier-constantime-dummy")
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
panic(fmt.Sprintf("passwd: entropie dummy indisponible: %v", err))
|
||||
}
|
||||
h, err := Hash(string(raw))
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("passwd: impossible de pré-hacher le dummy: %v", err))
|
||||
}
|
||||
@@ -75,6 +80,18 @@ func Verify(password, stored string) error {
|
||||
if _, err := fmt.Sscanf(fields[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
|
||||
return ErrMalformed
|
||||
}
|
||||
// Caps anti-DoS : un hash stocké compromis ne doit pas provoquer un
|
||||
// OOM/CPU arbitraire au prochain login (cf. FEEDBACK §moyenne).
|
||||
const (
|
||||
maxMemory = 256 * 1024 // 256 MiB
|
||||
maxTime = 10
|
||||
maxThreads = 8
|
||||
maxKeyLen = 128
|
||||
maxSaltLen = 128
|
||||
)
|
||||
if memory <= 0 || memory > maxMemory || timeCost <= 0 || timeCost > maxTime || threads <= 0 || threads > maxThreads {
|
||||
return ErrMalformed
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(fields[4])
|
||||
if err != nil {
|
||||
@@ -84,6 +101,9 @@ func Verify(password, stored string) error {
|
||||
if err != nil {
|
||||
return ErrMalformed
|
||||
}
|
||||
if len(salt) == 0 || len(salt) > maxSaltLen || len(want) == 0 || len(want) > maxKeyLen {
|
||||
return ErrMalformed
|
||||
}
|
||||
|
||||
got := argon2.IDKey([]byte(password), salt, uint32(timeCost), uint32(memory), uint8(threads), uint32(len(want)))
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
|
||||
Reference in New Issue
Block a user