Skip to content

Instantly share code, notes, and snippets.

@lukpueh
Created March 20, 2020 14:46
Show Gist options
  • Save lukpueh/dae46ed4fc51cd55bb90d69d596e197c to your computer and use it in GitHub Desktop.
Save lukpueh/dae46ed4fc51cd55bb90d69d596e197c to your computer and use it in GitHub Desktop.
Minimal tuf repo <-> client unicode example
# coding: utf-8
"""Minimal tuf repo <-> client example, with unicode
- delegated targets role name, and
- target file name
"""
import os, tempfile, shutil, six
from tuf.repository_tool import *
from securesystemslib.process import subprocess, run_duplicate_streams
TARGET_ROLE_NAME = "😷"
TARGET_NAME = "🦠"
# Create and change into test tempdir inside cwd
temp_dir = tempfile.mkdtemp(dir=os.getcwd())
os.chdir(temp_dir)
# Init one key for all roles
generate_and_write_ed25519_keypair("key", password="0")
private_key = import_ed25519_privatekey_from_file("key", password="0")
public_key = import_ed25519_publickey_from_file("key.pub")
# Init repo with top-level roles
repo = create_new_repository("repo")
for role in ["root", "snapshot", "targets", "timestamp"]:
role_obj = getattr(repo, role)
role_obj.add_verification_key(public_key)
role_obj.load_signing_key(private_key)
# Create targets file and add it to targets metadata
with open(os.path.join("repo", "targets", TARGET_NAME), "w") as f: f.write("0")
repo.targets.delegate(TARGET_ROLE_NAME, [public_key], [TARGET_NAME])
repo.targets(TARGET_ROLE_NAME).add_target(TARGET_NAME)
repo.targets(TARGET_ROLE_NAME).load_signing_key(private_key)
# Write repository metadata to disk and publish
repo.writeall()
shutil.copytree(
os.path.join("repo", "metadata.staged"),
os.path.join("repo", "metadata"))
# Start repo server in subprocess
server_module = "SimpleHTTPServer" if six.PY2 else "http.server"
server_process = subprocess.Popen(
["python", "-m", server_module, "8001"], cwd="repo")
# Create client directory and copy over inital files
create_tuf_client_directory("repo", os.path.join("client", "tufrepo"))
# NOTE: 'create_tuf_client_directory' copies too much, this should also work with just root
for role in ["snapshot", "targets", "timestamp", TARGET_ROLE_NAME]:
for when in ["current", "previous"]:
os.remove(os.path.join("client", "tufrepo", "metadata", when, role +".json"))
# NOTE: would be nice if 'run_duplicate_streams' supported kwargs like 'cwd'
os.chdir("client")
_, _, err = run_duplicate_streams(
["client.py", "--repo", "http://localhost:8001", TARGET_NAME])
os.chdir("..")
# Shut down server process
server_process.kill()
# Change back and and tear down test repo
os.chdir("..")
shutil.rmtree(temp_dir)
# Assert TARGET_NAME was downloaded by the client
assert ("The file's sha256 hash is correct: "
"5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9") in err
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment