g1t/services/repos/src/commit_file.rs

171 lines7,457 bytesCodeBlame
1//! 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 }
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 };
63 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);
124 let mut objects: Vec<(ObjectKind, Vec<u8>)> = vec![(ObjectKind::Blob, blob)];
125 objects.extend(merged.objects.into_iter().map(|bytes| (ObjectKind::Tree, bytes)));
126 objects.push((ObjectKind::Commit, commit));
127 let access = git.access(Scope::Write).await?;
128 // Only if the branch is still not there.
129 let pushed = land::push_pack(&access, &a.branch, None, &commit_id, write_pack(&objects)).await?;
130 self.refs_moved(&repo.id).await;
131
132 let git_ref = format!("refs/heads/{}", a.branch);
133 let mut target = self.audit_target(&a.repo).await?;
134 target.git_ref = Some(git_ref.clone());
135 let mut entry = NewAuditEntry::new(
136 AuditActor::of(&a.actor),
137 "git.push",
138 Surface::Git,
139 target,
140 &Decision::allow("person"),
141 g1t_contracts::new_id("req", now_ms()),
142 );
143 if let Err(reason) = pushed {
144 entry.result = Some("conflict".to_owned());
145 entry.message = Some(reason.clone());
146 self.record_git(entry).await;
147 return Ok(Outcome::fail(FailureCode::Conflict, format!("{} could not be created: {reason}", a.branch)));
148 }
149 entry.result = Some("ok".to_owned());
150 self.record_git(entry).await;
151 self.publish_push(&repo, &git_ref, None, &commit_id, Some(a.actor.id.clone())).await?;
152 Ok(Outcome::Ok(CommittedFile {
153 branch: a.branch,
154 commit: commit_id,
155 }))
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::valid_path;
162
163 #[test]
164 fn only_plain_relative_paths_are_written() {
165 assert!(valid_path(".g1t/workflows/ci.yml"));
166 assert!(valid_path("README.md"));
167 for path in ["", "/etc/passwd", "a/../b", "a//b", ".git/config", "a/./b", "dir/", "a\\b"] {
168 assert!(!valid_path(path), "{path}");
169 }
170 }
171}