Skip to content

g1t/services/repos/src/commit_file.rs

195 lines8,606 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Fast pages, required checks on the branch, self-hosted runners, honest incidents1//! One file, committed on a new branch without a sandbox: how g1t proposes
2//! a change on someone's behalf, such as a starter workflow, which then
3//! becomes a pull request they can read, change and merge.
4//!
5//! The new tree is the default branch's head with the file put in place.
6//! Only the trees on the way to it are rewritten (as catching up does), and
7//! the blob, those trees and one commit by the person asking are pushed as
8//! a pack to a branch that must not exist yet.
9
10use std::collections::{BTreeSet, HashMap};
11
12use g1t_contracts::access::Capability;
13use g1t_contracts::audit::{AuditActor, NewAuditEntry, Surface};
14use g1t_contracts::credentials::Decision;
15use g1t_contracts::repos::{CommitFileArgs, CommittedFile, EntryKind, TreeEntry, is_valid_branch_name};
16use g1t_contracts::{FailureCode, Outcome};
17use g1t_kit::now_ms;
18use g1t_scan::pack::{ObjectKind, object_id, write_pack};
19use worker::Result;
20
21use crate::catch_up::{Change, Signature, ancestors, commit_object, merge_tree, read_dirs};
22use crate::registry::{can_write, store_key};
23use crate::store::{GitRepo, GitStore, Scope};
24use crate::{Repos, UNVERIFIED, land, not_found};
25
26/// The largest file this writes.
27const MAX_CONTENT_BYTES: usize = 64 * 1024;
28
29/// Whether `path` is somewhere a file can be written: relative, without
30/// empty, `.` or `..` parts, and not inside `.git`.
31pub(crate) fn valid_path(path: &str) -> bool {
32 !path.is_empty()
33 && path.len() <= 400
34 && !path.starts_with('/')
35 && !path.ends_with('/')
36 && path.split('/').all(|part| !part.is_empty() && part != "." && part != ".." && part != ".git")
37 && !path.chars().any(|c| c.is_control() || c == '\\')
38}
39
40impl<S: GitStore> Repos<S> {
41 pub(crate) async fn commit_file(&self, a: CommitFileArgs) -> Result<Outcome<CommittedFile>> {
42 let actor = Some(a.actor.clone());
43 let Some(repo) = self.readable(&a.repo, &actor).await? else {
44 return Ok(not_found());
45 };
46 if !can_write(&repo, &actor) {
47 return Ok(Outcome::fail(
48 FailureCode::Forbidden,
49 g1t_contracts::access::needs(Capability::Push, &format!("{}/{}", repo.namespace, repo.name)),
50 ));
51 }
52 if !a.actor.verified {
53 return Ok(Outcome::fail(FailureCode::Forbidden, UNVERIFIED));
54 }
55 if let Some((code, message)) = crate::lifecycle::archived_refusal(&repo) {
56 return Ok(Outcome::fail(code, message));
57 }
Merge branch 'worktree-agent-a2013627e5ea4ab13'58 // Moving between namespaces: wait for it (moves.rs).
59 let repo = match self.unpaused(repo).await? {
60 Ok(repo) => repo,
61 Err((code, message)) => return Ok(Outcome::fail(code, message)),
62 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents63 if !is_valid_branch_name(&a.branch) || a.branch == repo.default_branch {
64 return Ok(Outcome::fail(FailureCode::Invalid, format!("{} cannot be the new branch's name.", a.branch)));
65 }
66 if !valid_path(&a.path) {
67 return Ok(Outcome::fail(FailureCode::Invalid, format!("{} is not a path a file can be written to.", a.path)));
68 }
69 if a.content.len() > MAX_CONTENT_BYTES {
70 return Ok(Outcome::fail(FailureCode::Invalid, "The file is too large to write this way."));
71 }
72 let message = a.message.trim();
73 if message.is_empty() {
74 return Ok(Outcome::fail(FailureCode::Invalid, "A commit needs a message."));
75 }
76
77 let git = self.store.open(&store_key(&repo)).await?;
78 if git.branches().await?.iter().any(|branch| branch.name == a.branch) {
79 return Ok(Outcome::fail(FailureCode::Conflict, format!("A branch named {} already exists.", a.branch)));
80 }
81 let history = git.log(&repo.default_branch, 1).await?;
82 let Some(head) = history.first() else {
83 return Ok(Outcome::fail(
84 FailureCode::Conflict,
85 format!("{} has no commits yet. Push a first commit, then try again.", repo.default_branch),
86 ));
87 };
88 let dirs: BTreeSet<String> = ancestors(&a.path).map(str::to_owned).collect();
89 let read = read_dirs(&git, &head.tree_hash, &dirs).await?;
90 let (parent, name) = a.path.rsplit_once('/').unwrap_or(("", a.path.as_str()));
91 let exists = read
92 .get(parent)
93 .is_some_and(|(_, entries)| entries.iter().any(|entry| entry.name == name));
94 if exists {
95 return Ok(Outcome::fail(FailureCode::Conflict, format!("{} already exists on {}.", a.path, repo.default_branch)));
96 }
97
98 let blob = a.content.clone().into_bytes();
99 let blob_id = object_id(ObjectKind::Blob, &blob);
100 let trees: HashMap<String, Vec<TreeEntry>> = read.into_values().collect();
101 let change = Change {
102 path: a.path.clone(),
103 entry: Some((EntryKind::Blob, blob_id)),
104 };
105 let merged = match merge_tree(&head.tree_hash, &trees, &[change]) {
106 Ok(merged) => merged,
107 Err(why) => {
108 return Ok(Outcome::fail(FailureCode::Conflict, format!("g1t could not write {}: {why}.", a.path)));
109 }
110 };
111
112 let author = self.commit_identity(&a.actor).await;
113 let commit = commit_object(
114 &merged.tree,
115 &[&head.hash],
116 &Signature {
117 name: &author.name,
118 email: &author.email,
119 seconds: now_ms() / 1000,
120 },
121 message,
122 );
123 let commit_id = object_id(ObjectKind::Commit, &commit);
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar124 // Push protection, as for git: a secret nobody let through stops it.
125 if let Some(refusal) = self.protect_file(&repo, &a.actor, &a.path, a.content.as_bytes(), &commit_id).await {
126 return Ok(Outcome::fail(FailureCode::Forbidden, refusal));
127 }
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge128 // The rules of the new branch, as for a push of this commit.
129 let change = g1t_rules::push::RefChange {
130 git_ref: format!("refs/heads/{}", a.branch),
131 old: None,
132 new: Some(commit_id.clone()),
133 fast_forward: None,
134 commits: vec![crate::rules::made_commit(
135 &commit_id,
136 message,
137 &author.email,
138 1,
139 vec![g1t_contracts::rules::FileChange { path: a.path.clone(), size: Some(blob.len() as u64), deleted: false }],
140 )],
141 complete: true,
142 };
143 if let crate::rules::Ruled::Refused { message, .. } =
144 self.check_changes(&repo, &a.actor, g1t_contracts::rules::Action::Commit, vec![change]).await?
145 {
146 return Ok(Outcome::fail(FailureCode::Forbidden, message));
147 }
Fast pages, required checks on the branch, self-hosted runners, honest incidents148 let mut objects: Vec<(ObjectKind, Vec<u8>)> = vec![(ObjectKind::Blob, blob)];
149 objects.extend(merged.objects.into_iter().map(|bytes| (ObjectKind::Tree, bytes)));
150 objects.push((ObjectKind::Commit, commit));
151 let access = git.access(Scope::Write).await?;
152 // Only if the branch is still not there.
153 let pushed = land::push_pack(&access, &a.branch, None, &commit_id, write_pack(&objects)).await?;
154 self.refs_moved(&repo.id).await;
155
156 let git_ref = format!("refs/heads/{}", a.branch);
157 let mut target = self.audit_target(&a.repo).await?;
158 target.git_ref = Some(git_ref.clone());
159 let mut entry = NewAuditEntry::new(
160 AuditActor::of(&a.actor),
161 "git.push",
162 Surface::Git,
163 target,
164 &Decision::allow("person"),
165 g1t_contracts::new_id("req", now_ms()),
166 );
167 if let Err(reason) = pushed {
168 entry.result = Some("conflict".to_owned());
169 entry.message = Some(reason.clone());
170 self.record_git(entry).await;
171 return Ok(Outcome::fail(FailureCode::Conflict, format!("{} could not be created: {reason}", a.branch)));
172 }
173 entry.result = Some("ok".to_owned());
174 self.record_git(entry).await;
175 self.publish_push(&repo, &git_ref, None, &commit_id, Some(a.actor.id.clone())).await?;
176 Ok(Outcome::Ok(CommittedFile {
177 branch: a.branch,
178 commit: commit_id,
179 }))
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::valid_path;
186
187 #[test]
188 fn only_plain_relative_paths_are_written() {
189 assert!(valid_path(".g1t/workflows/ci.yml"));
190 assert!(valid_path("README.md"));
191 for path in ["", "/etc/passwd", "a/../b", "a//b", ".git/config", "a/./b", "dir/", "a\\b"] {
192 assert!(!valid_path(path), "{path}");
193 }
194 }
195}

This file's history is long; its oldest lines are credited to the oldest commit read.