NETWORK SECURITY AND FIREWALLS
Try the `upki` preview for Ubuntu
This article was originally posted on the Ubuntu Discourse, and is reposted here. I welcome comments and further discussion in that thread. The development of upki has been steadily progressing over the past few months. Since my last update, the project has released a beta version of the CLI tool and library, and the Ubuntu Foundations team has released a preview that users of Ubuntu 26.04 LTS and Ubuntu 26.10 development snapshots can try out. The preview is still experimental, but it contains both the upki client packages, and the initial OpenSSL integration. An instance of the upki mirror which serves the CRLite filter data is being hosted in Canonical’s infrastructure at upki.ubuntu.com. In this post I’ll briefly recap what upki is trying to achieve, cover the infrastructure and packaging work that has landed, and show how to try the preview on Ubuntu 26.04 LTS or Ubuntu 26.10. Recap: what is upki? Linux has long had a gap in how it handles Web PKI data outside browsers. Firefox and Chromium have mature, browser-specific infrastructure for certificate revocation and related PKI data, but system utilities, package managers, language runtimes and many command-line tools have historically lacked a consistent mechanism for checking whether a publicly trusted TLS certificate has been revoked. upki’s first goal is to bring reliable, efficient and privacy-preserving revocation checking to Linux and other Unix-like operating systems. It builds on Mozilla’s CRLite work, using compact filter data that can be synced locally and queried offline. The client can then answer the question “is this certificate revoked?” without leaking browsing activity to a certificate authority (CA) and without requiring every application to implement its own CRL management stack. The project is designed around a few interfaces: a command-line tool for fetching revocation data and checking certificate chains; a Rust library for direct integration with Rust applications; a C FFI for integration from C, C++, Go and other runtimes; a rustls-upki integration crate for Rust applications using rustls; and an upki-openssl integration layer that exposes an OpenSSL verification callback. Longer-term, the same local data distribution mechanism could support other browser-grade Web PKI data, including intermediate preloading, Certificate Transparency policy, root distrust information and, further out, Merkle Tree Certificates. Recent progress #The upstream rustls/upki repository has moved on substantially since the initial upki-0.1.0 release in February. The current beta pre-release is upki-1.0.0-beta.1, published on 10 June 2026. Since then, the C FFI has been folded into the main upki crate and now has a documented minimal example, upki-openssl has landed, exposing upki_openssl_verify_callback() for OpenSSL-based clients, and the rustls-upki crate now provides policy-controlled behaviour for missing data, certificates not covered by revocation data, and certificates without Signed Certificate Timestamps (SCTs). The upki package we’re making available in a PPA installs a system-wide configuration file under /etc/upki/config.toml, creates a dedicated upki service user, and installs an upki-fetch.timer that runs every two hours after an initial boot delay. Install the development preview # This preview is intended for testing only. It includes patched OpenSSL packages, so use a disposable VM or test system, not a production machine. On Ubuntu 26.04 LTS or Ubuntu 26.10, add the preview PPA: 1 2 sudo add-apt-repository ppa:ubuntu-foundations-team/upki-preview sudo apt install openssl upki libupki-openssl1 On Ubuntu 26.10, upki is intended to come from the archive while the preview PPA supplies the patched OpenSSL integration. On Ubuntu 26.04 LTS, the PPA supplies both the backported upki package and the patched OpenSSL packages. Once installed, the revocation cache will populate on a timer (run systemctl status upki-fetch.timer for details). To trigger a fetch manually: 1 sudo -u upki upki fetch For a manual check, pipe a certificate chain from curl into upki: 1 2 3 4 5 $ curl -sw '%{certs}' https://google.com | upki revocation check NotRevoked $ curl -sw '%{certs}' https://revoked-ctrca.certificates.certum.pl/ | upki revocation check CertainlyRevoked For the OpenSSL path, tools linked against the patched OpenSSL build can exercise revocation checking during certificate verification. For example, testing against a deliberately revoked certificate endpoint should fail during the TLS handshake with OpenSSL reporting a revoked certificate: 1 2 3 4 5 $ curl https://revoked-ctrca.certificates.certum.pl/ curl: (60) SSL certificate OpenSSL verify result: certificate revoked (23) More details here: https://curl.se/docs/sslcerts.html. curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the webpage mentioned above. The integration with OpenSSL is probably the most important part of this preview. When the packaging is finalised for Ubuntu (and included by default), any utility that links against a patched TLS provider (like OpenSSL), and follow the standard certificate verifications path should benefit from upki-backed revocation checking without application-specific changes. The current preview is intentionally broad so that we can test the plumbing. The final integration policy may be narrower, and some applications that disable or override OpenSSL verification will need direct application-level integration rather than relying solely on a library callback. Canonical-hosted infrastructure #One of the pieces I called out in the last update was production infrastructure. upki needs a mirror for CRLite filter data so that clients are not coupled directly to Mozilla’s internal serving infrastructure, and so that distributions and large deployments can point their systems at a stable, policy-controlled endpoint. That work is now in place for the preview. The Ubuntu preview packages point at: 1 2 [revocation] fetch-url = "https://upki.ubuntu.com/revocation/" The endpoint is live and serving a manifest.json describing the current revocation filter set. The service is operated using the upki-mirror Kubernetes operator, a Charmed Operator that drives the upki-mirror service on Kubernetes. The operator packages the mirror binary in a chiseled container and serves the generated filter data with nginx. What’s next #The next phase is about polishing the preview into something we can confidently integrate more widely. The aim is to ship upki and its early integrations by default in Ubuntu 26.10. Over the coming weeks we’re hoping to gather feedback from this preview and fix any issues in the packaging/Ubuntu integration, while the core team behind upki continues to work on the OpenSSL integration and measuring the fetch performance, cache size and revocation query latency on real systems. As always, thanks to Dirkjan, Joe, Julian and everyone else contributing to the implementation, packaging and infrastructure work that has made this preview possible.
CANONICALUBUNTUMOZILLACANONICAL
WATER RESOURCES AND MANAGEMENT
Revitalising Ubuntu Project Documentation
> This article was originally posted on the Ubuntu Discourse, and is reposted here. I welcome comments and further discussion in that thread. ## Introduction # Back in February I wrote some thoughts on Ubuntu’s documentation and its role within the community. For a mostly-online software community, documentation is one of our most critical forms of communication. In the last two years there has been lots of focus on the technical aspects of our documentation (how-to guides, tutorials, etc.), but I’d like to focus more on what I’m calling the “Ubuntu Project Documentation” over the coming months. Documentation isn’t only about technical how-to guides and tutorials, nor is it only about troubleshooting or satisfying particular use-cases. Our documentation can set the tone for the project, give a means for the community to state an intent, and guide both current and future contributors in their daily work. Ubuntu has a lot of documentation, most of which has grown organically over the last 20 years, but it’s not always easy to find or understand. Our documentation should illuminate and inspire a path to contribution. It should provide direction and clarity on complex issues, reference on technology and past decisions, and precision in the execution of process. Our project documentation should detail what makes Ubuntu happen. How are decisions made? What are the teams contributing to Ubuntu? How are those teams appointed? What are their responsibilities? If you’re on the Main Inclusion Review (MIR) team and you’re assigned a package to review, what steps should you take? How does package sponsorship work, and who should you contact if you’re stuck? How are the Access Control Lists (ACLs) updated for packages and package sets, and who can make those changes? What does the journey look like from first time package bug-fixer to Ubuntu Core Developer? These are all examples of questions that we, the collective conscious of Ubuntu, know the answers to, yet it is still difficult to find up-to-date answers to these questions, often requiring input from some of our busiest and most knowledgeable contributors to settle discussions and answer basic queries. If a potential contributor identifies a bug in a package, there should be one authoritative source of information on where the package source can be located, how it can be pulled, built and tested, and how to work with a sponsor to land changes. Such a process is satisfying for contributors, making it more likely they’ll stay engaged, and therefore benefits the distribution’s longevity and sustainability. Answering questions and mentoring people will remain a central part of our community’s role, but many of the first questions asked could be serviced by better documentation. ## The Challenge # Much of the required content already exists. The venerable Ubuntu Wiki was the go-to destination for such documentation, but has become outdated both technologically and in the content it serves. This degradation gained pace as we diversified the number of destinations that documentation could live: the Wiki, Discourse, Github, Launchpad, etc. The Ubuntu Community team have made significant efforts over the past months to centralise the documentation for membership, our code of conduct and project governance. I also called out the renewed Stable Release Update (SRU) documentation in my first post for having made its first steps toward a new and improved structure. These examples prove we have all the skills we need to write excellent documentation. Throughout the 25.10 cycle, I intend to put some focus on this, consolidating as much of our content into modern formats as possible, thereby making it as accessible as possible. In doing this work, I hope to: - Illustrate contributor journeys across disciplines - Create resilience in the project by reducing the “bus factor” - Increase the accessibility and ergonomics of our documentation - Enable more efficient, asynchronous collaboration on a wide range of tasks ## End Goal # To quote the Canonical.com page on Documentation Practice: > we have embarked on a comprehensive, long-term project to transform documentation. Our aim is to create and maintain documentation product and practice that will represent a standard of excellence. We want documentation to be the best it possibly can be. At the heart of this mission Diátaxis: a way of thinking about documentation. Diátaxis “prescribes approaches to content, architecture and form that emerge from a systematic approach to understanding the needs of documentation users”. You’ll have seen Diátaxis in use across many of our product documentation pages: the Juju docs, the MAAS docs, the Pebble docs, the Rockcraft docs and many more. Most of those existing sites are specific - they document a particular product or ecosystem which neatly scopes the documentation structure, but the Diátaxis framework can also be used to bring structure, precision and clarity to the documentation of the Ubuntu project as a whole. Earlier this month I surveyed the various documentation sites in use by Canonical and the Ubuntu Community, and settled on three common themes around which we will structure our renewed project documentation: - Governance: in which membership, code of conduct, team structures, communication practices, delegation, mission, software licensing and 3rd-party software guidelines will be documented. - Develop Ubuntu: documentation for current and aspiring Ubuntu developers, including how to package software for Ubuntu, how to merge packages from Debian, how to sponsor packages, how to use
git-ubuntu and conduct “+1 Maintenance”, etc. - Archive Administration: the nuts and bolts of managing Ubuntu’s prolific software repositories: how to manage seeds, configure phased updates, conduct an MIR, run an SRU process, etc. These categories were not immediately obvious, and they’re not necessarily mutually exclusive, but they fell out quite naturally when trying to logically organise our existing content. During the process, I came up with this rough sketch: an outline of how our Ubuntu Project documentation might be structured This illustrates how multiple categories of documentation from different corners of Ubuntu might come together in a single landing page. To give an idea of how we might further break down existing content by type, then category: an outline of how our Ubuntu Project documentation TOC might be structured This may not be the final structure, but it’s indicative of how we can use Diátaxis to break down large documentation premises into smaller, more digestible and more ergonomic pieces. ## The Plan # During the Ubuntu 25.10 cycle, we’ll be dedicating two of our Technical Authors to make this happen. One of these authors has been largely responsible for overhauling the Ubuntu Server docs, but both are very familiar with Diátaxis and the tooling we using to deliver documentation. Throughout this process, we’ll likely come across outdated, poorly reviewed or incorrect documentation, but as we work through the process of consolidating, we can note where this has happened and get it on our backlog to fix. Perhaps we’ll find items which lend themselves to inclusion in the Canonical Open Documentation Academy, or maybe we’ll need to reach out to some of our less active community members for clarification, but once the structure is in place we’ll at least have a place to collaborate. Once the transition is complete, there will be an authoritative source for project documentation that is easy to navigate, easy to contribute to and with a well-defined review process that encourages progress over gatekeeping. ## Summary # Documentation is the backbone of a thriving open-source community, guiding contributors, setting expectations, and ensuring long-term sustainability. While Ubuntu has extensive documentation, much of it is scattered, outdated, or difficult to navigate. By leveraging the Diátaxis framework, we aim to bring structure, clarity, and accessibility to Ubuntu Project Documentation. Our focus will be on governance, development, and archive administration, ensuring that key processes and responsibilities are well-documented and easy to follow. With dedicated technical authors and community collaboration, the Ubuntu 25.10 cycle will mark a significant step toward making our documentation searchable, structured, and sustainable. I hope this effort will empower contributors, reduce reliance on institutional knowledge, and create a more resilient project for the next generation of Ubuntu developers and users.WEB DEVELOPMENT AND INTERNET TECHNOLOGIES
Libations: Tailscale on the Rocks
## Introduction # I’m a long-time, self-professed connoisseur of cocktails. I’ve always enjoyed making (and drinking!) the classics, but I also like experimenting with new base spirits, techniques, bitters etc. Over the years, I’ve collected recipes from a variety of sources. Some originated from books (such as Cocktail Codex and Cocktails Made Easy), others from websites (Difford’s Guide), and most importantly those that I’ve either guessed from things I’ve drunk elsewhere (like my favourite bar in Bristol, The Milk Thistle), or modifications to recipes from the referenced sources. I wanted somewhere to store all these variations: somewhere that I could search easily from my iPhone (which is nearly always close to me when I’m making drinks). I wanted each recipe to fit in its entirety on my iPhone screen without the need to scroll. Around the time I started thinking about this problem, I also learned about
tsnet and was desperate for an excuse to try it out - and thus Libations was born as the product of two things I love: Tailscale and cocktails! ## tswhat? # Some time ago, Tailscale released a Go library named tsnet. To quote the website: > tsnet is a library that lets you embed Tailscale inside of a Go program In this case, the embedded Tailscale works slightly different to how tailscaled works (by default, anyway…). Rather than using the universal TUN/TAP driver in the Linux kernel, tsnet instead uses a userspace TCP/IP networking stack, which enables the process embedding it to make direct connections to other devices on your tailnet as if it were “just another machine”. This makes it easy to embed, and drops the requirement for the process to be privileged enough to access /dev/tun. One of the things I like about how tsnet presents applications as devices on the tailnet, is that you can employ ACLs to control who and what on your tailnet can access the application, rather than the device. I’ve solved this problem before by putting applications in their own systemd-nspawn container and joining those containers to my tailnet. Another nice option is tsnsrv which essentially acts as a Tailscale-aware proxy for individual applications, but in this case I wanted to bake it into the application - which I would only access over my tailnet. Getting started with tsnet couldn’t be easier: | 1 2 3 | bash mkdir tsnet-app; cd tsnet-app go mod init tsnet-app go get tailscale.com/tsnet | | ------------- | ------------------------------------------------------------------------------------------ | That will get you set up with a basic Go project, with the tsnet library available. Create a new main.go file with the following contents: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | go package main import ( "fmt" "log" "net/http" "tailscale.com/tsnet" ) func main() { // Create a new tsnet server instance s := tsnet.Server{Hostname: "tsnet-test"} defer s.Close() // Have the tsnet server listen on :8080 ln, err := s.Listen("tcp", ":8080") if err != nil { log.Fatal(err) } defer ln.Close() // Define a very simple handler with a simple Hello, World style message handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<html><body><h1>Hello from %s, tailnet!</h1>\n", s.Hostname) }) // Start an HTTP server on the tsnet listener err = http.Serve(ln, handler) if err != nil { log.Fatal(err) } } | | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | This is about the most minimal example I could contrive. The code creates a simple instance of tsnet.Server with the hostname tsnet-app, listens on port 8080 and serves up a simple Hello, World! style message. On running the application you’ll see the following: | 1 2 3 4 5 | bash ❯ go run . 2024/08/13 15:03:37 tsnet running state path /home/jon/.config/tsnet-tsnet-app/tailscaled.state 2024/08/13 15:03:37 tsnet starting with hostname "tsnet-test", varRoot "/home/jon/.config/tsnet-tsnet-app" 2024/08/13 15:03:38 LocalBackend state is NeedsLogin; running StartLoginInteractive... 2024/08/13 15:03:43 To start this tsnet server, restart with TS_AUTHKEY set, or go to: https://login.tailscale.com/a/deadbeeffeebdaed | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Clicking the link will open a page in your browser that runs you through Tailscale’s authentication flow, after which you should be able to curl the page directly from any of your devices (assuming you’re not doing anything complicated with ACLs that might prevent it)! | 1 2 3 4 5 6 7 8 | bash ❯ tailscale status # ... 100.93.165.28 kara jnsgruk@ linux - 100.106.82.10 tsnet-test jnsgruk@ linux - # ... ❯ curl http://tsnet-test:8080 <html><body><h1>Hello from tsnet-test, tailnet!</h1> | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | The library has a pretty small API surface, all of which is documented on pkg.go.dev. ## Libations # For my cocktail app, I wanted to employ a similar, albeit simplified, set of techniques that I use to build this blog. I love Go’s ability to embed static files that can be served as web assets. ### Recipe Schema # I wanted to represent recipes in a format that could be updated by hand if necessary, and easily parsed into a web frontend. I decided to use JSON for this, representing the recipes as a list: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | json [ { "id": 10, "name": "New York Sour", "base": ["Bourbon"], "glass": ["12oz Lowball"], "method": ["Dry Shake", "Shake"], "ice": ["Cubed"], "ingredients": [ { "name": "Lemon Juice", "measure": "20", "unit": "ml" }, { "name": "Sugar", "measure": "20", "unit": "ml" }, { "name": "Red Wine", "measure": "10", "unit": "ml" }, { "name": "Bourbon", "measure": "40", "unit": "ml" }, { "name": "Egg White", "measure": "20", "unit": "ml" } ], "garnish": ["Lemon Sail"], "notes": "Use claret or malbec" } ] | | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | This schema is able to capture all the relevant details from the different formats I’ve seen over the years. It would take some time to format my favourites into this schema, but that was always going to be the case. I was fortunate enough to get access to the recipe collection from a well regarded cocktail bar in the UK. Unfortunately it was given to me in a hard-to-parse PDF, which resulted in many hours of playing with OCR tools and manual data cleaning - but enabled me to bootstrap the app with around 450 high quality recipes. I didn’t include their recipes in the libations repository, but I did include some of my own favourite concoctions in a sample recipe file. My Mezcal Margarita gets pretty good reviews 😉. ### Server # The server implementation needed to fulfil a few requirements: - Parse a specific recipes file, optionally passed via the command line - Have an embedded filesystem to contain static assets and templates - Be able to render HTML templates with the given recipes - Listen on either a tailnet (via tsnet), or locally (for testing convenience) - When listening on the tailnet, listen on HTTPS, redirecting HTTP traffic accordingly I wanted to keep dependencies to a minimum to make things easier to maintain over time. The tsnet library pulls in a few indirect dependencies, but everything else Libations uses is in the Go standard library. The recipes JSON schema is very simple, and is modelled with a couple of Go structs: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | go // Ingredient represents the name and quantity of a given ingredient in a recipe. type Ingredient struct { Name string Measure string Unit string } // Drink represents all of the details for a given drink. type Drink struct { ID int Name string Base []string Glass []string Method []string Ice []string Ingredients []Ingredient Garnish []string Notes string } | | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | The parseRecipes function checks whether or not the user passed the path to a specific recipe file, or whether it should default to parsing the sample recipes file. Once it’s determined the right file to parse, and validated its existence, it unmarshals the JSON using the Go standard library. Users have the option of passing the -local flag when starting Libations, which bypasses tsnet completely and starts a local HTTP listener on the specific port. This makes for easier testing when iterating through changes to the web UI and other elements: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | go // ... addr := flag.String("addr", ":8080", "the address to listen on in the case of a local listener") local := flag.Bool("local", false, "start on local addr; don't attach to a tailnet") // ... var listener *net.Listener if *local { listener, err = localListener(*addr) } else { listener, err = tailscaleListener(*hostname, *tsnetLogs) } if err != nil { slog.Error("failed to create listener", "error", err.Error()) os.Exit(1) } //... | | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Setting up the tsnet server and listener is only mildly more complicated – but mostly due to my requirement that all HTTP traffic is redirected to HTTPS, using the LetsEncrypt certificates that Tailscale provides automatically. The redirects are handled by a separate Goroutine in this case: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | go // Start a standard HTTP server in the background to redirect HTTP -> HTTPS. go func() { httpLn, err := tsnetServer.Listen("tcp", ":80") if err != nil { slog.Error("unable to start HTTP listener, redirects from http->https will not work") return } slog.Info(fmt.Sprintf("started HTTP listener with tsnet at %s:80", hostname)) err = http.Serve(httpLn, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { newURL := fmt.Sprintf("https://%s%s", r.Host, r.RequestURI) http.Redirect(w, r, newURL, http.StatusMovedPermanently) })) if err != nil { slog.Error("unable to start http server, redirects from http->https will not work") } }() | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | With the correct listener selected, I create an http.ServeMux to handle routing to static assets and rendering templates, and pass that mux to the http.Serve method from the Go standard library - and that’s it! At the time of writing the Go code totals 235 lines - not bad! ### Web Interface # The web interface was designed primarily for mobile devices, and I’ve not yet done the work to make it excellent for larger-screened devices - though it’s certainly bearable. It’s also read-only at the moment: you can browse all the recipes, and there is a simple full-text search which can narrow the list of recipes down by searching for an ingredient, method, glass type, notes, etc. As mentioned in an earlier post, I’m a big fan of the Vanilla Framework, which is a “simple, extensible CSS framework” from Canonical, and is used for all of Canonical’s apps and websites. Given that I had some prior experience using it, I decided to use it again here. I started using my tried and tested recipe of Vanilla + Hugo, but later reverted to using simple HTML templates with Go’s html/template package. The result is a set of templates, which iterate over the recipe data from the JSON file, and output nicely styled HTML elements: screenshot of the libations app displaying the recipe for a mezcal margarita There is nothing fancy going on here - it’s nearly all stock Vanilla Framework. I do specify some overrides to make the colours a bit less Ubuntu-ish, but that’s it! One detail I’m pleased with is the dynamic drink icons. The icons indicate the type of glass the particular drink should be served in. This is a simple trick: for each drink the HTML template renders a glass-icon partial, which reads the glass type specified in the recipe, and renders the appropriate SVG file which is then coloured with CSS. ## Packaging for NixOS # There were two main tasks in this category: creating the Nix package itself, and writing a simple NixOS module that would make it simple for me to run it on my NixOS server. The project uses a Flake to provide the package, overlay and module. The standard library in Nix has good tooling for Go applications now, meaning the derivation is short: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | nix { buildGo122Module, lastModifiedDate, lib, ... }: let version = builtins.substring 0 8 lastModifiedDate; in buildGo122Module { pname = "libations"; inherit version; src = lib.cleanSource ../.; vendorHash = "sha256-AWvaHyJL7Cm+zCY/vTuTAsgLbVy6WUNfmaGbyQOzMMQ="; } | | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | I haven’t cut any versioned releases of Libations at the time of writing - I’m using the last modified date of the flake to version the binaries. The module starts the application with systemd, and optionally provides it with a recipes file. There are four options defined at the time of writing: services.libations.{enable,recipesFile,tailscaleKeyFile,package}: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | nix options = { services.libations = { enable = mkEnableOption "Enables the libations service"; recipesFile = mkOption { type = nullOr path; default = null; example = "/var/lib/libations/recipes.json"; description = '' A file containing drinks recipes per the Libations file format. See https://github.com/jnsgruk/libations. ''; }; tailscaleKeyFile = mkOption { type = nullOr path; default = null; example = "/run/agenix/libations-tsauthkey"; description = '' A file containing a key for Libations to join a Tailscale network. See https://tailscale.com/kb/1085/auth-keys/. ''; }; package = mkPackageOption pkgs "libations" { }; }; }; | | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | The tailscaleKeyFile option enables the service to automatically join a tailnet using an API key, rather than prompting the user to click a link and authorise manually. These options are translated into a simple systemd unit: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | nix config = mkIf cfg.enable { systemd.services.libations = { description = "Libations cocktail recipe viewer"; wantedBy = [ "multi-user.target" ]; after = [ "network.target" ]; environment = { "XDG_CONFIG_HOME" = "/var/lib/libations/"; }; serviceConfig = { DynamicUser = true; ExecStart = "${cfg.package}/bin/libations -recipes-file ${cfg.recipesFile}"; Restart = "always"; EnvironmentFile = cfg.tailscaleKeyFile; StateDirectory = "libations"; StateDirectoryMode = "0750"; }; }; } | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | The XDG_CONFIG_HOME variable is set so that tsnet stores it’s state in /var/lib/libations, rather than trying to store it in the home directory of the dynamically created user for the systemd unit. I use agenix on my NixOS machines to manage encrypted secrets, and for this project I used it to encrypt both the initial Tailscale auth key, and my super-secret recipe collection! The configuration to provide the secrets and configure the server to run libations is available on Github, but looks like so: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | nix { config, self, ... }: { age.secrets = { libations-auth-key = { file = "${self}/secrets/thor-libations-tskey.age"; owner = "root"; group = "root"; mode = "400"; }; libations-recipes = { file = "${self}/secrets/thor-libations-recipes.age"; owner = "root"; group = "root"; mode = "444"; }; }; services.libations = { enable = true; recipesFile = config.age.secrets.libations-recipes.path; tailscaleKeyFile = config.age.secrets.libations-auth-key.path; }; } | | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | As a result, the application is now available at https://libations, with a valid LetsEncrypt certificate, on all of my machines! 🎉 ## Summary # This was a really fun project. It felt like a fun way to explore tsnet, and resulted in something that I’ve used a lot over the past year. I don’t have many plans to adjust things in the near future - though I do find myself wanting a nice interface to add new recipes from time to time. And now for the twist: three weeks ago I gave up drinking alcohol (likely for good), so now I’m on a mission to find some non-alcoholic recipes to make life a little tastier! I suspect this will be hard work - and I’ll certainly miss some of my favourites, but my wife and I have already found some compelling alternatives. If you’ve got a favourite recipe (alcoholic or not) and you liked the article, then perhaps open a PR and add it to the sample recipes file!BLOCKCHAIN AND DISTRIBUTED LEDGERS
Integration testing with NixOS in Github Actions
## Introduction # While in my own time I’ve tended toward NixOS over the past 18 months, in my day-to-day work for Canonical I’m required to interact with a fair few of our products - and particularly build tools. I frequently need to use some combination of Snaps, Charms and Rocks. Each of these have their own “craft” build tools (
snapcraft, charmcraft and rockcraft), which are distributed exclusively as Snap packages and thus a little tricky to consume from NixOS. ## The Problem # Packaging the tools for Nix was a little repetitive, but not particularly difficult. They’re all built with Python, and share a common set of libraries. Testing that the packages were working correctly (i.e. could actually build software) on NixOS using the NixOS version of LXD in Github Actions proved more difficult. Github Actions defaults to Ubuntu as the operating system for its runners - an entirely sensible choice, but not one that was going to help me test packages could work together on NixOS. I could have hosted my own Github Actions runners to solve the problem, but I didn’t want to maintain such a deployment. For a while I relied on just testing each of the crafts locally before pushing, and the CI simply installed the Nix package manager on the runners (using the excellent Nix installer from Determinate Systems) and ensured that the build could succeed, but this left a lot to be desired - particularly when I accidentally (and somewhat inevitably) broke one of the packages. ## KVM for Github Actions # Some time later I came across this post on the Github Blog, stating the following: > Starting on February 23, 2023, Actions users […] will be able to make use of hardware acceleration […]. What follows is an example of a relatively simple addition to a Github Workflow to enable KVM on Github Actions runners: | 1 2 3 4 5 | yaml - name: Enable KVM group perms run: | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules sudo udevadm control --reload-rules sudo udevadm trigger --name-match=kvm | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Given the ability to relatively easily create NixOS VMs from a machine configuration, this should enable me to run a NixOS VM inside my Github Actions runners, and use that VM to run end to end tests of my craft packages. After some quick tests, I confirmed that the above snippet worked just fine on the freely available runners that are assigned to public projects. After tooting excitedly about this, it was also picked up by the folks at Determinate Systems who promptly added support for this in their Nix install Github Action - enabling the feature by default. ## Building VMs with Nix # A really nice feature of NixOS that I discovered relatively late, is that given a NixOS machine configuration it’s trivial to build a virtual machine image for that configuration. This has the nice property that one can actually boot a VM-equivalent of any previously defined machines. You could, for example, boot a VM-equivalent of my laptop with the following command: | 1 | bash nix run github:jnsgruk/nixos-config#nixosConfigurations.freyja.config.system.build.vm | | --------- | ------------------------------------------------------------------------------------------------- | In order to test my craft tools, I needed a relatively simple NixOS VM that had LXD enabled, and my craft tools installed. My test VM configuration looks like this: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | nix { modulesPath, flake, pkgs, ... }: { # A nice helper that handles creating the VM launch script, which in turn # ensures the disk image is created as required, and QEMU is launched # with sensible parameters. imports = [ "${modulesPath}/virtualisation/qemu-vm.nix" ]; # Define the version of NixOS and the architecture. system.stateVersion = "23.11"; nixpkgs.hostPlatform = "x86_64-linux"; # This overlay is provided by the crafts-flake, and ensures that # 'pkgs.snapcraft', 'pkgs.charmcraft', 'pkgs.rockcraft' all resolve to # the packages in the flake. nixpkgs.overlays = [ flake.outputs.overlay ]; # These values are tuned such that the VM performs on Github Actions runners. virtualisation = { forwardPorts = [{ from = "host"; host.port = 2222; guest.port = 22; }]; cores = 2; memorySize = 5120; diskSize = 10240; }; # Configure the root user without password and enable SSH. # This VM will only ever be used in short-lived testing environments with # no inbound networking permitted, so there is minimal (if any) risk. # If you put this VM on the internet, you can keep the pieces! :) networking.firewall.enable = false; services.openssh.enable = true; services.openssh.settings.PermitRootLogin = "yes"; users.extraUsers.root.password = "password"; # Ensure that LXD is installed, and started on boot. virtualisation.lxd.enable = true; # Include the `craft-test` script, ensuring the craft apps are installed # and included in its PATH. environment.systemPackages = [ (pkgs.writeShellApplication { name = "craft-test"; runtimeInputs = with pkgs; [ unixtools.xxd git snapcraft charmcraft rockcraft ]; text = builtins.readFile ./craft-test; }) ]; } | | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Anybody can build and launch this VM trivially: | 1 | bash nix run github:jnsgruk/crafts-flake#testVM | | --------- | ------------------------------------------------------ | ## Writing a Github workflow # All the building blocks are in place! I wanted to keep the actual workflow definition for the tests as clean and understandable as possible, so I put together the craft-test script as a small helper which automates the building of real artefacts. An example invocation might be: | 1 | bash bash craft-test snapcraft | | --------- | ------------------------------------- | On each invocation, the script creates temporary directory, clones some representative build files for the selected craft tool, and launches the craft. The repos it uses for the representative packages are hard-coded for each craft for now. I wrote one more small helper script to simplify connecting to the VM with the required parameters. It’s a wrapper around ssh and sshpass that’s hard-coded with the credentials of the test VM (don’t @ me!), and executes commands over SSH in the test VM. Using this script, one can bash vm-exec -- craft-test snapcraft and the craft-test script will be executed over SSH in the VM. With all that said and done, the resulting workflow is pleasingly simple: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | yaml # ... jobs: test: runs-on: ubuntu-latest strategy: matrix: package: ["charmcraft", "rockcraft", "snapcraft"] steps: - name: Checkout flake uses: actions/checkout@v4 - name: Install nix uses: DeterminateSystems/nix-installer-action@v9 - name: Build and run the test VM run: | nix run .#testVm -- -daemonize -display none - name: Test ${{ matrix.package }} run: | nix run .#testVmExec -- craft-test ${{ matrix.package }} | | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | A separate job is run for each of the crafts, and a real artefact is built in each, giving reasonable confidence that the consumers of my flake will be successful when building snaps, rocks and charms natively on NixOS. A successful run can be seen here. ## Summary # In this article we’ve covered: - Enabling KVM on Github Runners - Building NixOS VMs using Flakes - Booting NixOS VMs in Github Actions If you’d like to build snaps, rocks or charms and you’re running NixOS, you can run the tools individually from my flake: | 1 2 3 4 5 6 7 8 | bash # Run charmcraft nix run github:jnsgruk/crafts-flake#charmcraft # Run rockcraft nix run github:jnsgruk/crafts-flake#rockcraft # Run snapcraft nix run github:jnsgruk/crafts-flake#snapcraft | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | Or you can check out the README for instructions on how to integrate into your Nix config using overlays! That’s all for now! 🤓CANONICAL