Skip to content

Serve projects as git repositories (issue #29) - #38

Merged
nk-coding merged 29 commits into
mde-optimiser:mainfrom
amirrza777:amir/git-server
Sep 25, 2026
Merged

nk-coding merged 29 commits into
mde-optimiser:mainfrom
amirrza777:amir/git-server

Conversation

@amirrza777

Copy link
Copy Markdown
Contributor

Closes #29, following the design agreed there: MDEO Cloud serves each project as a real git repository over smart HTTP, rather than syncing to an external host. Any git client can clone/push directly against a project using the user's existing MDEO login (HTTP Basic), so there is nothing new to store or manage credentials for.

Design recap

  • Storage. Git objects live in Postgres, not on disk, through JGit's DfsRepository/DfsObjDatabase, the same abstraction Gerrit uses for this. Keeps the backend stateless, matching how the rest of the platform already works.
  • Protocol. UploadPack/ReceivePack driven directly over two Ktor routes (GitServlet doesn't drop in, since this is Netty rather than a servlet container).
  • Commit boundary. On fetch, the current file state is committed only if it differs from the last recorded head. Real, append-only history with a boundary nobody has to choose, not a commit per WebSocket save.
  • Push. Applied through the ordinary file service, so a push gets exactly the same validation, version bump and locking as a workbench edit. Anything that isn't a fast-forward is rejected by git; the user merges locally with tools they already know. No conflict-resolution UI needed.
  • What's in the tree. Project files, plus .mdeo/plugins.json carrying the project's enabled plugins (as their registered urls, not per-instance ids, so it's portable across MDEO instances). Diagram layout (file_metadata) was considered too but deliberately left out: it's purely representational, changes on nearly every diagram interaction, and would turn "commit when something real changed" into "commit on every look."

What's implemented

  • Postgres-backed object and ref storage (PostgresDfsRepository/PostgresDfsObjDatabase/PostgresDfsRefDatabase)
  • Clone (git-upload-pack) and push (git-receive-pack) over smart HTTP
  • .mdeo/plugins.json, round-tripped on both clone and push, with unknown urls on push skipped rather than failing, and its absence from a pushed tree leaving plugins untouched rather than clearing them
  • Push atomicity: a rejected or partially-failed push rolls back any file writes it already made rather than leaving them applied
  • A size limit on pushes, refused up front with a clear message rather than attempted and failed halfway through
  • Pushes to the same project are serialized, fixing a real race: two concurrent pushes could both pass validation and both write files to Postgres before git's own ref-level check picked a winner, so a push git told the client was rejected could still silently land its files
  • A "Git" section in the workbench's project panel showing the clone URL with a copy button

Verified

All of the above against the real running dev stack: git clone/git push from the CLI, direct Postgres checks after each push, and the clone-URL UI in the workbench. The concurrency fix specifically was reproduced with real concurrent git push processes, confirmed via direct DB query, then re-verified 3 times clean after the fix.

Why draft

This is a large new subsystem (storage layer, protocol handling, workbench integration) and the design itself already went through discussion in #29. Opening as a draft so the storage/protocol approach can get a look before going further, rather than presenting it as a fait accompli.

Groundwork for serving projects as git repositories, the direction agreed on
issue mde-optimiser#29. JGit's DFS storage layer is designed for backends that are not
filesystems: it never asks for individual objects, only for whole pack files
to write and read back, so a backend has to move byte streams and keep enough
metadata to rebuild a pack description.

That maps onto three tables. Pack metadata and the pack bytes are separate
because one pack has several files, and JGit reads them as random access
streams, so a payload is only fetched when a read reaches it. Refs are updated
through a compare and set, which becomes a statement matching on the previous
value.

Keeping this in Postgres rather than on disk preserves the property that the
backend holds no persistent state outside the database. Bare repositories on
disk would have meant giving it a volume and a backup story it does not
currently need.

No routes yet, this is storage only.
Clone now works: git clone http://<user>@<host>/git/<projectId>

A project's files live in Postgres and are edited live, so there is no commit
history to draw on. History is appended when someone looks instead: before a
repository is served, the current file state is written as a commit, but only
if it differs from what the branch already points at. That gives an append
only history with a boundary nobody has to choose, and repeated fetches of
unchanged content do not pile up empty commits.

Authentication is HTTP basic against existing MDEO accounts, checked against
the project read permission that already exists. Git clients cannot present a
session cookie or a JWT, which is why these routes sit outside both
authenticate blocks and verify credentials themselves. An unauthorised project
answers exactly as an unknown one, so the endpoint cannot be used to find out
which project ids exist.

Only upload-pack is served. Push is refused with a plain message rather than a
protocol error, which reports far better in a client.

Verified against the running stack: clone of a real project, nested
directories intact, git fsck clean, a second fetch with no edits producing no
new commit, and an edit producing exactly one fast forward commit carrying the
change.
A push is applied by writing every path of the received commit through the
ordinary file service, so it goes through the same validation, version bump
and project locking as an edit made in the workbench. Paths the commit no
longer contains are deleted, which is what makes a push replace the project
rather than only add to it.

The work happens in a pre-receive hook, before the ref moves, so a push that
cannot be written into the project is refused outright rather than leaving the
branch ahead of the files.

Two things are refused. A push that is not a fast forward, because the user
merges locally with tools they already know, which is what removes the need
for any conflict resolution here. And a push to any branch other than the one
the project publishes, because a project has one set of files rather than one
per branch.

One gap worth naming: clients with the project open are not told that files
changed. The platform has no file change broadcast at all today, so an edit
made in one browser tab is equally invisible to another. Not specific to
pushing, but a push can move many files at once, which makes it more visible.

Verified against the running stack: a push creating a file and editing another
lands in the project and the app parses the result; a push deleting a file
removes it; a rewind is rejected by the server; and a push to another branch
is rejected with a readable reason. A fetch straight after a push adds no
duplicate commit, so the two halves agree on what the current tree is.
A clone with no plugin config would be a project the workbench cannot
open properly, since plugins.json is the only source of which
languages and editors are active. Diagram layout was considered too
(see issue mde-optimiser#29) but left out on nk-coding's point: it changes on
practically every diagram interaction, which would turn commit-on-fetch
into a commit on every look rather than one on real change.

Enabled plugins are published as their registered urls, the stable
identifier already used by DEFAULT_PLUGIN_URLS, not the per-instance
plugin id. On push, a url with no matching registered plugin is
skipped rather than failing the push, and the file's absence from a
pushed tree leaves plugins untouched rather than clearing them.

The file's content is only regenerated when the enabled set actually
changed; otherwise the current head's own bytes are reused. Without
this, a push whose JSON formatting differs from the canonical output
would make the very next fetch look like a change and add a
commit-on-fetch node describing nothing real, the same class of noise
that ruled out diagram layout.
applyCommitToProject wrote and deleted each path in a push one at a time,
each through FileService's own transaction. A failure partway (a path
colliding with an existing directory, a plugins file that will not parse) was
reported to the client as a rejection, but every write already made before
that point in the loop had already committed, so the ref not moving did not
mean the project was unchanged. A rejected push could still leave a project
part old, part new.

The apply loop now runs inside one outer transaction, and a failure throws
instead of returning early. FileService's own transaction blocks join this
one rather than committing separately, so the throw rolls every write and
delete made by this push back out together. Reused as a normal ApiResult
message once caught, so the client sees the same rejection reason as before.

Verified against the running stack: pushed a commit that both adds a new file
and replaces an existing directory with a file at the same path, ordered so
the valid write runs before the one that fails. The push is rejected, and the
new file is confirmed absent from the project afterward.
Nothing capped how large a pushed pack could be. A configurable limit
(GIT_MAX_PUSH_PACK_SIZE_BYTES, defaulting to 100 MiB) is now set on
ReceivePack, checked by JGit while unpacking and before any command runs, so
an oversized push is refused outright rather than partway through applying
some of its files.

JGit reports this to the client as a normal git status report, but also
throws UnpackException out of receive() afterward. Left uncaught, that reached
the application's generic exception handler and logged as an unhandled
500, which reads as a server crash for what is really an expected rejection
of a push that is too large. Caught locally and logged at info instead.

Verified against the running stack: a 150 MiB push is cleanly rejected with
the configured limit in the message, and the rejection now logs as a normal
push outcome rather than an unhandled exception.
The only way to use the git server so far was to hand-build a curl or git URL
against the backend directly. The project panel now has a Git section with a
read-only clone URL and a copy button, right above the existing Management
section.

nginx only proxied /api/ and /plugin/* to the backend, so a URL built from the
workbench's own origin would not actually have worked; added a /git/ location
alongside them, with its own client_max_body_size raised to match the
backend's push size limit rather than inheriting the server-wide 64m meant for
plugin file-data requests. The vite dev server gets the equivalent proxy
entry for running the workbench outside Docker.

Verified against the running stack: the URL shown in the panel is exactly
what git clone accepts through the workbench's own origin (not just the
backend's own port), and the copy button places that same URL on the
clipboard.
A ReceivePack reads the ref it treats as current itself, live, at the start
of handling its own request rather than from an earlier advertisement. Two
pushes to the same project racing on the same starting head could both make
that live read before either had moved the ref, so both passed validation and
both ran applyCommitToProject from the pre-receive hook, which runs before
JGit's own ref update decides which one actually wins. The one that lost that
update was reported to its client as rejected, but its files had already been
written.

Reproduced against the running stack: two clients pushing different new files
from the same head at the same time, one push rejected as expected, but its
file present in the project regardless.

Pushes to one project now run inside a per-project mutex covering the whole
receive-pack request, so a second push's live ref read only happens after the
first has fully finished. It then correctly sees the first push's new head,
fails validation, and is rejected before the hook ever touches a file, rather
than racing it.

Verified against the running stack: the same two-client scenario run three
times, each producing one accepted push and one cleanly rejected one, with
the rejected push's file confirmed absent from the project every time. A
single ordinary push still succeeds as before.
# Conflicts:
#	app/packages/workbench/src/components/projects/ProjectDetails.vue
The backend had no tests at all and no JUnit platform wired up, despite
already depending on kotlin-test-junit5. Enabled useJUnitPlatform() so
kotlin.test annotations actually run under Gradle.

Extracted .mdeo/plugins.json's parsing and comparison logic out of
GitRepositoryService into GitPluginsFile, a small pure object with no
JGit or Postgres dependency, so it could be unit tested directly rather
than only through a live clone/push. Covers the formatting-insensitive
comparison the phantom-commit fix relies on, and the plain and
malformed-input parsing cases.

Also covers ByteArrayReadableChannel, JGit's random-access read
interface over an in-memory pack file: sequential reads, seeking,
EOF and past-EOF behavior, and the open/close lifecycle.

Scoped to pure, dependency-free logic rather than full integration
tests against a live Postgres, as a first, minimal precedent for
backend testing rather than a wholesale test infrastructure buildout.
Nothing ran them before: the docker build only runs shadowJar, which
does not depend on the test task, so the new git storage tests would
have passed or failed silently forever. Added as its own workflow
rather than folding into docker-publish.yml, since it is a much
shorter, unrelated check and shouldn't wait on or block image builds.
@amirrza777

Copy link
Copy Markdown
Contributor Author

Added since opening this as a draft:

  • Verified two edge cases live: cloning a genuinely empty project (works, git reports it as an empty repo as expected) and pushing into one for the first time (works, and `.mdeo/plugins.json` is correctly added retroactively on the next fetch once the project has real content). Also confirmed the cascade deletes on the new `git_packs`/`git_pack_files`/`git_refs` tables actually clean up when a project is deleted, not just that the foreign keys claim to.
  • Added this repo's first unit tests: extracted `.mdeo/plugins.json`'s parsing and formatting-insensitive comparison logic (the piece the phantom-commit fix from earlier in this branch relies on) into a small pure GitPluginsFile object, and wrote tests for it plus for ByteArrayReadableChannel. The backend had kotlin-test-junit5 as a dependency but no useJUnitPlatform() and zero test files, so also wired that up.
  • Added a dedicated backend-tests.yml CI workflow to actually run them: the existing docker-publish.yml only runs gradle :backend:shadowJar, which doesn't depend on test, so these would otherwise pass or fail silently forever.

Scoped the tests to pure, dependency-free logic rather than full integration tests against a live Postgres, as a minimal first precedent rather than a wholesale test infrastructure decision, happy to discuss if a different starting point is preferred.

amirrza777 and others added 2 commits August 12, 2026 09:49
The only place this feature was discoverable before was the Git
section's own hint text in the project panel. Added alongside the
existing zip import/export docs, since it's the same kind of thing:
moving a project in or out of the platform.
@nk-coding

Copy link
Copy Markdown
Collaborator

I tested it, it works nicely!
I think in the future we need improved authentication (probably like github, with ssh support and OAauth tokens for access itself (we do not want the user to use their password in the generic dialog), but that is stuff for a future PR
I again let an agent do a review too, these are the findings: https://claude.ai/code/artifact/ac3c0274-8655-49f6-9959-3ed25fddf4c7
I think it would be a good idea to move from that .mdeo dir as this can easily collide with user content, probably a .mdeo config file is sufficient as we only have one and then the file name (or rather lack of file name) would also guarantee that this is never a user content

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds native smart-HTTP Git repositories for projects, backed by PostgreSQL and integrated into the workbench.

Changes:

  • Implements JGit object/ref storage, clone/push routes, authentication, and push handling.
  • Adds plugin metadata round-tripping and Git configuration.
  • Adds clone UI, proxying, documentation, tests, and CI.

Reviewed changes

Copilot reviewed 22 out of 22 changed files in this pull request and generated 10 comments.

Show a summary per file
File Description
website/docs/guide/workbench.md Documents Git clone and push behavior.
platform/gradle/libs.versions.toml Adds JGit dependency version.
platform/backend/src/test/kotlin/com/mdeo/backend/git/GitPluginsFileTest.kt Tests plugin metadata encoding.
platform/backend/src/test/kotlin/com/mdeo/backend/git/ByteArrayReadableChannelTest.kt Tests in-memory pack reads.
platform/backend/src/main/kotlin/com/mdeo/backend/service/PluginService.kt Reads and replaces project plugins by URL.
platform/backend/src/main/kotlin/com/mdeo/backend/routes/GitRoutes.kt Implements smart-HTTP Git routes.
platform/backend/src/main/kotlin/com/mdeo/backend/git/PostgresDfsRepository.kt Defines PostgreSQL-backed repositories.
platform/backend/src/main/kotlin/com/mdeo/backend/git/PostgresDfsRefDatabase.kt Persists Git refs.
platform/backend/src/main/kotlin/com/mdeo/backend/git/PostgresDfsObjDatabase.kt Persists Git pack objects.
platform/backend/src/main/kotlin/com/mdeo/backend/git/NamedPackDescription.kt Retains database pack names.
platform/backend/src/main/kotlin/com/mdeo/backend/git/GitRepositoryService.kt Synchronizes projects and Git commits.
platform/backend/src/main/kotlin/com/mdeo/backend/git/GitPluginsFile.kt Encodes plugin metadata.
platform/backend/src/main/kotlin/com/mdeo/backend/git/ByteArrayReadableChannel.kt Provides random-access pack reads.
platform/backend/src/main/kotlin/com/mdeo/backend/database/Tables.kt Adds Git storage tables.
platform/backend/src/main/kotlin/com/mdeo/backend/database/DatabaseFactory.kt Creates the Git tables.
platform/backend/src/main/kotlin/com/mdeo/backend/config/AppConfig.kt Adds Git push-size configuration.
platform/backend/src/main/kotlin/com/mdeo/backend/Application.kt Registers Git services and routes.
platform/backend/build.gradle.kts Adds JGit and test configuration.
infra/docker/workbench/nginx.conf Proxies smart-HTTP Git requests.
app/packages/workbench/vite.config.ts Proxies Git during development.
app/packages/workbench/src/components/projects/ProjectDetails.vue Displays and copies clone URLs.
.github/workflows/backend-tests.yml Runs backend tests in CI.
Suppressed comments (2)

platform/backend/src/main/kotlin/com/mdeo/backend/git/GitRepositoryService.kt:142

  • files can already contain .mdeo/plugins.json because the ordinary file service does not reserve this logical path. Appending another stage-0 entry with the same path makes JGit's DirCacheBuilder.finish() throw duplicateStagesNotAllowed, so fetching such a project fails. Reserve this path for Git metadata or filter the ordinary row before building the tree.
            for ((path, content) in files + (pluginsPath to pluginsContent)) {
                val entry = DirCacheEntry(path)
                entry.fileMode = FileMode.REGULAR_FILE
                entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, content))
                builder.add(entry)

platform/backend/src/main/kotlin/com/mdeo/backend/routes/GitRoutes.kt:132

  • The entire push is allocated with readBytes() before setMaxPackSizeLimit is reached, so the backend's configured limit does not bound request buffering. Direct, development, or differently configured proxy access can exhaust heap before JGit rejects the pack. Stream the request to ReceivePack, or enforce a counting/content-length limit before allocating the body.
            gitRepositoryService.withPushLock(projectId) {
                val repository = gitRepositoryService.openRepository(projectId)
                val requestBody = call.receiveStream().readBytes()

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread infra/docker/workbench/nginx.conf Resolved
…gle .mdeo file

The workbench's BACKEND_SERVICE env var included a /api path segment that
nginx's proxy_pass silently mangles for any route outside /api, breaking
the new /git/* routes; drop the path and let each location block append
its own. Also rename the published plugins manifest from .mdeo/plugins.json
to a plain .mdeo file per review feedback, and add a copy-clone-URL aria-label.
…imits, and correctness bugs

Covers every finding from the Claude architecture review (G-1..G-12, V-1..V-5)
and the separate Copilot review of the git-server branch:

- Reject unsafe/.git-prefixed paths on push (G-1), belt-and-braced by
  ReceivePack.setCheckReceivedObjects(true); verified live that a crafted
  push targeting .git/config is rejected by JGit's own object checker.
- Stream push/fetch request bodies instead of buffering, and enforce a
  configurable max push size against the running inflated total (G-2).
- Reserve .mdeo at the FileService level too, not just on the git side (G-3).
- Generate pack names from UUIDs instead of a non-atomic in-memory counter (G-4).
- Reclaim storage from rejected pushes via JGit's DfsGarbageCollector instead
  of leaving orphaned packs behind (G-5).
- Batch listPacks() into one query instead of one-per-pack, and read pack
  bytes lazily by range (PostgresPackReadableChannel) instead of loading
  whole bytea columns (G-6).
- Widen the per-project lock to cover fetches too, closing a fetch-vs-push
  race; documented as valid only for a single backend replica (G-7).
- Move blocking JGit/JDBC work off the default coroutine dispatcher (G-10).
- Add an in-memory sliding-window rate limiter (5/min per username, 20/min
  per address) shared between session login and git basic auth (G-8).
- Return generic errors for unexpected exceptions instead of leaking
  internals to git clients (G-9).
- Fix HEAD defaulting to refs/heads/master on repository creation instead
  of refs/heads/main (Copilot).
- Make ref creation atomic via insertIgnore/ON CONFLICT instead of a
  non-atomic check-then-insert (Copilot).
- Always publish current files over git, including for projects with zero
  ordinary files, so .mdeo is never silently dropped (V-4, Copilot).
- Skip rewriting files whose content is unchanged on publish (V-1), track
  monotonic per-path version counters that survive delete+recreate instead
  of resetting to 1 (V-2, new file_version_counters table), thread an
  optional expectedVersion through writeFile for future conflict detection
  (V-3), broadcast a filesChanged websocket event after an accepted push,
  and clean up now-empty directories after a push deletes files (V-5).
- Gate .mdeo admin-permission checks and plugin sync on whether the pushed
  .mdeo content actually differs from the project's current plugins, not
  merely on its presence in the pushed tree. Git always sends the full tree
  on every push, so the original presence check required admin permission
  for every push once .mdeo existed; found and fixed via live testing with
  a write-only project member.

Verified locally: full backend test suite green, and live end-to-end
testing over the real git HTTP protocol covering fresh-project clone,
push/fetch round trips, a write-only user's push being correctly scoped
to non-.mdeo changes, monotonic versioning across delete+recreate, rate
limiting tripping under rapid auth attempts, and a rejected malicious push
leaving the ref untouched.

Deliberately out of scope, left as-is with rationale in code comments:
per-project locking stays in-process (not pg_advisory_xact_lock) since the
service already runs as a single replica and cross-connection session-lock
semantics weren't worth the risk without multi-replica testing; storage
reclaim on rejection is synchronous rather than a periodic sweep since no
scheduler infrastructure exists yet.
…erver

# Conflicts:
#	infra/k8s/mdeo/services.tf
@amirrza777

Copy link
Copy Markdown
Contributor Author

Pushed a round addressing every item from both the architecture review and Copilot's review comments:

Security/correctness (the review's G-1..G-12):

  • Reject unsafe/.git-prefixed paths on push, plus ReceivePack.setCheckReceivedObjects(true) as a second line of defense. Verified live: a crafted push writing into .git/config via raw plumbing is rejected by JGit's own object checker before it reaches application code, and the ref is left untouched.
  • Stream push/fetch bodies instead of buffering, and enforce a configurable max push size against the running inflated total.
  • .mdeo is now reserved at the FileService level too, not just on the git side.
  • Pack names come from UUIDs instead of a non-atomic counter.
  • Rejected pushes now reclaim their storage via JGit's own DfsGarbageCollector.
  • listPacks() batches into one query instead of one-per-pack, and pack bytes are read lazily by range instead of loading whole bytea columns.
  • The per-project lock now covers fetches too, closing a fetch-vs-push race (documented as valid only for a single backend replica, matching current replicas = 1).
  • Blocking JGit/JDBC work moved off the default coroutine dispatcher.
  • Added a sliding-window rate limiter (5/min per username, 20/min per address), shared between session login and git basic auth.
  • Unexpected exceptions now return a generic message to git clients instead of leaking internals.

Copilot's findings:

  • Fixed HEAD defaulting to refs/heads/master on repo creation instead of refs/heads/main.
  • Made ref creation atomic (insertIgnore/ON CONFLICT instead of check-then-insert).
  • Publishing now always runs, even for a project with zero ordinary files, so .mdeo is never silently dropped.
  • Plus the N+1 pack query, uncompressed-size limit, and copy-clone-URL accessibility label.

Version-keeping cache correctness (V-1..V-5):

  • Skip rewriting a file whose content hasn't actually changed.
  • Per-path version counters now live in their own table and survive delete+recreate instead of resetting to 1.
  • writeFile takes an optional expectedVersion for future conflict detection.
  • A filesChanged websocket event fires after an accepted push.
  • Empty directories left behind by a push are cleaned up.

.mdeo naming: now a single file at the project root, not a directory, per your comment.

Found and fixed during live testing (not in either review): the original .mdeo-admin-permission check fired on every push, not just ones that actually changed .mdeo — because git always sends the full tree, so .mdeo shows up in every push once it exists. Fixed by comparing pushed .mdeo content against the project's actual plugin state, and confirmed live with a write-only project member: unrelated file pushes go through, genuine plugin changes still require admin.

Verified locally end-to-end over the real git HTTP protocol: fresh-project clone, push/fetch round trips, the write-only-user scenario above, monotonic versioning across a delete+recreate cycle, the rate limiter tripping under rapid auth attempts, and the malicious-push rejection. Full backend test suite and all CI checks are green.

Two things deliberately left as-is, with rationale in code comments:

  • The per-project lock stays in-process rather than moving to pg_advisory_xact_lock — the service already runs as a single replica, and getting cross-connection session-lock semantics right without multi-replica testing wasn't worth the risk for a lock that's already correct at the current scale.
  • Storage reclaim on a rejected push runs synchronously rather than as a periodic sweep, since there's no scheduler infrastructure in the codebase yet.

SSH/OAuth-token auth is tracked separately in #41, per your comment that it's future-PR work.

…ve/ref-CAS ordering gap

Copilot's oversized-push finding asked for both an aggregate uncompressed
limit (already added) and a per-object limit at the JGit level; add the
latter via setMaxObjectSizeLimit so a single highly compressible blob is
rejected during unpack instead of only being caught by the running total
afterward.

Also document, at the call site, that applyCommitToProject's file writes
commit in their own transaction before JGit's ref CAS runs, so a crash in
that narrow window leaves files ahead of the ref rather than atomically
succeeding or failing together. The per-project lock already closes the
concurrent-reader half of this; the crash-durability half is left as a
known gap since coordinating with JGit's internal ref update isn't exposed
as something this code can wrap in its own transaction, and a client's
natural retry is a no-op against the already-written files.
…for git auth

Half of issue mde-optimiser#41 (Niklas's PR38 follow-up): git clone/push over HTTP still
prompts for the account's own MDEO username and password, which is a
generic credential a user doesn't want in every git client and can't
revoke without changing their login password. This adds GitHub-style
personal access tokens as the recommended alternative.

- New personal_access_tokens table; tokens are SHA-256-hashed (fast hash is
  correct here, since the secret is already 256 bits of CSPRNG entropy, not
  a low-entropy password bcrypt needs to slow down), prefixed mdeo_pat_ so
  GitRoutes can cheaply recognize one before touching the database.
- PersonalAccessTokenService: create (returns the raw value once), list
  (metadata only), revoke (scoped to the caller's own tokens), and verify
  (the git-auth equivalent of UserService.verifyPassword).
- GitRoutes.authorizeGit tries token verification first, falling back to
  the existing password check unchanged - additive, not a breaking change.
  Also closes G-8's bcrypt-oracle concern for anyone who switches: a token
  check is a hash lookup, not a bcrypt comparison.
- New self-service /api/tokens routes (create/list/revoke), mounted behind
  session auth like the rest of account management.
- Workbench: an "Access tokens" section in the Account dialog, alongside
  the existing change-password one - create, one-time reveal with copy,
  list, revoke.

Verified locally: full backend test suite green, and live end-to-end
against the real git HTTP protocol - create a token via the API, clone and
push with it as the Basic Auth password, confirm lastUsedAt updates,
revoke it and confirm the next git operation is rejected while the account
password keeps working unchanged.

No dedicated unit tests added for PersonalAccessTokenService: this
codebase has no database test harness (the two existing backend tests
only cover pure, DB-free logic), so a real create/verify/revoke test would
need new test infrastructure out of scope here. Correctness is verified
live instead, against the actual running stack.

Second half of mde-optimiser#41 (SSH support) is tracked as a separate follow-up PR.
Second half of issue mde-optimiser#41 (first half was personal access tokens for HTTP,
#1): a git-over-SSH listener on its own port,
authenticated by registered public key, serving the same operations the
HTTP smart-git routes serve.

Design (verified against real JGit 7.3.0 and MINA SSHD 2.15.0 sources, not
guessed): org.eclipse.jgit.ssh.apache is client-only (it exists for this
backend to act as a git client, not to host inbound SSH). org.apache.sshd's
own git-server classes (GitPackCommandFactory/GitPackCommand) only open
filesystem repositories, with no seam for our Postgres-backed
DfsRepository. So this depends on plain sshd-core and reuses JGit's
UploadPack/ReceivePack by hand, exactly as GitRoutes.kt already does for
HTTP - the SSH-specific code is a thin CommandFactory/Command pair.

- SshPublicKeysTable + SshKeyService: register/list/remove a key,
  fingerprint-based lookup for the authenticator.
- com.mdeo.backend.git.ssh: GitSshServer (owns the listener), a
  PublickeyAuthenticator resolving offered keys to users, a CommandFactory
  parsing exec requests and checking the same read/write/admin permissions
  the HTTP routes check, and a Command driving UploadPack/ReceivePack
  against the command's streams with identical configuration to GitRoutes
  (size limits, object checking, pre-receive hook, post-push side effects).
  Command.start() spawns its own thread and runBlocking()s into
  GitRepositoryService's suspend API, per MINA SSHD's own contract that
  start() must not block the session's I/O thread.
- Extracted parseProjectIdFromGitPath as a small shared helper, since SSH's
  exec argument can carry a leading slash HTTP's route parameter never has.
- GitConfig gains sshPort (default 2222) and an optional sshHostKey,
  following the same load-from-config-or-generate-with-a-warning shape
  JwtService already uses for its RSA pair.
- Workbench: an "SSH keys" section in the Account dialog, alongside access
  tokens and change password.
- k8s: a second Service/container port for 2222, explicitly flagged in a
  comment as pod-to-pod only - the existing Gateway API HTTPRoute is
  L7-only and can't carry SSH, so external reachability needs a separate
  L4 path someone with cluster access should add. A Terraform-generated
  host key (mirroring the existing JWT key pattern) for a stable identity
  across pod restarts.

Two real bugs found only through live testing over the actual SSH
protocol, not caught by compilation or the research above:

1. MINA SSHD's own EdDSA support silently only recognizes key objects a
   registered EdDSA-capable security provider produced - a plain JDK
   KeyPairGenerator.getInstance("Ed25519") key looks identical but fails
   signature operations with "no resolved signatures available" during key
   exchange, and KeyUtils.getFingerPrint throws "EdDSA provider not
   supported" outright. This would have broken both the ephemeral host key
   and every ed25519 client key (the modern ssh-keygen default) with no
   compile-time or unit-test signal. Fixed by adding bcprov-jdk18on -
   MINA SSHD auto-detects and registers it once present, and client key
   parsing (AuthorizedKeyEntry) picks it up transparently; only the
   server's own host-key generation needed a code change, to explicitly
   request the "BC" provider rather than whatever the JVM resolves first.
2. SshGitPackCommand copied setBiDirectionalPipe(false) from GitRoutes.kt
   without adjusting for the transport difference: HTTP splits ref
   advertisement (GET /info/refs) from the exchange (POST
   git-upload-pack), so the exchange half must skip re-advertising: false
   is correct there. SSH's exec channel is one continuous stream with no
   separate advertisement step, so upload()/receive() need to send the
   advertisement themselves, which is what the default (true) makes them
   do. With false, the command hung forever waiting for input that would
   never arrive, since the client was equally waiting for an advertisement
   the server would never send.

Verified live end-to-end after both fixes, using the real git and ssh-keygen
CLIs against the running dev stack: clone and push with a registered
ed25519 key, an unregistered key correctly rejected, and a write-only
project member's push scoped identically to the HTTP behavior already
verified in mde-optimiser#38 - an unrelated file goes through, a .mdeo change is
rejected with the same admin-permission message.
…ic CAS

FileService.writeFile's edit path bumped version in place instead of
consulting the durable file_version_counters table, so a delete followed
by recreate could hand out a version already used by a prior edit.
rename() and its directory-children helper had the same problem. All
three now go through nextVersion() like file creation already did.

writeFile's expectedVersion check was a plain SELECT-then-UPDATE with no
enforcement in the UPDATE itself, so two concurrent writers passing the
same expectedVersion could both succeed, with the second silently
overwriting the first. The UPDATE's WHERE clause now includes the
expected version and checks the affected-row count, making the check
atomic; unconditional writes without expectedVersion are unaffected.

Also stop putting the raw token in the clone URL in the personal access
token docs example, since that persists it in shell history and
remote.origin.url; point at git's own password prompt or a credential
helper instead.
Copilot AI review requested due to automatic review settings September 5, 2026 20:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@amirrza777

Copy link
Copy Markdown
Contributor Author

Pushed a follow-up commit addressing two Copilot findings from its review summary that weren't posted as inline threads:

  • FileService's version counter went stale outside of file creation. writeFile's edit path and rename() (including the directory-children helper) were bumping version in place instead of consulting file_version_counters, so a delete followed by a recreate could hand out a version number a pre-deletion edit had already used. All three paths now go through the same nextVersion() counter that file creation already used.
  • writeFile's expectedVersion check wasn't an atomic compare-and-set. It was a plain read-then-update with no enforcement in the UPDATE itself, so two concurrent writers passing the same expectedVersion could both succeed, with the second silently clobbering the first. The UPDATE's WHERE clause now includes the expected version and checks the affected-row count. Unconditional writes (no expectedVersion) are unaffected. Verified live with two independent WebSocket connections racing 30 concurrent writes at the same expected version - exactly one winner every time.
  • Docs: the personal-access-token clone example put the raw token in the URL (https://<user>:<token>@host/...), which persists it in shell history and remote.origin.url. Now shows a credential-free URL and points at git's own password prompt or a credential helper instead.

Also replied on and resolved the X-Forwarded-For thread now that ClientAddress.kt is fully wired through both AuthRoutes and GitRoutes.

The pre-receive/ref-CAS ordering thread is left open as previously discussed - it's a separate, still-accepted trade-off from the publishedFileVersions fix.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical correctness and security issues can cause data loss, conflict bypasses, token caching, and ineffective rate limiting.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

platform/backend/src/main/kotlin/com/mdeo/backend/git/GitRepositoryService.kt:385

  • This snapshot comparison is not atomic with the writes below. At the configured READ_COMMITTED isolation it does not lock the rows, so a workbench write can commit immediately after this check and then be overwritten by the unconditional writeFile call. Use a database lock shared by all project mutations, or make every pushed update/delete conditional on the captured versions and roll back on any conflict.
  • Files reviewed: 68/68 changed files
  • Comments generated: 14
  • Review effort level: Balanced

Comment on lines +96 to +100
const paths = [...this.fileTreeCache.entries()]
.filter(([, info]) => info.type === FileType.File)
.map(([path]) => path);
this.fileTreeCache.clear();

Comment on lines +522 to +527
// A version conflict says this client's idea of the file is stale, so
// whatever is cached for it has to go: keeping it would send the same
// rejected version again on the next attempt.
if (this.cachedProjectId === projectId && code === FileSystemErrorCode.VersionConflict) {
this.fileTreeCache.delete(normalizedPath);
}
Comment on lines +363 to +366
val changedPlugins = pushedPlugins
?.takeIf { it != pluginService.getProjectPluginUrls(projectId).sorted() }
if (changedPlugins != null && !callerIsProjectAdmin) {
return "changing a project's plugins ($projectFilePath) requires project admin permission"
// large project should not invalidate the rest of it.
continue
}
val result = fileService.writeFile(projectId, path, content, create = true, overwrite = true)
Comment on lines +245 to +249
logger.info("Issued git OAuth access token '{}' for user {}", token.name, redemption.userId)
call.respondText(
"""{"access_token":"${token.token}","token_type":"Bearer","scope":"git"}""",
ContentType.Application.Json
)
Comment on lines +125 to +126
oauthAuthorizePath = System.getenv("GIT_OAUTH_AUTHORIZE_PATH") ?: "/oauth/authorize",
oauthTokenPath = System.getenv("GIT_OAUTH_TOKEN_PATH") ?: "/api/oauth/token"
// in the files table do not need to be walked. Git infers them.
val dirCache = DirCache.newInCore()
val builder = dirCache.builder()
for ((path, content) in files.map { it.path to it.content } + (projectFilePath to projectFileContent)) {
Comment on lines +555 to +558
val path = row[FilesTable.path].trimStart('/')
if (path.isEmpty() || path.endsWith(RESERVED_FILE_EXTENSION, ignoreCase = true)) {
return@mapNotNull null
}
Comment on lines +307 to +311
val parsed = runCatching { URI(uri) }.getOrNull() ?: return false
if (!parsed.scheme.equals("http", ignoreCase = true)) {
return false
}
return parsed.host in setOf("127.0.0.1", "::1", "[::1]", "localhost")
Comment on lines +246 to +250
val newVersion = nextVersion(projectId, normalizedPath)
if (expectedVersion != null) {
// The precondition check above is not by itself a compare-and-set: another
// writer could commit between that SELECT and this UPDATE. Folding the same
// condition into the UPDATE's own WHERE clause makes the database enforce it
@amirrza777

Copy link
Copy Markdown
Contributor Author

Hello Dear @szschaler and @nk-coding,

After our last meeting I made a deep dive into the code, and found that he design itself isn't broken. The real issue is process: a lot of new security-critical code (auth, tokens, SSH, OAuth) was built and merged in one large batch rather than smaller reviewed pieces, a fix made in one place wasn't applied everywhere the same bug could occur, the same security logic exists in two unsynchronized copies (HTTP and SSH), and almost none of it has automated test coverage, so nothing catches this kind of mistake except another manual review. It's a scope-and-rigor problem more than a design flaw, though it's fair to separately ask whether this much custom-built infrastructure was worth it.

So I have come up with three options we could proceed with:

Option A — Fix forward, add a verification gate. Fix the critical issues found, then require an integration test for concurrent edits and a human read-through of the auth-critical code before this merges. Keeps the current design intact but doesn't address the duplicated logic or the underlying habit of fixes not propagating.

Option B — Split the PR before it merges. Since nothing has reached main yet, split this single PR into pieces — merge only HTTP clone/push with password and token auth (the original ask) first, and hold SSH support and OAuth sign-in back for their own separately reviewed PRs. Reduces how much new security surface lands in main at once.

Option C — Revisit the original design trade. The "MDEO as its own git server" choice has cost six custom-built subsystems that GitHub already handles safely. Worth revisiting, with real numbers, whether that trade still makes sense — the most disruptive option, but it directly engages your original concern.

Will wait for your answer and suggestions before proceeding.

@szschaler

Copy link
Copy Markdown
Member

Thanks, @amirrza777. From my perspective, Option A seems the most sensible choice, given what we already have now. @nk-coding WDYT?

@nk-coding

Copy link
Copy Markdown
Collaborator

Thanks, @amirrza777. From my perspective, Option A seems the most sensible choice, given what we already have now. @nk-coding WDYT?

definitely A

@amirrza777

Copy link
Copy Markdown
Contributor Author

Ok then I will proceed with A

identity bug found during an independent review of the branch

applyCommitToProject checked the whole push's file versions once, up front,
then wrote each changed file through fileService.writeFile without passing
the expectedVersion the Sept 5 CAS fix added specifically for this: a
workbench edit landing in the gap between that snapshot and this push's own
per-file write was silently overwritten instead of causing a rejection.
delete() gained the same expectedVersion parameter so the push's delete loop
is guarded the same way. Verified live and by a new Testcontainers-backed
test: a concurrent edit deterministically wins, and the push is cleanly
rejected instead of clobbering it.

Separately, GitRoutes.authorizeGit cleared the auth rate limiter's failure
count using the client-supplied Basic-auth username even when a personal
access token (which proves nothing about that field) is what actually
authenticated - anyone holding a valid token of their own could clear an
arbitrary victim username's lockout on demand. Now keyed on the account that
actually authenticated. Verified live: a forged "victim:attacker's-token"
login no longer resets victim's failure count.

Also: PersonalAccessTokenService.verifyToken no longer stamps lastUsedAt on
a hash match alone - moved to a new recordTokenUsed, called only once scope
and permission have both passed, mirroring SshKeyService.recordKeyUsed.
FileService.delete and rename's source path now go through checkNotReserved
like every other mutating method already did.

An "integer overflow near the storage cap" finding from the same review did
not hold up on inspection - Postgres caps a single bytea value at ~1GB,
well under where it would trigger - so nothing was changed there.

Adds this repo's first Postgres-backed test (Testcontainers), for the one
place a pure unit test can't reach: the race depends on real transaction
isolation, not just the CAS logic in isolation.
Copilot AI review requested due to automatic review settings September 9, 2026 18:56

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@szschaler

Copy link
Copy Markdown
Member

@amirrza777 could you please respond to and close any conversations that have been addressed?

@nk-coding would you be able to review the latest version to see if this can be merged?

@nk-coding

Copy link
Copy Markdown
Collaborator

@amirrza777 could you please respond to and close any conversations that have been addressed?

@nk-coding would you be able to review the latest version to see if this can be merged?

https://claude.ai/artifact/PxPsrh9jnSRcuoRpcQMJ4y
it seems like most stuff is done, but there are still several open ones

@szschaler

Copy link
Copy Markdown
Member

Thanks. @amirrza777 can you please respond to these and fix the remaining issues?

independent re-check found on top of them

All verified against the actual code at the reviewed head before being
fixed, and re-verified live or by test afterward - see the reasoning per
item below rather than taking the review ledger's claims on faith.

Blocker - existing files regressed to version 1 after upgrade
(FileVersionCountersTable had no backfill from files.version, so any
pre-existing file's first edit handed back version 1 regardless of its real
version). DatabaseFactory now seeds the counter table from FilesTable on
every startup (ON CONFLICT DO NOTHING, safe to rerun). Verified live: seeded
a file at version 9 with no counter row, restarted the backend, confirmed
the counter backfilled to 9 and the next edit correctly returned 10. Two
new Testcontainers tests cover the backfill and its idempotency.

Rate limiter check-and-record was not atomic, and a successful login
cleared the whole per-address window. Both close under one fix:
AuthRateLimiter.isAllowed/recordFailure/recordSuccess become
tryReserve/recordSuccess - every attempt reserves a slot atomically before
verification runs (closing the race concurrent requests could exploit),
and a success releases only that one reservation rather than clearing
a whole window, so it can never wipe out unrelated accumulated failures on
either the username or the address side. This also means recordSuccess in
GitRoutes goes back to keying on the raw Basic-auth username rather than
the resolved user.username: releasing the field that was actually reserved
is what keeps the accounting correct, including under the token-spoofing
scenario the previous keying choice was defending against - the reserve
now bounds that exposure to at most one reservation's worth, not a full
clear. Verified live: 4 real failures against a throwaway username, then
one successful request that spoofed that same username via a valid token
as password, then a further real failure and lockout landing exactly on
the 6th attempt - proving the spoofed success granted no extra attempts.
New AuthRateLimiterTest cases include a genuinely multi-threaded test
(50 real threads racing tryReserve) proving the atomicity fix.

writeFile's version counter advanced even when the guarded compare-and-set
it fed into then failed, wasting a version number on every lost race.
Fixed by taking a FOR UPDATE lock on the file row before deciding whether
to proceed, so nextVersion() is only called once the version check has
already passed under a lock that rules out anyone else changing the row
before this transaction commits - not just avoiding the waste, closing the
underlying race entirely.

A push that replaces a file with a directory at the same path could orphan
the new nested file: writes ran before deletes, and
ensureParentDirectories only checked a row existed at the parent path, not
that it was actually a directory. Deletes now run first, and
ensureParentDirectories rejects a file found where a directory is needed
instead of silently nesting under it. Verified live: created a file
`foo`, pushed a commit replacing it with `foo/` containing `foo/bar`,
confirmed `foo` is a real directory afterward and `foo/bar` is reachable
through readdir, not just present as an orphaned row.

Pushed *new* files were not version-guarded - the per-file expectedVersion
only applied to paths the push's snapshot already knew about, so a
workbench create landing in the same window for a brand-new path was still
overwritten unconditionally. writeFile's overwrite flag in the push loop
is now conditioned on whether the path was in the snapshot, so a genuine
collision on a new path fails with FILE_EXISTS instead of applying
silently. New Testcontainers test covers this specifically, since the
existing race test only covered edits.

Smaller items, each verified: OAuth token responses now carry
Cache-Control: no-store and Pragma: no-cache per RFC 6749; a redirect URI
carrying a fragment is now rejected (verified live via
/api/oauth/request-info) rather than silently breaking the code exchange;
a pushed plugin-selection change is now read inside the same transaction
as the rest of the push instead of before it, closing a narrow
admin-push-reverts-a-concurrent-plugin-change window; the reserved
.mdeo-extension check on git reads now checks every path segment, matching
FileService's own check, instead of only the full path's suffix.

Frontend: the client dropped a file's cached version entirely on both a
push notification and a version conflict, so a retry after either had no
expectedVersion to send and silently overwrote whatever caused the
conflict. Both paths now keep the (possibly stale) version and clear only
the content, forcing the next read to fetch fresh state while still
leaving a real version for the next write to be conditioned on.

Documented rather than partially fixed: a caller can lock an arbitrary
username out of login and git with five wrong passwords from one address,
no authentication needed - inherent to any per-username lockout without a
CAPTCHA or similar, and the review's own suggested mitigation (keying on
username+address) would not have closed it, since the same single caller
from the same single address exhausts that too. Recorded as an accepted,
conscious trade-off directly on the constant it concerns, not papered over
with a change that would not actually alter the outcome.

Declined: the review's "integer overflow near the storage cap" claim
(PostgresPackReadableChannel) does not hold up - Postgres caps a single
bytea value at ~1GB, well under where that overflow would trigger - so
nothing was changed there.
Copilot AI review requested due to automatic review settings September 17, 2026 14:26

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@szschaler

Copy link
Copy Markdown
Member

Thanks, @amirrza777 . @nk-coding can you have a quick look over these changes and approve the PR if happy?

@szschaler
szschaler requested a review from nk-coding September 18, 2026 13:07

@nk-coding nk-coding left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code looks fine, Claude also said all the review comments are fixed, I will test the functionality a bit manually when I'm home and approve then

…sh leaves

The HEAD link was guarded on ObjectDatabase.exists(), which is a hardcoded
`return true`, so it never ran: HEAD stayed unborn and `git clone --depth N`
(and --single-branch) silently produced an empty repository on both transports.
Linking it also needs scanAllRefs to list a symbolic ref among the repository's
refs and not only as symbolic, or JGit's RefMap throws and every git request
500s. Reclaiming rejected-push storage needs a garbage TTL: at the collector's
default the unreachable objects were only repacked as UNREACHABLE_GARBAGE and
kept, so storage grew by a pack per rejected push and a project driven past its
limit stayed there. It now holds at about one push's worth.
Copilot AI review requested due to automatic review settings September 20, 2026 20:35

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@nk-coding nk-coding left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

two small issues which I fixed myself

@nk-coding

Copy link
Copy Markdown
Collaborator

@szschaler do you want to merge this?

@szschaler

Copy link
Copy Markdown
Member

I was assuming @amirrza777 would do it, but please do go ahead.

@nk-coding
nk-coding merged commit 361a9a4 into mde-optimiser:main Sep 25, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Git Sync: scope the design before implementation

4 participants