Sub topic 11
Publishing only what was approved
This chapter assumes you have read the chapters on content states and approval gates. It also assumes you can read short Python programs. The earlier chapters decided who approves content. This chapter covers the last step: how the system makes sure that only approved text goes live.
Why publishing needs its own control
An approval gate records a decision. Publish control enforces it. Without enforcement, a workflow is a set of habits. Someone can still paste text into the live site, an editor can tweak a sentence after sign-off, or a script can push a draft that never reached review.
Three conditions must all be true at the moment content goes live:
- The item is in the APPROVED state, so it passed every gate its risk tier requires.
- The approval came from someone other than the author, in the number the tier demands.
- The text being published is exactly the text the reviewer approved.
The third condition is the one teams most often miss. A reviewer approves a particular version of the text, not an item identifier. If the text can change after approval and the approval still counts, the approval no longer means anything.
Binding approval to the exact text
The usual fix is to store a fingerprint of the approved text at approval time and compare it at publish time. A SHA-256 digest works well because any change to the text, even one character, produces a different digest.
Save this as workflow.py. It is the state machine from earlier chapters, with the approval digest in place.
import hashlib
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
class State(Enum):
DRAFT = "draft"
IN_REVIEW = "in_review"
CHANGES_REQUESTED = "changes_requested"
APPROVED = "approved"
PUBLISHED = "published"
ALLOWED = {
State.DRAFT: {State.IN_REVIEW},
State.IN_REVIEW: {State.APPROVED, State.CHANGES_REQUESTED},
State.CHANGES_REQUESTED: {State.IN_REVIEW},
State.APPROVED: {State.PUBLISHED},
State.PUBLISHED: set(),
}
def digest(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
@dataclass
class Item:
text: str
author: str
state: State = State.DRAFT
approved_digest: str | None = None
log: list = field(default_factory=list)
def _move(self, new_state, actor, note=""):
if new_state not in ALLOWED[self.state]:
raise ValueError(f"cannot go from {self.state.value} to {new_state.value}")
self.log.append({
"at": datetime.now(timezone.utc).isoformat(),
"actor": actor,
"from": self.state.value,
"to": new_state.value,
"note": note,
})
self.state = new_state
def revise(self, new_text, actor):
if self.state not in (State.DRAFT, State.CHANGES_REQUESTED):
raise ValueError("text can only be edited before review or after changes are requested")
self.text = new_text
self.log.append({"at": datetime.now(timezone.utc).isoformat(), "actor": actor, "edit": digest(new_text)})
def submit(self, actor):
self._move(State.IN_REVIEW, actor)
def request_changes(self, reviewer, note):
self._move(State.CHANGES_REQUESTED, reviewer, note)
def approve(self, reviewer):
if reviewer == self.author:
raise PermissionError("the author cannot approve their own item")
self._move(State.APPROVED, reviewer)
self.approved_digest = digest(self.text)
def publish(self, actor):
if self.approved_digest != digest(self.text):
raise ValueError("text differs from the approved version")
self._move(State.PUBLISHED, actor)Two layers protect the text. The state machine blocks revise() once an item is approved, which stops honest mistakes. The digest check in publish() stops everything the state machine cannot see: a direct database edit, a bug in another service, or a script that sets item.text without going through revise().
The publish gate in practice
Item.publish() only changes the record. In a real system something also has to push the text to a website, a CMS, or an email platform. That step needs its own guard. The function below wraps the push so the check and the push use the same snapshot of the text.
from workflow import Item, State, digest
live_site = {}
def go_live(item, actor, push):
if item.state is not State.APPROVED:
raise ValueError(f"item is {item.state.value}, not approved")
snapshot = item.text
if digest(snapshot) != item.approved_digest:
raise ValueError("text differs from the approved version")
push(snapshot)
item.publish(actor)
item = Item(text="Spring sale starts Monday.", author="ben")
item.submit("ben")
item.approve("ana")
item.text = "Spring sale starts Monday. Guaranteed savings!" # bypasses revise()
try:
go_live(item, "ben", lambda t: live_site.update(page=t))
except ValueError as error:
print("blocked:", error)
item.text = "Spring sale starts Monday."
go_live(item, "ben", lambda t: live_site.update(page=t))
print(item.state.value, live_site)The first attempt prints blocked: text differs from the approved version. The second prints published {'page': 'Spring sale starts Monday.'}.
Three details are worth noticing:
- The author,
ben, can publish. Publishing is a mechanical step, not a judgment, so separation of duties applies to approval and not to the final button. Some teams restrict it anyway. That is a policy choice, not a requirement of the design. - The snapshot is taken once. The code checks
snapshotand pushessnapshot. If it checkeditem.textand then pusheditem.text, the text could change between the two reads. - Restoring the original text makes the item publishable again. The digest binds approval to content, not to history. That is correct, but it also means the tampering edit left no trace in
item.log, because it did not go throughrevise().
The full path to live content
Every rejection should be logged with the reason. A rejected publish is information. Repeated digest mismatches on one item usually mean some other tool is editing text behind the workflow's back.
Make the gate the only door
A check is useful only if it cannot be walked around. Most real failures of publish control are not broken checks. They are other paths to the live site.
- Give the publishing service the only write credential for the live site. Editors, authors, and the drafting model should have no direct write access.
- Do not let the AI drafting step call the publish function. Drafting produces text and submits it. Everything after that belongs to people and the workflow.
- Make the publish function the only code that moves an item to PUBLISHED, and keep the state map in one place so no second code path can change states.
- Treat scheduled publishing the same way. A scheduler should call
go_liveat the chosen time, so the checks run at publish time and not only when the schedule was set.
Scheduling is a common edge case. If a post is scheduled for Friday and someone edits it on Thursday, the digest check catches it only if the check runs on Friday. Checking once, when the schedule is created, leaves a gap.
Normalization and what counts as the same text
Strict comparison has a cost. If your editor adds a trailing newline or converts line endings, the digest changes and publishing fails for a harmless reason. You have two choices:
- Compare bytes exactly. This is simple and safe, and it needs an editor that does not silently reformat. A failed publish after a trivial change is an annoyance, not a risk.
- Normalize first, for example strip trailing whitespace and use one line-ending style, then hash. This reduces false alarms. Keep the rules small and write them down, because every character a rule ignores is a character that can change after approval. Never normalize away words, punctuation, or numbers.
Start with exact comparison. Add normalization only when false alarms become costly, and review that rule as carefully as you would review content.
Failure modes at publish time
- Push succeeds, recording fails. In
go_live, the site could be updated and thenitem.publish()could raise an error. The item stays APPROVED while the content is live. A retry is safe because the same snapshot passes the same checks, so make the push idempotent, meaning repeating it with the same content has no further effect. Reconcile by comparing the live content to the approved digest. - Push fails, nothing recorded. The item stays APPROVED and nothing is lost. Retry later.
- Approval is stale. Policy may say an approval expires after some days, for example if a price or a law might change. Store the approval time and add a check for it. The log already holds timestamps.
- Tier rules change. If a tier now requires two approvals and an item has one, decide whether old approvals are grandfathered. Make that decision explicit, and have the gate read the current rule so no item is exempt by accident.
- The tier check is skipped. The digest check proves the text is unchanged. It does not prove enough people approved it. Run both. The earlier
can_publish(risk_tier, approvers, author)function counts only approvers other than the author, so call it inside the gate.
Corrections after publishing
In the state map, PUBLISHED has no outgoing transitions. That is deliberate. A published item is a record, and editing it in place would break the link between the log and the live text.
To correct a live piece, create a new item that refers to the old one and send it through the whole pipeline. When it is published, retire the earlier version on the site. For urgent takedowns, such as a legal problem, provide a separate retract action that anyone on call can use. It should be logged like any other transition. Taking something down is safer than putting something up, so it can have a lighter gate. It still needs an audit entry with a named actor and a reason.
Exercise
An item was approved with text X. Before publishing, a script sets the text to Y by assigning to item.text directly. The item's log shows no edit. What stops Y from going live, and what does the log fail to show?
Show answer
The digest check stops it. go_live compares the digest of the current text with approved_digest, which was computed from X, so they differ and the publish is rejected. The log fails to show who changed the text, because the script bypassed revise(), which is the only method that writes an edit entry. The rejection itself should be logged, and the credential model should prevent such direct writes in the first place.
Exercise
A post is scheduled to publish on Friday. On Thursday an editor fixes a typo in the stored text. Where should the digest check run so the typo fix is not published unreviewed, and what should happen to the approval?
Show answer
The check should run on Friday, at the moment the scheduler calls the publish function, not only when the schedule is created. The typo fix changes the digest, so publishing is rejected. The item should go back through review and be approved again, so a new digest is stored for the corrected text.