Files
shopdb-flask/plugins/securesend/models/securesend.py

78 lines
3.0 KiB
Python

"""A secret handed over by link, encrypted before it ever reaches here.
NOT AN ASSET, so this is a standalone table rather than an extension keyed by
assetid: a shared credential is an event with a short life, not a thing the site
owns and inventories.
WHAT THIS TABLE CAN AND CANNOT SEE. The AES key lives in the URL fragment, which
browsers never send to a server, so what is stored is ciphertext and an IV and
nothing else. Compromising this table yields no secrets. It also means the
server cannot inspect what it is holding - which is the right trade for a
credential, and the reason the SIZE limit in the routes carries the whole weight
of "this is not a document transfer".
"""
from datetime import datetime, timezone
from shopdb.api import db, BaseModel
def _utcnow():
return datetime.now(timezone.utc).replace(tzinfo=None)
class SecureSecret(BaseModel):
"""One shared secret: opaque id, ciphertext, and the rules for its life."""
__tablename__ = 'securesendsecrets'
secretid = db.Column(db.Integer, primary_key=True)
# The unguessable half of the link. With no login on the read side this IS
# the credential, so it is 128 bits of randomness rendered as hex - never a
# sequence, which would be enumerable by anyone who received one link.
token = db.Column(db.String(64), unique=True, nullable=False, index=True)
# Base64 of the AES-GCM ciphertext, and the IV it was sealed with. Opaque
# here by design.
ciphertext = db.Column(db.Text, nullable=False)
iv = db.Column(db.String(64), nullable=False)
# Both limits apply, whichever comes first.
expiresat = db.Column(db.DateTime, nullable=False, index=True)
viewsremaining = db.Column(db.Integer, nullable=False, default=1)
# Who created it. The reader is anonymous by design, so this is the only
# person the row can name - and the reason creation requires a login.
createdbyuserid = db.Column(
db.Integer,
db.ForeignKey('users.userid', ondelete='SET NULL'),
nullable=True,
index=True,
)
# Recorded for the audit trail; the content of what was read is not
# recoverable, but that it was read, and when, is.
lastviewedat = db.Column(db.DateTime, nullable=True)
viewcount = db.Column(db.Integer, nullable=False, default=0)
def is_expired(self, now=None):
return (now or _utcnow()) >= self.expiresat
def is_spent(self):
return self.viewsremaining <= 0
def to_dict(self):
"""NEVER includes the ciphertext.
This is the shape the CREATOR sees back - a receipt. Handing the payload
back on create would put the secret in a second place for no reason.
"""
return {
'token': self.token,
'expiresat': self.expiresat.isoformat() if self.expiresat else None,
'viewsremaining': self.viewsremaining,
'viewcount': self.viewcount,
'createddate': self.createddate.isoformat() if self.createddate else None,
}