forked from mtusi2026/mtusi2026lab3
На 5
This commit is contained in:
@@ -3,7 +3,9 @@ package encrypting
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -30,13 +32,13 @@ func (e *encryptor) EncryptSecret(_ context.Context, secret string) (string, err
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) EncryptSecretUsingSum256(_ context.Context, secret string) (string, error) {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
res, err := e.generateFromPasswordFunc([]byte(hex.EncodeToString(sum[:])), e.cost)
|
||||
if err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
// EncryptSecretUsingSum256 hashes a high-entropy session token, not a password.
|
||||
func (e *encryptor) EncryptSecretUsingSum256(ctx context.Context, secret string) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(res), nil
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return "sha256:" + hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password string) error {
|
||||
@@ -47,11 +49,24 @@ func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password strin
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(_ context.Context, hash, password string) error {
|
||||
sum := sha256.Sum256([]byte(password))
|
||||
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:])))
|
||||
if err != nil {
|
||||
return ErrFailedToComparePasswords
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(ctx context.Context, hash, secret string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
if payload, ok := strings.CutPrefix(hash, "sha256:"); ok {
|
||||
stored, err := hex.DecodeString(payload)
|
||||
if err != nil || len(stored) != sha256.Size || subtle.ConstantTimeCompare(stored, sum[:]) != 1 {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Preserve existing lab2/lab3 sessions across a rolling deployment.
|
||||
// Passwords continue to use Argon2id; only old random-token fingerprints use this fallback.
|
||||
if strings.HasPrefix(hash, "$2") {
|
||||
if err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:]))); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSessionFingerprints(t *testing.T) {
|
||||
e := New()
|
||||
ctx := context.Background()
|
||||
token := "synthetic-high-entropy-session-value"
|
||||
hash, err := e.EncryptSecretUsingSum256(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, hash, token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{"sha256:00", "sha256:invalid", "unknown"} {
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, bad, token) == nil {
|
||||
t.Fatal("accepted malformed fingerprint")
|
||||
}
|
||||
}
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, hash, token+"x") == nil {
|
||||
t.Fatal("accepted wrong token")
|
||||
}
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
legacy, err := bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(sum[:])), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, string(legacy), token); err != nil {
|
||||
t.Fatal("legacy session rejected", err)
|
||||
}
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if e.CompareHashAndSecretUsingSum256(canceled, hash, token) == nil {
|
||||
t.Fatal("ignored cancellation")
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,16 @@ func Token(r *http.Request) (string, bool) {
|
||||
return token, true
|
||||
}
|
||||
|
||||
type sessionContextKey struct{}
|
||||
|
||||
func WithVerifiedSession(r *http.Request, data *dto.UserDataInToken) *http.Request {
|
||||
return r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, *data))
|
||||
}
|
||||
|
||||
func ParseToken(r *http.Request, provider jwtprovider.Provider) (*dto.UserDataInToken, error) {
|
||||
if data, ok := r.Context().Value(sessionContextKey{}).(dto.UserDataInToken); ok {
|
||||
return &data, nil
|
||||
}
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "missing authorization header")
|
||||
|
||||
@@ -39,12 +39,13 @@ func (a *authMiddleware) WithAdminAccess(next http.Handler) http.Handler {
|
||||
|
||||
func (a *authMiddleware) privateAccessCheckCallback(next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := a.verifySession(r); err != nil {
|
||||
data, err := a.verifySession(r)
|
||||
if err != nil {
|
||||
framework.JSONError(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
next.ServeHTTP(w, framework.WithVerifiedSession(r, data))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +62,7 @@ func (a *authMiddleware) operatorAccessCheckCallback(expectedRole role.Role, nex
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
next.ServeHTTP(w, framework.WithVerifiedSession(r, u))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type sessionVerifier struct {
|
||||
calls int
|
||||
data dto.UserDataInToken
|
||||
err error
|
||||
}
|
||||
|
||||
func (v *sessionVerifier) VerifySession(context.Context, dto.Token) (*dto.UserDataInToken, error) {
|
||||
v.calls++
|
||||
return &v.data, v.err
|
||||
}
|
||||
|
||||
func TestVerifiedSessionIsRequestScoped(t *testing.T) {
|
||||
verifier := &sessionVerifier{data: dto.UserDataInToken{UserID: uuid.New()}}
|
||||
middleware := NewAuthMiddleware(verifier)
|
||||
handled := 0
|
||||
handler := middleware.WithPrivateAccess(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// A nil provider is intentional: the handler must use the verified request identity.
|
||||
data, err := framework.ParseToken(r, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data.UserID != verifier.data.UserID {
|
||||
t.Fatal("verified identity changed")
|
||||
}
|
||||
handled++
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
for range 2 {
|
||||
request := httptest.NewRequest("GET", "/private", nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != 204 {
|
||||
t.Fatal(recorder.Code)
|
||||
}
|
||||
}
|
||||
if verifier.calls != 2 || handled != 2 {
|
||||
t.Fatal("session verification must run for every request")
|
||||
}
|
||||
verifier.err = apperr.New(apperr.CodeUnauthorized, "revoked session")
|
||||
request := httptest.NewRequest("GET", "/private", nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != 401 || handled != 2 {
|
||||
t.Fatal("revocation was bypassed by cached request identity")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingTokenDoesNotCallSessionStore(t *testing.T) {
|
||||
verifier := &sessionVerifier{err: errors.New("must not be called")}
|
||||
handler := NewAuthMiddleware(verifier).WithPrivateAccess(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Fatal("handler called without a token") }))
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/private", nil))
|
||||
if recorder.Code != 401 || verifier.calls != 0 {
|
||||
t.Fatal("missing token was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
func Instance(id string) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user