crypto: harden API surface

Make it explicit that expiration is not being tested with Decrypt, and
test that the expiration is meaningful with DecryptWithExpiration.
This commit is contained in:
Drew DeVault 2021-01-07 09:38:30 -05:00
parent 12996e4a18
commit 900693b830
4 changed files with 7 additions and 4 deletions

View File

@ -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

View File

@ -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})
}

View File

@ -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!"))
}

View File

@ -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")
}