From 35fcda70aa20bb643182e6d654b323a6a28e81b7 Mon Sep 17 00:00:00 2001 From: Didactic Drunk <1479616+didactic-drunk@users.noreply.github.com> Date: Wed, 2 Jun 2021 20:25:28 -0700 Subject: [PATCH] SecureBuffer: raise when out of memory --- spec/sodium/secure_buffer_spec.cr | 6 ++++-- src/sodium/secure_buffer.cr | 9 +++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/spec/sodium/secure_buffer_spec.cr b/spec/sodium/secure_buffer_spec.cr index a91cd23..368581f 100644 --- a/spec/sodium/secure_buffer_spec.cr +++ b/spec/sodium/secure_buffer_spec.cr @@ -43,8 +43,10 @@ describe Sodium::SecureBuffer do buf2 = buf.dup buf2.@state.should eq Sodium::SecureBuffer::State::Readwrite - buf[0] = 0_u8 - buf2[0] = 0_u8 + buf[0] = 1_u8 + buf.to_slice.hexstring.should_not eq buf2.to_slice.hexstring + buf2[0] = 1_u8 + buf.to_slice.hexstring.should eq buf2.to_slice.hexstring end it "transitions correctly" do diff --git a/src/sodium/secure_buffer.cr b/src/sodium/secure_buffer.cr index 2c3fd93..8b02384 100644 --- a/src/sodium/secure_buffer.cr +++ b/src/sodium/secure_buffer.cr @@ -13,6 +13,10 @@ module Sodium class InvalidStateTransition < Error end + + # Check RLIMIT_MEMLOCK if you receive this + class OutOfMemory < Error + end end enum State @@ -31,6 +35,7 @@ module Sodium def initialize(@bytesize : Int32) @ptr = LibSodium.sodium_malloc @bytesize + raise Error::OutOfMemory.new if @ptr.null? end # Returns a **readonly** random SecureBuffer. @@ -115,8 +120,8 @@ module Sodium end end - # Temporarily make buffer readonly within the block returning to the prior state on exit. - # WARNING: Not thread safe unless this object is readonly or readwrite + # Temporarily make buffer readwrite within the block returning to the prior state on exit. + # WARNING: Not thread safe unless this object is **readwrite** def readwrite with_state State::Readwrite do yield