Freezing signed documents in Postgres with triggers
In my Rails 8 app the model says a signature is read-only. The database makes sure of it.

When a customer signs an estimate in the app I'm building, three things get written to the database: the version of the estimate they saw, the signature itself, and a log of events around it (sent, viewed, signed). After that, those rows should never change. If the contractor and the customer ever remember the deal differently, the stored version is the record both of them can look at. It's worth nothing if anyone could have edited it afterwards.
The app is Quoza, an estimate app for trade businesses of one to five people. It runs on Rails 8 and Postgres. This post is about how I made those rows read-only in the database with triggers, and what that changed in the Rails code and in the tests.
Why the model isn't enough
The model has its own guard. Signature#readonly? returns true once the record is sealed, and before_destroy raises. That covers update! and destroy on a loaded record.
It doesn't cover update_all, update_column, delete_all, a raw execute inside a data migration, or a quick fix typed into a production console. All of them skip callbacks and validations. So does any background job someone writes next year without knowing the rule.
So the same rule also lives in Postgres. The model guards fail early with a clear error. The triggers are the last line: whatever code writes to the table, the database refuses.
The simple case: append-only
signature_events is a log. Rows are inserted and never touched again. One function covers it, and I reuse it for other log tables:
CREATE FUNCTION quoza_append_only_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION '% is append-only: % forbidden', TG_TABLE_NAME, TG_OP
USING ERRCODE = 'restrict_violation';
END;
$$;
CREATE TRIGGER signature_events_append_only
BEFORE UPDATE OR DELETE ON signature_events
FOR EACH ROW EXECUTE FUNCTION quoza_append_only_guard();
TG_TABLE_NAME and TG_OP put the table and the operation into the message, so the same function works on any table. INSERT isn't in the trigger, so new events are written as usual.
Each event also stores a SHA-256 hash of the previous event's hash plus its own fields. SignatureEvent.chain_valid? walks the chain and recomputes every hash, so a row changed behind the trigger's back breaks the chain.
Frozen except for a few columns
Sent estimate versions are harder. A sent version has to stay exactly as the customer saw it, but one thing can still happen to it: a newer version replaces it. The contractor edits the estimate and sends it again, and the old version gets superseded_at and superseded_by_id. Drafts stay fully editable and can be deleted.
I didn't want to list every frozen column in the trigger, because someone adds a column next month and forgets the trigger. So the function turns both rows into jsonb, removes the columns that may change, and compares what's left:
CREATE FUNCTION quoza_sent_quote_versions_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF OLD.kind <> 'sent' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
IF NEW.kind = 'sent' THEN
RAISE EXCEPTION 'quote_version %: a draft step cannot become sent', OLD.id
USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
END IF;
IF TG_OP = 'DELETE' THEN
RAISE EXCEPTION 'sent quote_version % is immutable: DELETE forbidden', OLD.id
USING ERRCODE = 'restrict_violation';
END IF;
IF (to_jsonb(NEW) - ARRAY['superseded_at', 'superseded_by_id', 'updated_at'])
IS DISTINCT FROM
(to_jsonb(OLD) - ARRAY['superseded_at', 'superseded_by_id', 'updated_at']) THEN
RAISE EXCEPTION 'sent quote_version % is immutable: only superseding is allowed', OLD.id
USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
END;
$$;
With an allow-list, a new column is frozen by default. If it has to be editable after sending, you change the function on purpose, in a migration, where a reviewer sees it. A draft also can't be turned into a sent version with an UPDATE. Sending always inserts a new row.
Sealing: one update, then never again
A signatures row gets exactly one update after it's created. The signed PDF is rendered, its SHA-256 goes into document_sha256, and from then on the row is sealed:
IF TG_OP = 'DELETE' THEN
RAISE EXCEPTION 'signatures are immutable: DELETE forbidden (id %)', OLD.id
USING ERRCODE = 'restrict_violation';
END IF;
IF OLD.document_sha256 IS NOT NULL THEN
RAISE EXCEPTION 'signature % is sealed: UPDATE forbidden', OLD.id
USING ERRCODE = 'restrict_violation';
END IF;
IF (to_jsonb(NEW) - ARRAY['document_sha256', 'pdf_generated_at', 'updated_at'])
IS DISTINCT FROM
(to_jsonb(OLD) - ARRAY['document_sha256', 'pdf_generated_at', 'updated_at']) THEN
RAISE EXCEPTION 'signature % evidence columns are immutable', OLD.id
USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
Before sealing, only the hash and its timestamp can be set. After sealing, nothing. The signer's name, IP address, user agent, consent text version and the amounts are frozen from the first insert.
The PDF bytes live in Postgres too, through a database service for Active Storage. Later I added the same kind of guard on the Active Storage tables. A file attached as signed_pdf is accepted only if encode(sha256(f.data), 'hex') equals the signature's document_sha256, so the database checks that the stored file is the one that was hashed.
The Rails side
schema.rb can't hold functions or triggers. With config.active_record.schema_format = :sql, Rails dumps db/structure.sql, and the test database is built from it, triggers included. Without that switch the tests would run against a database with no triggers and pass for the wrong reason.
The triggers themselves are plain execute <<~SQL migrations, with a down that drops them.
The model keeps its own guard:
class Signature < ApplicationRecord
MUTABLE_UNTIL_SEALED = %w[document_sha256 pdf_generated_at updated_at].freeze
validate :evidence_unchanged, on: :update
before_destroy { raise ActiveRecord::ReadOnlyRecord, "signatures are retained" }
def sealed? = document_sha256_in_database.present?
def readonly? = (persisted? && sealed?) || super
private
def evidence_unchanged
changed_evidence = changed - MUTABLE_UNTIL_SEALED
errors.add(:base, "signature evidence is immutable") if changed_evidence.any?
end
end
The same column list is in Ruby and in SQL. That's duplication, and I keep it. The Ruby check gives a validation error the app can handle. The SQL check catches everything else. When Postgres refuses a write, Rails raises ActiveRecord::StatementInvalid with the trigger's message, and the transaction rolls back.
sealed? reads document_sha256_in_database, the stored value. Assigning the attribute in memory doesn't make the record look sealed before it's saved.
Testing the database, not the model
A test that calls signature.update! only tests the Ruby guard. To test the triggers, the tests go around the model on purpose and send raw SQL:
def sql(statement)
ActiveRecord::Base.transaction(requires_new: true) do
ActiveRecord::Base.connection.execute(statement)
end
end
def assert_db_rejects(statement)
error = assert_raises(ActiveRecord::StatementInvalid) { sql(statement) }
assert_match(/immutable|append-only|sealed/, error.message)
end
test "signature_events are append-only" do
event = @g[:signature_event]
assert_db_rejects "UPDATE signature_events SET event = 'signed' WHERE id = #{event.id}"
assert_db_rejects "DELETE FROM signature_events WHERE id = #{event.id}"
end
requires_new: true wraps each statement in a savepoint. Without it, the first refused statement aborts the test's transaction, and every query after it fails with "current transaction is aborted".
The same file checks the other direction too: drafts can still be updated and deleted, and a sent version that nobody signed can still be superseded. A trigger that blocks too much is also a bug.
What it costs
Deleting old data takes a deliberate step. A retention purge has to run as the database owner with ALTER TABLE ... DISABLE TRIGGER written out explicitly. I'm fine with that, because I want deleting a signature to be hard.
Changing a rule means a migration that replaces a function. Two rules came later this way. A signed version can't be superseded. And nobody can sign a version that has already been superseded: a BEFORE INSERT trigger on signatures checks the version row, and it takes that row FOR SHARE first, so a send running at the same moment can't slip past it.
The trigger messages are for developers. A user should never see one. If a user hits one, the bug is in the app code above it.
If you've solved this another way, for example with REVOKE UPDATE on the app's database role or with a separate audit table, how did it hold up?
About the author
- I'm building Quoza, a phone-first estimate app for trade crews of one to five people: write the quote on site, text the customer one link, and they pick an option, sign and pay a deposit. Before Quoza I was a telecom engineer, a key account manager and head of sales at an IT services company, then spent five years on growth and marketing at a warehouse software company. I write about pricing jobs, getting paid, and building a small SaaS on Rails 8 and Hotwire.
Comments
Join the discussionNo comments yet. Be the first to comment.