~bigbes/core-go

900693b830c34ef54b73bf3c1e88175d864719e9 — Drew DeVault 5 years ago 12996e4
crypto: harden API surface

Make it explicit that expiration is not being tested with Decrypt, and
test that the expiration is meaningful with DecryptWithExpiration.
4 files changed, 7 insertions(+), 4 deletions(-)

M auth/middleware.go
M crypto/crypto.go
M crypto/crypto_test.go
M model/cursor.go
M auth/middleware.go => auth/middleware.go +1 -1
@@ 215,7 215,7 @@ type AuthCookie struct {

func cookieAuth(cookie *http.Cookie, w http.ResponseWriter,
	r *http.Request, next http.Handler) {
	payload := crypto.Decrypt([]byte(cookie.Value))
	payload := crypto.DecryptWithoutExpiration([]byte(cookie.Value))
	if payload == nil {
		authError(w, "Invalid authentication cookie", http.StatusForbidden)
		return

M crypto/crypto.go => crypto/crypto.go +4 -1
@@ 63,12 63,15 @@ func Encrypt(payload []byte) []byte {
	return msg
}

func Decrypt(payload []byte) []byte {
func DecryptWithoutExpiration(payload []byte) []byte {
	return fernet.VerifyAndDecrypt(payload,
		time.Duration(0), []*fernet.Key{fernetKey})
}

func DecryptWithExpiration(payload []byte, expiry time.Duration) []byte {
	if expiry == 0 {
		panic(fmt.Errorf("DecryptWithExpiration given expiration of zero. Use DecryptWithoutExpiration if you really meant it."))
	}
	return fernet.VerifyAndDecrypt(payload, expiry, []*fernet.Key{fernetKey})
}


M crypto/crypto_test.go => crypto/crypto_test.go +1 -1
@@ 57,7 57,7 @@ func TestEncrypt(t *testing.T) {
	assert.NotNil(t, enc)
	assert.NotEqual(t, enc, []byte("Hello, world!"))

	dec := Decrypt(enc)
	dec := DecryptWithoutExpiration(enc)
	assert.NotNil(t, dec)
	assert.Equal(t, dec, []byte("Hello, world!"))
}

M model/cursor.go => model/cursor.go +1 -1
@@ 20,7 20,7 @@ func (cur *Cursor) UnmarshalGQL(v interface{}) error {
	if !ok {
		return fmt.Errorf("cursor must be strings")
	}
	plain := crypto.Decrypt([]byte(enc))
	plain := crypto.DecryptWithoutExpiration([]byte(enc))
	if plain == nil {
		return fmt.Errorf("Invalid cursor")
	}