Skip to content

Git delivery: Git protocol for branches and commits, a thin PR adapter for GitHub, GitLab, Bitbucket and Gitea #286

Open
10 of 13 issues completed

Description

@ephico2real2

Part of #18. Supersedes the approach of #279 / PR #285. Revised 2026-11-15 after the owner's review.

The owner's direction, 2026-11-15

  • "what we need is non complicated format that will work in all git repo and not married to featires in github. what we need is a token or ssh keys."
  • "features there are of API integration that we keep ... we need support for gitlab and bitbucket"
  • "a logic where request is checkout of the main branch using the requestID as the branch and folder name ... this were we create the PR and merge it after request is fullfilled"
  • "do we need PVC ... and cleanup that occurs when no job is running"
  • "proper logging in case we have merge issues"
  • "a direct requst will be wrong": no direct commit to main. Every change goes through a PR or MR.

Design: two layers, as Renovate does

Renovate's model is the reference: one shared Git layer, plus a thin platform adapter for each host for PRs only (Renovate platforms; Renovate's "gitFs" refactor, renovate#2774).

1. The Git layer: the Git protocol only, the same for every host.

  • Credential: exactly one of these, in Secret cmapi-git, in the Argo CD and Flux Secret shapes.
    • An HTTPS token. It goes through GIT_ASKPASS or a credential file. It is never in a URL, argv, a log or .git/config. TLS verification stays on, with CMAPI_GIT_CA_BUNDLE.
    • An SSH key with a pinned known_hosts. An unknown host key is a refusal, never StrictHostKeyChecking=no.
  • Working storage: each worker pod has one bare mirror (partial clone, --filter=blob:none). It sits in an emptyDir (node disk, not medium: Memory) with a sizeLimit and an ephemeral-storage request and limit on the worker, not a PVC. Measured: the repository is 21 KB, and CRC's node allows 115 GB of ephemeral storage. A generic ephemeral volume is the fallback if the clone ever grows to gigabytes. Each request gets a git worktree at <workdir>/<cluster>/<requestId>, on branch cmapi/<cluster>/<requestId>, cut from origin/main after a fetch. This replaces today's cmapi/<cluster>/<namespace>/<requestId> (jobs/open_pr.py:48). The owner agreed on 2026-11-15. The cluster keeps the name unique across the three instances, and cmapi/ keeps bot branches apart. A branch that already exists on a retry is reused only if its head carries this request's trailers and plan hash. That gives a clean checkout per request and no cross-contamination.
  • Why not a PVC: the remote is the source of truth, so a lost emptyDir costs only one re-clone. Resilience: 2 or 3 replicas of the API and worker per instance, with shared state in PostgreSQL, proven #225 runs 2 or 3 worker replicas, and an RWO PVC cannot be shared between them; RWX adds a storage dependency for a cache. Record this decision with its measurements: clone time and size on cmapi-cluster-configs.
  • Write: render the files into the worktree, make one commit (the message carries the request ID, plan hash, approval and requester), and push the request branch. Pushes to main never happen.
  • Cleanup: remove the worktree (git worktree remove) when its request reaches a final state. A sweeper runs when no Git job is running: it calls git worktree prune, removes the directory of any request that is not in flight, and runs git gc --auto. Its result is logged and counted.

2. The platform layer: a thin host API, for the PR only.

  • Operations: open a PR or MR from the request branch, read its state, merge it, and comment and close on failure.
  • Adapters:
    • github: REST.
    • gitlab: Merge Requests API, cloud and self-managed.
    • bitbucket: Cloud REST 2.0, and Data Center REST.
    • gitea: already exists.
    • Each is tested against its host's published API description.
  • Host CI is optional and off by default. The gate is cmapi's own plan-time kubeconform and Kyverno checks, plus approval in cmapi. When it is enabled, only the commit-status API each host has in common is read. Never GitHub's Checks API: fine-grained tokens cannot call it (BUG-69).

Merge after the request is fulfilled

  • delivery.mode: apply (CRC): apply before merge, the Atlantis model (runatlantis.io).
    1. Apply the rendered files from the request branch.
    2. Confirm by reading them back (core/sync.py, confirmed_by_read).
    3. Then merge the PR. So main records only what succeeded.
    • On an apply failure: comment on the PR and close it, leave main untouched, and mark the request failed with the reason.
  • delivery.mode: argocd: merge first, because Argo CD follows main. Then wait for the sync. That is the behaviour today.
  • Before every merge:
    1. Fetch main.
    2. Run git merge-tree --write-tree (Git 2.38 or later) to find conflicts with no checkout.
    3. Check that the request's folder on main still matches the plan's base.
    • The one-open-request-per-namespace rule (core/db/repo.py:6, change-pending) means two requests never change the same folder, so a conflict is a real fault.

Logging for merge problems

Every Git and platform operation logs one structured event with: request_id, cluster, namespace, branch, op (fetch, worktree, commit, push, pr_open, pr_state, merge_check, merge, cleanup), the main sha, the base sha, the head sha, attempt, outcome, the duration, and the Git exit code with redacted stderr.

  • A conflict also logs the conflicted paths from merge-tree.
  • A host API failure also logs its status and message.
  • The same reason goes on the request's timeline, so the portal and GET /requests/{id} show why.
  • Counted in cmapi_git_operations_total{op,result}.
  • A test proves that no token appears in any of it.

How to prove it

  • Against a real bare repository (file://, and SSH with a throwaway sshd and a pinned key), with a stub platform:
    • create, change and delete;
    • two concurrent requests on different namespaces;
    • a conflicting main, refused with its paths logged;
    • an unknown host key, refused;
    • cleanup after a final state and by the sweeper;
    • no secret in a log, argv or .git/config.
  • Each fails on main and passes after.
  • Each platform adapter against its host's published API description.
  • On CRC (apply mode): req-20261115-0002 gets a fresh branch and PR, is applied, is confirmed, and its PR is merged. Then D19 runs.

Sub-issues

Sub-issues

10 of 13 Issues completed
Loading 13 sub-issues

Activity

  1. added
    enhancement
    status:open
    In-Progress
    on Nov 15, 2026
  2. changed the title [-]Plain Git delivery: a token or an SSH key, no host API (PRs, checks, statuses)[/-] [+]Git delivery: Git protocol for branches and commits, a thin PR adapter for GitHub, GitLab, Bitbucket and Gitea[/+] on Nov 15, 2026
  3. ephico2real2 commented on Nov 15, 2026

    @ephico2real2
    OwnerAuthor

    Design review: Fable 5.2, a second model family. Scope was cut to D1, D2 and D4 because of its quota. Full text: workbench/cmapi/review-286-fable/REPORT.md. The coordinator checked each code claim against the code and ran the mirror hypothesis. Each one below is accepted into the design.

    F1 (HIGH): an applied change whose merge then fails has no state.

    • failed is not in OPEN_STATES (core/db/models.py:17, checked). Failing the request would release the namespace lock while the cluster holds a change that main lacks. The next plan reads main (jobs/open_pr.py:41-45) and would overwrite it.
    • Design change:
      • Run merge-tree and the plan-base check before the apply, and again before the merge.
      • Merge pinned to the applied head sha.
      • A new state, merge_failed, in OPEN_STATES. The PR and the branch are kept. Retry with backoff, then alert and wait for :retry.
      • Never roll the cluster back or close that PR automatically.
    • Test: a stub merge fails after a confirmed apply. The lock holds (409 change-pending), the PR stays open, and :retry reaches synced.

    F2 (HIGH): the credentials are two Secrets.

    • cmapi-git-ssh, of type kubernetes.io/ssh-auth, key ssh-privatekey, for the Git transport, mounted in the worker only.
    • cmapi-git, key token, for the host API only, never given to a git process.
    • "Exactly one" applies to the transport. A PR provider without an API token stops at start. The WIP's refusal of both (plain.py:135-136, checked) goes.

    F3 (HIGH): an API credential is needed for each host. SSH covers only fetch and push.

    Host SSH API
    GitHub a write deploy key a fine-grained token with Pull requests and Contents write, or a GitHub App
    GitLab a read-write deploy key made by a service account a project access token
    Bitbucket Cloud a bot account's own key (access keys are read-only) a repository access token
    Bitbucket Data Center, Gitea a write deploy key a repository-scoped token
    • main is protected on the host, so the rule that cmapi never pushes to main is enforced there too.
    • Facts that Fable marked [memory] are verified at the primary source before they go into the docs.

    F4 (MEDIUM): the SSH details.

    • The public key is not needed in the Secret. If it is stored, it goes under ssh-publickey, never ssh-privatekey.pub. cmapi logs the key's fingerprint at start and refuses a mismatch.
    • known_hosts is in ConfigMap cmapi-git-known-hosts, holding every key type the host publishes (GitHub: ed25519, ecdsa and rsa). It is mounted as a directory, not by subPath, so a rotation needs no restart. To rotate: add the new key, then remove the old one.
    • The key is ed25519 with no passphrase (BatchMode=yes). A key that is encrypted or does not parse stops cmapi at start.
    • The mount is defaultMode: 0440 (group-readable through the pod's fsGroup), readOnly, with items for the key only.

    Mirror (confirmed by measurement): git clone --mirror fetches with +refs/*:refs/* and has no refs/remotes/origin/main. The cache is therefore a bare clone with the fetch refspec +refs/heads/main:refs/remotes/origin/main and --filter=blob:none, so a fetch never writes into the cmapi/* branches that the worktrees hold.

    Not reviewed by Fable: D3 (SSH under an arbitrary UID), D5 (worktree concurrency), D6 (merge-tree exit codes) and D7 (missing cases). They belong to PR-A's design record and its review.

  4. ephico2real2 commented on Nov 15, 2026

    @ephico2real2
    OwnerAuthor

    The owner's decision, 2026-11-15: a machine user account cmapi-git-bot on each host. It is a GitHub machine user, a GitLab service account or a Bitbucket bot account.

    • Its SSH public key is configured in the account, and the API token is that account's token, so pushes and PRs are authored by cmapi-git-bot.
    • The commit identity is cmapi-git-bot with a configured no-reply email (GIT_AUTHOR_* and GIT_COMMITTER_*). The request ID, plan hash, approval and requester stay in the commit trailers.
    • The SSH login user stays git@<host>, because these hosts pick the account by its key.
    • Deploy keys remain a documented alternative.

    The pod's local UID is a separate matter. OpenSSH looks up its own UID at start and stops with "No user exists for uid …" before any config is read. So the image's /etc/passwd is made group-writable by gid 0, and CRI-O adds the entry, as Red Hat's arbitrary-UID guidance says. A test runs ssh under a UID with no passwd entry.

  5. ephico2real2 commented on Nov 15, 2026

    @ephico2real2
    OwnerAuthor

    Names, the owner's decision, 2026-11-15:

    • Secret cmapi-git-bot (Opaque, key token, for the host API)
    • Secret cmapi-git-bot-ssh (kubernetes.io/ssh-auth, key ssh-privatekey and optional ssh-publickey, for the Git transport, mounted in the worker only)
    • ConfigMap cmapi-git-bot-known-hosts

    These replace cmapi-git and cmapi-git-ssh everywhere. On CRC the bot's new token goes into cmapi-git-bot; the old cmapi-git is removed by name after PR-A deploys.

  6. ephico2real2 commented on Nov 15, 2026

    @ephico2real2
    OwnerAuthor

    Retraction (coordinator). My earlier comment says the image's /etc/passwd is made group-writable by gid 0 so that CRI-O adds the entry. CRI-O's source refutes it: cri-o/cri-o main utils/utils.go, GeneratePasswd returns early at line 222 when checkFilePermissions is true, and that is stat.Mode&0o022 != 0 at line 314. A group- or other-writable /etc/passwd stops the entry. Red Hat (access.redhat.com/articles/4859371) also names a writable /etc/passwd as a privilege-escalation risk.

    The design:

    • /etc/passwd stays 0644 root.
    • On OpenShift, CRI-O adds the pod UID's entry.
    • Where no runtime adds it (podman, containerd), nss_wrapper is set only in the environment of git's ssh, only when getpwuid fails, with a private passwd file.
    • A test checks that the image's /etc/passwd is not group- or other-writable. Found by OB1 run 10.
  7. ephico2real2 commented on Nov 15, 2026

    @ephico2real2
    OwnerAuthor

    #286: the coordinator's arbitration of the two designs

    The coordinator (Opus 5.5) wrote this on 2026-11-15 after reading both designs in full:

    • Fable 5.2: workbench/cmapi/design-286-fable/DESIGN.md, 517 lines.
    • OB1 run 10 (Opus 5.5): wt10-a/docs/reviews/2026-11-15-issue-286/README.md at db0738e, 382 lines.

    Each was written without the other. Where they differ, the choice and its reason are below. Where they agree, the shared text stands. The result goes into the design record of PR-A.

    # Question Fable OB1 Chosen Why
    1 States after pr_open in apply mode applied and merge_failed, both in OPEN_STATES. An apply_started event is committed in its own transaction merge_failed only. One job, deliver_pr, does the apply and the merge Fable With OB1's single job, a crash after the apply re-runs from step 1. A failure there is marked failed, which releases the lock while the cluster holds the change: F1 again. The apply_started marker and the applied state make "the cluster is ahead of main" a state, so the table itself refuses CANCEL, PR_FAILED and BASE_CHANGED there (lifecycle.py:4-5: lock ownership follows the state)
    2 Job split Five single-effect jobs (push_branch, open_pr, pr_checks, apply, merge) plus git_cleanup and git_reconcile deliver_pr combines the apply and the merge Fable One external effect for each job makes each one idempotent, with its own detection of work already done (section 2 of Fable's design)
    3 A remote branch that already exists The adoption test (2.2). If it is not adopted, replace it with a lease on the sha seen Reuse it if the trailers match; otherwise refuse and leave it Fable's adoption test, with OB1's refusal for foreign commits Replace with a lease only when the head carries this request's Cmapi-Request-Id: our own stale attempt, for example after main moved. A head with no cmapi trailers is a person's work: refuse, log and alert. Never overwrite it
    4 Deletes in apply mode Apply before merge, through awaiting_prune then APPLIED Merge first, then awaiting_prune OB1 The prune waits for an operator's prune:confirm for an unbounded time. Holding a PR and a branch open across a human step adds staleness, for no gain: the namespace exists in both orders until the prune. This is today's tested flow. Recorded as a known exception to "merge after fulfilled"
    5 Reproducible commit (both dates = approved_at) Yes Not specified Fable A repeated push is a no-op, and a deleted branch can be re-created bit for bit
    6 Sweeper A loop in each pod, with a non-blocking exclusive flock git_sweep, a recurring database job Fable's per-pod scope, run in the worker loop between jobs A database job runs on one replica, but each pod has its own emptyDir. The worker runs one job at a time (worker.py:94: the only thread is the lease heartbeat), so the loop's idle moment is "when no job is running"
    7 Locking inside a pod Shared and exclusive flock for each operation class One lock for each process serialises Git; a process-ownership flock OB1 One job at a time for each process (finding 6). Fable's finer locks protect against concurrency that the worker does not have. Test 7.4-a still runs, with N jobs in threads against one workdir, to prove that the single lock is enough if the worker ever runs jobs in parallel
    8 Host branch deletion Conditional delete by a Git push with a lease, shared by every adapter Rely on the host's "delete branch on merge" Fable The host setting is host-specific and off by default on some hosts. A lease push is one code path, and conditional
    9 PRs and branches a crashed worker left git_reconcile, a periodic job, with the table in 5.3 Not designed Fable —
    10 merge-tree exit codes Read from the docs: 0 clean, 1 conflict, other is an error Measured: exit 1 also for "not something we can merge" on 2.52.0 and 2.55.0 OB1 A measurement beats the doc text. A conflict is exit 1 with a tree OID as the first field; every other result is an error, never "clean"
    11 Host CI off: post statuses as a record? Only when host_ci or git.postStatus is set Post ci/* and cmapi/check always Fable Posting needs Commit statuses write, a host feature the owner does not want depended on. Off by default
    12 Plan-time reads in the API pod Move the reads to the Git layer The API keeps reading through the host API, because the SSH key is in the worker only OB1 for PR-A; owner decision before PR-B GitHub's read endpoints exist and work today, so CRC is unblocked. Each new host would then need read endpoints too. Before PR-B the owner picks: (a) the API mounts the bot's credential read-only and reads through Git, or (b) the host API reads stay for each host
    13 Git over HTTPS with the API token on CRC — An interim, until the bot's SSH key exists OB1 Recorded as a known exception to F2
    14 Bitbucket Cloud has no sha-pinned merge A read-check, then the merge, then the post-merge folder check (2.4) — Fable Verify against Atlassian's API description in PR-C
    15 :revert before a merge (sync_failed with no merge_sha), and from merge_failed restore_apply proposed; the owner decides No revert from merge_failed The owner decides; not in PR-A —
    16 A hand merge while cmapi delivers merge reads the state first and adopts a merge Open (WIP fails the request) Fable —
    17 Logging and metrics 6.1 to 6.3 2.8 Fable's fields and metrics, with OB1's redact() and its test Fable's set is a superset. OB1's redaction of registered secrets is the mechanism

    Both agree, and it stands: the two-layer split; the bare git init with the single refspec; the worktree path and branch name; the empty lease on the first push; the fence before each external effect; the credential objects and mounts; SSH options; nss_wrapper with /etc/passwd at 0644; and the rejected options.

    Still to verify before the docs: every cell Fable marked [memory] in its 3.3 mapping, and OB1's per-host table, at each host's published API description (Fable's test 7.3-b).

  8. added a commit that references this issue on Nov 15, 2026
  9. added a commit that references this issue on Nov 15, 2026
  10. 2 remaining items

  11. ephico2real2 commented on Nov 15, 2026

    @ephico2real2
    OwnerAuthor

    OB1 run 11 on CRC (main 21a7f47): two defects found under this issue: #294 (BUG-75, request events stamped with the transaction start: 'applied' before 'apply_started', 'merged' before GitHub merged) and #295 (BUG-76, git_op pr_number stale after :retry; git_reconcile's per-PR events carry no request). The flow itself passed end to end (PRs #5 and #6 merged pinned to the applied head).

  12. added a commit that references this issue on Nov 16, 2026
  13. added
    status:partly-fixed
    and removed
    status:open
    on Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    In-Progressenhancementstatus:partly-fixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions