Skip to content

Commit

Permalink
Fix part of the problem with notebook losing trust.
Browse files Browse the repository at this point in the history
See jupyter/nbformat#236 and
https://github.com/jupyter/nbformat/issue/235.

This mostly affects frontends that do not always add ids to cells,
like classic notebook, and that issue is not limited to cells ids, but
also to empty cells, that may not have/need a trusted field.

But that is another issue.
  • Loading branch information
Carreau committed Nov 23, 2021
1 parent 601ac0e commit 2b321ec
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions notebook/services/contents/filemanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,29 @@

_script_exporter = None

# workaround nbformat bug:
# nbformat save logic will mutate the notebook if it does not
# have cells ids, so if we sign the notebook,
# the signature of the saved notebook is changed.
# we thus need to add cell ids to the notebook before signing.
try:
from nbformat.validator import normalize
except ImportError:
from nbformat.corpus.words import generate_corpus_id
from copy import deepcopy

def normalize(nbdict, version, version_minor):
nbdict = depcopy(nbdict)

if version >= 4 and version_minor >= 5:
# if we support cell ids ensure default ids are provided
for cell in nbdict["cells"]:
if "id" not in cell:
changes += 1
# Generate cell ids if any are missing
cell["id"] = generate_corpus_id()
return nbdict


def _post_save_script(model, os_path, contents_manager, **kwargs):
"""convert notebooks to Python script after save with nbconvert
Expand Down Expand Up @@ -473,6 +496,8 @@ def save(self, model, path=''):
try:
if model['type'] == 'notebook':
nb = nbformat.from_dict(model['content'])

nb = normalize(nb, nb.get("nbformat"), nb.get("nbformat_minor"))
self.check_and_sign(nb, path)
self._save_notebook(os_path, nb)
# One checkpoint should always exist for notebooks.
Expand Down

0 comments on commit 2b321ec

Please sign in to comment.