Automate Python Code Protection in GitHub Actions with uv
Every release, someone on the team has to remember to run the protection build. It’s not in the workflow, it’s not in the checklist above the fold, and it produces a different artifact than the one everyone tested. So it gets skipped on a hotfix, done inconsistently on a Friday, or run with a stale command that omits --library and quietly ships the wrong thing.
That’s a process problem, not a compiler problem. Py2Native already compiles plain Python into native machine code with no Cython syntax, no .pyx files to write by hand, and no manual cythonize step — which means nothing about it fights automation. The only reason the step stays manual is that nobody moved it.
This article moves it. By the end you’ll have a GitHub Actions workflow that turns a tag push into a compiled, protected wheel on Linux, Windows, and macOS — using uv run py2native and version-pinned tooling. If you want the compilation fundamentals first, read Compile Plain Python to Native Code Without Rewriting in C; here we only care about the pipeline.
One-Time Setup: Prepare Your Repo and Workflow for uv run py2native
1. Add the compiler as a dev dependency
uv add --dev py2native
git add pyproject.toml uv.lock
git commit -m "chore: add py2native dev dependency"
Commit the lockfile. This is the single most effective reproducibility lever you have: the same uv sync --frozen produces the same compiler version on every runner, forever.
2. Prove the build works locally
uv run py2native build main.py "*.py" --wheel dist --library
Two flags worth understanding before you wire them into CI:
--libraryproduces a shared library (.pyd/.so/.dylib) instead of an executable.--wheel distpackages that library as a PEP 427 wheel indist/, including the generated__init__.py(the meta-path finder that redirectsimport mypkg.submoduleinto the shared library) and__main__.py(sopython -m mypkgstill works). Both are required; the wheel builder generates them.
Quote the glob ("*.py") on Windows. Py2Native expands glob patterns itself under --base, so quoting lets the compiler do the expansion instead of PowerShell, and the command stays identical across all three runners. If you’d rather ship a runnable directory than a wheel, --embed <dir> creates a uv-managed deployment directory instead.
3. Know what the hosted runners already give you
Py2Native needs a platform C compiler and linker — MSVC on Windows, GCC on Linux, Clang on macOS. GitHub-hosted runners include all three. Your matrix is therefore just an OS list:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
fail-fast: false matters here: if Windows linking breaks you still want the Linux and macOS artifacts, and you want all three failures visible in one run rather than one at a time.
4. Optional: the Pro plugin for license enforcement
If you ship signed licenses, add the closed-source plugin and generate a keypair once, locally:
uv add --dev py2nativepro
uv run py2native keygen private.pem public.pem
uv run py2native sign --private private.pem payload.json license.dat
Store the signed license.dat contents as a repository secret named PY2NATIVE_LICENSE. Commit nothing else: keep private.pem offline, and store only public.pem wherever you need to inspect claims. The plugin embeds the public key and the ES256 verification code into the executable at build time — the private key never touches CI.
The Automated Pipeline: A GitHub Actions Workflow That Compiles on Every Release
Here’s the complete workflow. Save it as .github/workflows/protect.yml.
name: protect
on:
push:
tags:
- "v*"
permissions:
contents: write
jobs:
build:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
with:
enable-cache: true
- name: Sync environment
run: uv sync --frozen
- name: Compile plain Python to native
run: uv run py2native build main.py "*.py" --library --wheel dist
- name: Smoke test the compiled wheel
shell: bash
run: |
uv pip install dist/*.whl
uv run python -c "import mypkg; print(mypkg.__name__)"
- uses: actions/upload-artifact@v4
with:
name: wheel-${{ matrix.os }}
path: dist/*.whl
if-no-files-found: error
release:
needs: build
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/download-artifact@v4
with:
pattern: wheel-*
merge-multiple: true
path: dist
- uses: softprops/action-gh-release@v2
with:
files: dist/*.whl
A few things to notice:
astral-sh/setup-uvplusenable-cache: truegives you a cached uv binary and dependency cache for free.uv sync --frozeninstalls exactly what’s inuv.lockand fails rather than silently resolving something new.if-no-files-found: erroris the cheapest possible guard against a build that “succeeds” while producing nothing.- The
releasejob is gated onbuild. Withenvironment: productionconfigured to require reviewers, a tag push compiles everywhere but waits for a human before publishing.
Adding the Pro license gate
For Pro builds, write the secret to a file first — --license takes a path, not a token — and pass --public if you want the build to verify against a specific public key:
- name: Compile with license verification
shell: bash
env:
P2N_LICENSE: ${{ secrets.PY2NATIVE_LICENSE }}
run: |
printf '%s' "$P2N_LICENSE" > license.dat
uv run py2native build main.py "*.py" --library --wheel dist \
--license license.dat \
--public public.pem
shell: bash isn’t cosmetic — it makes that step identical on all three runners instead of forking into PowerShell on Windows.
The plugin bakes the signature verification code and the public key into the executable. Your code supplies the declaration and calls the verifier. Add the .pxd file next to your package so the compiled module can bind to the baked-in runtime:
# src/mypkg/_p2n_bootstrap.pxd
cdef _runtime_verify_es256_jwt(token, expected_iss=*, expected_aud=*)
Then cimport it in the license gate — the one file where you drop below plain Python — and call it with the license string:
# src/mypkg/_gate.pyx
from _p2n_bootstrap cimport _runtime_verify_es256_jwt
def check(licenseString):
license = _runtime_verify_es256_jwt(licenseString, expected_iss="RSJ Software GmbH", expected_aud="TimestampGIT")
return license
The elliptic-curve verification itself runs in compiled code inside the plugin’s runtime — no third-party crypto library is linked in, and only the public key ships. Full walkthrough of the claims, the signing payload, and how to surface a rejected license gracefully: Verify a Signed License Key Inside a Compiled Python Executable.
Monitoring and Failure Handling: Keep the Pipeline Honest
A protection build that fails silently is worse than a manual step, because everyone assumes it ran.
Fail loudly, at the job level. The release job doesn’t run when build fails, so an unprotected artifact can never reach a GitHub Release. Add a notification step so you find out in minutes rather than at the next tag:
- name: Notify on failure
if: failure()
uses: slackapi/slack-github-action@v2
with:
webhook: ${{ secrets.SLACK_WEBHOOK }}
webhook-type: incoming-webhook
payload: |
{"text": "Protection build failed on ${{ matrix.os }} for ${{ github.ref_name }}"}
Smoke test before you publish. Importing the wheel catches missing modules, unresolved symbols, and a wheel that installed but exports nothing. Running python -m mypkg --help covers the __main__.py path too. Both are seconds of runtime and catch the majority of link-time regressions.
Expect platform-specific error shapes and read them for what they are:
- Windows —
.pydnaming and MSVC linker errors (LNK2001unresolved externals usually mean the CPython shared library wasn’t located;runtime.pyhandles that lookup, but a mismatched Python version in the venv will break it). - Linux —
auditwheel repairruns during wheel creation; a manylinux compliance failure shows up as a missing or non-whitelisted shared object. If you need a specific manylinux tag, that failure text names the offending library. - macOS — Mach-O linking against
.dylib; architecture mismatches on ARM64 runners surface as “building for macOS-arm64 but attempting to link with file built for macOS-x86_64.”
Because the matrix uses fail-fast: false, all three logs land in the same run — compare them side by side instead of re-running CI three times to see each platform.
Debugging a Pro rejection safely. If a license check fails, dump the claims in a debug step rather than guessing:
uv run py2native show --public public.pem license.dat
That prints the JWT claims and optionally verifies the signature against the public key. Run it in a workflow_dispatch debug job with a short-lived artifact — never in a production step, because claims end up in logs that outlive the build.
Best Practices for Automated Python Code Protection
- Pin both tools. Pin the Py2Native version in
uv.lockand pin the setup action (astral-sh/setup-uv@v5) rather than trackingmain. A compiler upgrade should be a reviewed pull request, not a surprise on release day. - Upload only compiled output.
path: dist/*.whl,path: dist/*.so,path: dist/*.pyd, or the--embeddirectory. Neverpath: .— that’s how yoursrc/tree ends up in a public artifact and the entire exercise becomes theatre. - Separate build from release. Build in one job, publish in another gated by
needs:and a protectedenvironment. Manual approval on production releases costs one click and prevents a compromised tag from shipping. - Cache what’s expensive. The uv cache and, if you’re building many times a day, the pristine Python venv Py2Native uses for compilation.
enable-cache: trueon setup-uv covers the first; caching the pristine venv directory across runs covers the second. - Respect the two known constraints. Module names must be unique across your source files — two
utils.pyin different directories will collide. And__init__.pyis skipped during compilation because it’s a namespace marker, not compilable code, so don’t put logic there. In library mode,__main__.pyis excluded from sources because the wheel builder generates it. - Don’t over-promise. Third-party libraries stay as Python source, and monkey-patching remains possible. If you have LGPL dependencies, they stay replaceable by the end user for compliance. Compiling your own code is the protection boundary — see Cython vs Nuitka vs Py2Native for where that boundary sits relative to alternatives.
FAQ
Can I run Py2Native on GitHub-hosted runners without installing a C compiler?
Yes. GitHub-hosted runners for Ubuntu, Windows, and macOS already include the required C compilers (GCC, MSVC, Clang). You only need to set up uv and run uv run py2native build; no extra compiler installation is required.
How do I keep my Pro license key secret in GitHub Actions?
Store the license JWT as a repository secret (e.g. PY2NATIVE_LICENSE) and pass it to the build step as --license license.dat after writing the secret to that file. Never commit the private key; only the public key is embedded in the executable by the Pro plugin.
Does the automated build work for library mode and wheels?
Yes. The same workflow can use --library to produce a shared library and --wheel to package it as a PEP 427 wheel. The wheel includes the compiled .pyd/.so plus the required __init__.py and __main__.py, so you can upload it as a release artifact.
What happens if the protection step fails mid-release?
The GitHub Actions job fails and the release is not published if you gate the release job on the build job. Add a smoke test step to catch import or linking errors early, and configure notifications so the team is alerted immediately.
Conclusion
The manual protection build survives for exactly one reason: it lives outside the thing that runs on every release. Move it into the workflow and it stops being a memory test and starts being a property of your artifact — same compiler version, same flags, three platforms, every tag.
Py2Native is the piece that makes this short. You write plain Python, add uv run py2native as a dev dependency, and the workflow does the rest: Cython is invoked for you, no .pyx files to author, no build config to hand-tune for third-party libraries. Start with uv add --dev py2native, get one green run locally, then paste the workflow above and tag a release. Full CLI and runtime reference lives at py2native.dev.
Related posts
- Compile Plain Python to Native Code Without Rewriting in C
- Verify a Signed License Key Inside a Compiled Python Executable
- Compile a Python Script to a Native Executable Without PyInstaller