Automating mdtool Updates with GitLab

A walkthrough of Renovate, Codex and protected GitLab CI

1. How it started

I started with a recurring check for mdtool, my Go tool for turning Markdown and templates into documents. The check ran through Codex on my machine. Once I had tried it a few times, I wanted GitLab to handle the routine parts. It already had the runners that built the CLI, the packages and the container image. A scheduled pipeline could pick up updates while my machine was off, and I could still start one myself.

The first Renovate merge request showed why opening a merge request was the easy part. It bumped golang.org/x/net. The Go tests passed, but govulncheck found an advisory in github.com/gobwas/ws, a different dependency that was already on master. The compatible pin went into the same merge request and the full pipeline passed. The merge still needed a manual step, and the existing release pipeline published v1.0.2. The merge request · The v1.0.2 release

So what should GitLab do on its own?

I ended up with three decisions. Renovate decides which dependency update to propose. The merge job decides whether the tested commit is safe to merge under the rules I set. The release job decides if the result fixes something that users can already download.

Renovate opens a merge request. Passing CI goes through a protected merge check. Failed CI can get a Codex proposal. A validated patch returns to CI on the same branch. A rejected patch leaves the merge request open.
A repair changes the commit, so the merge request goes through CI again.

2. The private pilot and the Codex login

I ran the first real repair from a separate, private GitLab project. The merge request and its normal CI stayed in the public mdtool repository. I sent the private job evidence from the failed revision, including the Go scan and the relevant diffs. Codex produced a patch for the vulnerable gobwas/ws pin. I coordinated that handoff by hand, checked the proposed checksums upstream and used a separate writer to apply the patch to the same public branch. Both required jobs ran there again. I could test the repair before giving GitLab responsibility for the whole handoff. The public CI run after the pilot repair

I wanted CI to use my Codex subscription while my Mac was off. I signed in with a dedicated ChatGPT session using the device flow in a disposable container on the runner host. The first attempt failed over HTTPS. The host and Node could reach the endpoint, but the slim Codex image lacked the system CA bundle the CLI needed. Mounting that bundle read-only got the CLI to the device prompt.

The login state went into an owner-only directory mounted by the protected Codex runner as its CODEX_HOME. That mount had to be writable so the CLI could refresh the session. I tested the job with a harmless marker before installing the real login and checked that the other jobs could see neither the auth mount nor the host Docker socket. The review wrapper still starts Codex in a disposable working directory with a minimal environment. The subscription session stays with that runner, and GitLab write credentials stay with the jobs that use them. Review wrapper

How the mount is wired. Below are the relevant Docker executor settings, simplified with placeholder host paths. The same unprivileged job user owns the login file, which is readable and writable only by its owner. The CLI uses file-backed auth under CODEX_HOME and gets a separate, temporary HOME. This keeps login refresh across jobs while the review workspace and output files can be discarded. The read-only model sandbox and the writable CLI auth directory serve different purposes.

[runners.docker]
  privileged = false
  services_limit = 0
  volumes = [
    "/runner-owned/codex-auth:/codex-auth:rw",
    "/runner-owned/ca-certificates.crt:/etc/ssl/certs/ca-certificates.crt:ro",
  ]

The path on the right of the first bind is the one used by the review wrapper. Keeping the CA mount read-only was enough to fix HTTPS. The login state never travelled through a GitLab artifact.

3. Giving each runner just enough access

The old shared runner passed the host Docker socket into build jobs. That was convenient for a multi-architecture image build, but it gave those jobs access to the same daemon that managed other containers. Adding a runner with a live login made that arrangement untenable. I split the jobs across three runner roles.

  • Plain runner. Go checks and maintenance tooling run as unprivileged jobs without the host socket or the Codex auth mount. GitLab only supplies a writer credential to the protected job environment that needs it.
  • Build runner. Release verification talks to an isolated rootless Docker-in-Docker service. The runner-side guard checks the pinned service image, its user and its network. The image allowlist alone was insufficient because a job could also specify the service user. Rootless runs Docker inside that service as a non-root user, even though the pinned service itself needs outer container privileges. I verified that a request with another UID was rejected and that the real build still produced amd64 and arm64 images.
  • Codex runner. A tagged, project-locked runner accepts only protected refs and carries the subscription mount. The review job strips the GitLab job token from the environment it passes to the wrapper. The wrapper checks the runner and ref before it starts the model. Runner checks in CI · Protected review job

The rootless canary did not start on the first try. The runner host was itself a Linux container. The nested daemon needed subordinate UID and GID mappings and access to the TUN device for its network. After fixing those host settings, the two-platform canary passed. Rootless build canary

Changing the Docker endpoint also meant rechecking how Buildx worked. The existing build relied on the default docker driver with the containerd image store for multi-architecture output. I made the CI job check for rootless mode, that image store and the expected driver before starting GoReleaser. The snapshot then verified that the harder runner boundary still let the release build do its job. Multi-architecture snapshot pipeline

The release job starts by rejecting a job-visible host socket. It then waits for the DinD service and checks which daemon and builder it actually reached. Build preflight

test ! -S /var/run/docker.sock
for attempt in $(seq 1 45); do
  if docker info >/dev/null 2>&1; then break; fi
  sleep 1
done
docker info --format '{{json .SecurityOptions}} {{json .DriverStatus}}' > /tmp/docker-info
grep -q 'name=rootless' /tmp/docker-info
grep -q 'io.containerd.snapshotter.v1' /tmp/docker-info
docker buildx inspect default --bootstrap > /tmp/buildx-info
grep -Eq '^Driver:[[:space:]]+docker$' /tmp/buildx-info

A successful docker info on its own would only tell me that some daemon is reachable. The remaining checks keep the build tied to rootless mode, the containerd image store and the default Buildx driver. That matters if a runner gets reconfigured or an older runner picks up a build.

4. One project, several GitLab pipelines

The entry point is a pipeline input. The daily schedule selects maintenance, and I can select the same mode from Run pipeline. GitLab checks that the request targets the protected default branch and comes from a schedule, the web UI or the API. Here is the part of .gitlab-ci.yml that exposes the mode. Pipeline configuration

spec:
  inputs:
    mode:
      default: default
      options: [default, maintenance]
---
include:
  - local: .gitlab/maintenance.yml

variables:
  MDTOOL_MODE: $[[ inputs.mode ]]

For now I let Renovate propose minor and patch updates to Go requirements. It opens the merge request, runs go mod tidy as part of the update and leaves the merge to GitLab. In parallel, the maintenance run scans the published binaries and both container architectures. This also works on days when Renovate has nothing to propose. Renovate configuration · A scheduled run

What Renovate is allowed to propose. I reduced its config here to the part that controls cadence and the Go module manager. A routine version must have a known timestamp and be at least 24 hours old. Renovate’s vulnerability alerts have separate capacity and bypass the age filter at discovery. That gets an advisory into review sooner. The protected merge and publication checks still decide what can advance. Renovate settings

{
  "enabledManagers": ["gomod"],
  "automerge": false,
  "prConcurrentLimit": 1,
  "osvVulnerabilityAlerts": true,
  "vulnerabilityAlerts": {
    "prConcurrentLimit": 1,
    "branchConcurrentLimit": 1,
    "minimumReleaseAge": null
  },
  "minimumReleaseAge": "24 hours",
  "minimumReleaseAgeBehaviour": "timestamp-required",
  "postUpdateOptions": ["gomodTidy"]
}

The private project worked for the pilot, but I wanted to follow a repair from the mdtool merge request without a separate controller polling GitLab. A same-project CI bridge failed in the test with invalid_bridge_trigger. A shell job calling the trigger API reached the protected branch when I ran it as Owner, but the same test failed as the Renovate bot, which only had Developer access. I proved a temporary relay could dispatch the request, then replaced it with GitLab’s push webhook.

In the public mdtool project, after merge-request CI fails, the Developer bot’s notifier uses its short-lived job token to push a temporary request ref. A GitLab webhook uses a Maintainer-owned trigger token to start a protected pipeline on the default branch. Prepare, review and apply run there, and an accepted patch starts fresh merge-request CI.
The webhook crosses the protected-branch boundary. The merge-request job only signals that there is work to check.

The notifier has only its short-lived CI_JOB_TOKEN for that push. It creates a temporary request ref named for the MR pipeline, pointing at the commit that was tested. GitLab sends the push event through a branch-filtered webhook whose Maintainer-owned trigger token is stored in the webhook configuration. That starts a second pipeline on the protected default branch. A job-token push does not start normal CI, which is useful here because the request ref only carries the signal. The later patch writer uses the Developer bot credential to update the actual merge-request branch and start normal CI there. The automatic merge uses a separate Maintainer-level credential scoped to its protected environment. Job-token push behavior · GitLab webhook triggers · Maintenance jobs

The first webhook test exposed a detail I had missed. The trigger target can overwrite the ordinary ref in the payload. I configured the webhook to preserve the original ref in a separate request_ref field. The protected prepare job checks that ref and reads the candidate SHA from after. It then checks GitLab for the bot-owned MR, current branch heads and actual job results. A green notification can arrive just before GitLab marks the pipeline successful, so that branch waits briefly for the result. A green candidate skips Codex. Stale requests, duplicate reviews of the same commit and branch deletions also stop before a model call. After the native handoff worked, I retired the private controller. Request validation and preparation

Here is the first check on the protected side. In this payload, before is the all-zero SHA for a newly created ref. requestId reads the source pipeline number from that ref. For example, refs/heads/repair-requests/123 identifies pipeline 123, and after identifies the exact commit the jobs tested. The validator still asks GitLab whether those two things belong to the current MR. Webhook request parser

export function parseRequest(raw) {
  if (typeof raw !== 'string' || Buffer.byteLength(raw) > 4096) return null;
  let payload;
  try {
    payload = JSON.parse(raw);
  } catch {
    return null;
  }
  if (payload?.object_kind !== 'push' || !sameId(payload.project_id, projectId) ||
      !sameId(payload.user_id, bot) || payload.before !== zero) return null;
  const request = {
    ref: payload.request_ref,
    pipeline: requestId(payload.request_ref),
    head: payload.after
  };
  return validRequest(request) ? request : null;
}

Inside that protected pipeline, prepare, review and apply are separate jobs. GitLab passes the plan and review through restricted job artifacts using needs:artifacts. The review job reads the plan. The writer checks the plan and the review together before it can push. Artifact handoff

In the YAML, the apply job depends on both producers. The protected rule controls where the job can run. The resource group serializes writers that can touch the same repository state. Neither condition is inferred from a successful response by Codex. Apply job

apply-maintenance-repair:
  extends: .maintenance-writer
  stage: maintenance-apply
  resource_group: mdtool-repair-writer
  rules: *protected-repair
  needs:
    - job: prepare-maintenance-repair
      artifacts: true
    - job: review-maintenance-repair
      artifacts: true
  script:
    - node ci/maintenance/workflow.mjs apply

5. Preparing the prompt and checking the patch

I gave Codex the exact MR diff, current Go pins, short diagnostics from the failing jobs and the checksums for fixes the prepare job could verify upstream. The inputs are bounded. A diff or build log can contain arbitrary text, so the prompt explicitly treats both as evidence. Codex runs in a read-only sandbox with shell tools and web search disabled for this job. It returns JSON with a decision, a summary and a patch field. Prompt and output schema

The prompt in brief. Return accept if the evidence requires no change, fix with a minimal unified diff for a concrete failure, or hold when the evidence runs out. Keep the checks enabled, use verified checksums and report only what the evidence supports.

Set the execution boundary. The prompt and the CLI settings have different jobs. The prompt says how to interpret the diff and what to return. The wrapper passes it on standard input, disables the tools we do not need and gives the CLI a schema and a file to write. This excerpt omits the call options around the process. Codex invocation

execFileSync('codex', [
  '-a', 'never', '--disable', 'shell_tool', '--disable', 'unified_exec',
  '-c', 'web_search="disabled"', '-c', 'cli_auth_credentials_store="file"',
  'exec', '--skip-git-repo-check', '--ephemeral', '--sandbox', 'read-only',
  '--output-schema', schema, '-o', output, '-',
], { /* working directory, minimal environment, and prompt */ });

Validate the shape first. The CLI writes a JSON result constrained by a schema. This additional check enforces a rule the shape alone does not express. Only fix may have a non-empty patch. If the model says hold and also supplies a diff, the wrapper rejects the result instead of leaving the writer to interpret it. Result validation

export function checkReview(result) {
  if (!['accept', 'fix', 'hold'].includes(result?.decision) ||
      typeof result.summary !== 'string' || !result.summary.trim() ||
      result.summary.length > 4000 ||
      typeof result.patch !== 'string' || result.patch.length > 16000 ||
      Boolean(result.patch.trim()) !== (result.decision === 'fix')) {
    throw new Error('Codex returned an invalid review');
  }
  return result;
}

The writer checks the patch against the exact commit and only accepts changes to go.mod and go.sum. It verifies the proposed versions against the Go checksum database, then checks again that the MR and its CI results are still current. Each MR gets at most two attempts, recorded outside the pipeline so retrying a job cannot reset the budget. A disposable draft went through that entire loop and passed fresh CI on the repaired commit. The protected repair pipeline · Fresh CI on the repaired draft

Bind the write to the reviewed commit. The writer fetches the MR head, extracts just the two module files and validates the diff in a temporary directory. It builds the replacement commit without checking out the candidate tree. The earlier fetch verifies which files it started from. The lease below does the last comparison at push time. If Renovate rebased or someone pushed while Codex was working, Git refuses to replace the changed branch. The lease applies to the Renovate source branch. Patch application and push

// Keep the repaired MR at one commit directly on the verified target.
const commit = git(['commit-tree', tree, '-p', plan.target, '-m',
  'chore(deps): repair verified maintenance dependency pins']).trim();
if (!sha(commit) ||
    (await candidate(plan.iid, plan.request, plan.target, api))
      ?.mr.source_branch !== plan.branch) {
  throw new Error('MR source, target or checks changed before push');
}
git(['push', '--force-with-lease=' + ref + ':' + plan.head,
  '--', remote, commit + ':' + ref]);

The chromedp update was a good test of where to stop. It broke compilation in the Chromium renderer. Codex proposed rolling back the update, and the writer rejected that patch. The merge request stayed open with failed checks. A maintainer can now decide how to adapt the renderer or which version to use. This was a real run through the repair path, up to the point where the policy stopped it. The chromedp update · The protected repair pipeline

This is one of the checks in the writer. For a changed requirement, the new pin has to advance within the same major version and preserve Go’s +incompatible suffix if present. A rollback moves the version in the opposite direction. Patch validation

const oldSemver = parseVersion(oldVersion);
const newSemver = parseVersion(version);
if (!oldSemver || !newSemver || oldSemver.core[0] !== newSemver.core[0]
    || compareVersions(newSemver, oldSemver) <= 0
    || oldVersion.endsWith('+incompatible') !== version.endsWith('+incompatible')) {
    throw new Error('go.mod requires a same-major version advance for ' + name);
}

That failure also showed a gap between the prompt and the writer. The prompt asked for compatibility fixes in general, but the writer could only advance module pins. The renderer needed a source-code change or a different compatible update. A hold describes that situation better than a patch the writer cannot apply.

6. What a green merge request can authorize

I also ran into a case where my own policy was too strict. Renovate’s go mod tidy removed four indirect requirements from the chromedp candidate. A rule written for one version change per line rejected that shape. I reproduced the tidy result on the exact candidate using the pinned Go toolchain. The merge check now accepts verified tidy changes to indirect requirements and still rejects new direct dependencies, changes to module replacements and changes to existing checksum values. That fixed the false rejection. The renderer’s compile error still needed its own fix. Tidy qualification

Once the required jobs are green, the merge job checks their IDs and the tested source and target commits again. I enabled semi-linear merges, disabled automatic rebase and disabled force-pushing the default branch. That lets GitLab enforce the relationship the checks actually tested. The merge job saves an authenticated record of that decision, and the post-merge job checks that the resulting parents and tree match it. That’s the commit the release checks use. Merge and post-merge checks

This is the last check before calling GitLab’s merge API. Passing the source sha protects the source side of the request. The server’s semi-linear merge rule covers the target side, so a target update can require another rebase and fresh CI. The authenticated record lets the post-merge job verify both parents and the tree before moving on to release checks. Merge API call

const refreshed = await greenCandidate(plan.iid, plan.request, plan.target, api);
if (refreshed?.mr.source_branch !== plan.branch ||
    !sameChecks(current.checks, refreshed.checks)) return;
if (!await safeMergeSettings()) throw new Error('Server merge or branch protection changed');
const result = await api(mrPath(plan.iid) + '/merge', { method: 'PUT', body: {
  sha: plan.head, auto_merge: true, squash: false, should_remove_source_branch: true,
  merge_commit_message: 'Merge verified maintenance !' + plan.iid +
    ' from pipeline ' + record.pipeline + '/' + evidence,
} });
if (!['opened', 'merged'].includes(result.state))
  throw new Error('GitLab did not accept the maintenance merge');

7. When does this become a release?

One thing I liked about the existing pipeline was that it already built a GoReleaser snapshot. With --snapshot, CI can build the archives, packages and multi-architecture image using the release configuration without publishing a stable version. After a maintenance merge, verification runs again on the merged commit. Snapshot job

goreleaser release --snapshot --clean --skip=sign

For publication I compare what users can download today with the candidate, using the same scanner and database versions for both. A verified maintenance merge can lead to a patch release if its rebuilt CLI clears a vulnerability found in a shipped binary. A scheduled or on-demand maintenance run can refresh the container if it clears a fixable high or critical finding. That route keeps the CLI binaries and version unchanged, refreshes the existing image tag and preserves the previous digest. Both routes stop if the scan finds a new blocker or a blocking container finding remains. Staging job · Release decision code

The last part of the comparison shows how the two publication routes differ. A CLI patch needs the next patch number and a new commit. An image refresh pins the old version and checks every CLI binary hash. Both publishing routes require a new image digest, at least one eligible fix and no blocking image findings after the rebuild. With no eligible fix, the comparison falls back to the snapshot route. Release eligibility

const [, major, minor, patch] = stable.exec(published.version);
const patchVersion = 'v' + major + '.' + minor + '.' + (BigInt(patch) + 1n);
const sameBinaries = targets.every(target =>
  published.binary_hashes[target] === staged.binary_hashes[target]);
const desiredArtifacts = mode === 'cli-patch'
  ? staged.version === patchVersion && staged.commit !== published.commit
  : staged.version === published.version && sameBinaries;
const imageBlocking = after.filter(finding => finding.kind === 'oci' && finding.blocking);
const eligible = newBlocking.length === 0 && (mode === 'snapshot' ||
  (imageBlocking.length === 0 && fixes.length > 0 && desiredArtifacts &&
    published.image_digest !== staged.image_digest));
return { schema: 1, requested_mode: mode, route: eligible ? mode : 'snapshot', eligible,
  advisory: advisory ?? null, fixes, new_blocking: newBlocking,
  image_blocking: imageBlocking, databases, published, staged };
GitLab compares published artifacts with the candidate. A CLI fix that passes the checks qualifies for a signed patch release. A container-only fix that passes refreshes the same image tag. If the fix is missing or checks fail, GitLab publishes nothing.
The fix and the scan results determine what GitLab publishes.

For a qualifying release, the pipeline stages, signs and verifies the artifacts before it promotes them. The publisher uses the same bytes and image digest that passed verification. I exercised signed publication by replaying the historical v1.0.2 fix in a disposable project. When ORAS stalled on the image upload, I switched to Skopeo and resumed from the same signed stage, then checked the destination digest. That was the reason to preserve the stage through a retry. The enabled schedule passed in the real project and found nothing to publish. A qualifying production run through automatic merge and signed publication was still outstanding when I wrote this. Qualification notes

8. What I took away

I originally wanted to move a scheduled check off my machine. The part I kept coming back to was which job should be able to take the next step. The webhook can request a protected pipeline, Codex can propose a change, and the merge job can act on a tested commit. The broken Chromium update was a good reminder that leaving a merge request open with the right evidence is also a useful result.