Mirror of github.com/getsigit/si.
Mirrored from https://github.com/getsigit/si.git
Synced Nov 24, 08:15 UTC
Add si repo clone and a git credential helper
si repo clone OWNER/NAME runs git clone with a credential helper that points back at si, so the token is never put in the URL or written to disk. Extra arguments after -- go to git. si auth git-credential implements git's helper protocol. On get, for the configured host only, it mints a short-lived git password and prints it. store and erase do nothing, and it prints nothing when nobody is signed in so git moves on to the next helper. si auth setup-git writes the helper into the global git config, like gh auth setup-git. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Seto Elkahfi committed
Oct 28, 2026 at 10:11 UTC
ffcb7e870cbf1ed3d18aa319475c672d57140a56
6 files changed
+332
-4
crates/cli/src/cli.rs
+27
@@ -76,6 +76,22 @@ pub enum AuthCommand {
76
Logout,
77
/// Show who is currently signed in.
78
Status,
79
+ /// Let git use your sigit.si sign-in for clones and fetches, by adding a
80
+ /// credential helper to your global git config.
81
+ SetupGit,
82
+ /// Git's credential helper protocol. Git runs this; you don't need to.
83
+ #[command(hide = true)]
84
+ GitCredential {
85
+ #[arg(value_enum)]
86
+ operation: GitCredentialOperation,
87
+ },
88
+}
89
+
90
+#[derive(Clone, Copy, clap::ValueEnum)]
91
+pub enum GitCredentialOperation {
92
+ Get,
93
+ Store,
94
+ Erase,
95
}
96
97
#[derive(clap::Subcommand)]
@@ -107,6 +123,17 @@ pub enum RepoCommand {
123
},
124
/// Open a repository in your browser.
125
Browse { repo: Option<String> },
126
+ /// Clone a repository with git, signing in through `si` so the token
127
+ /// never lands in the URL or on disk.
128
+ Clone {
129
+ /// OWNER/NAME.
130
+ repo: String,
131
+ /// Directory to clone into.
132
+ dir: Option<String>,
133
+ /// Extra arguments for `git clone`, after `--`.
134
+ #[arg(last = true)]
135
+ git_args: Vec<String>,
136
+ },
137
}
138
139
#[derive(clap::Subcommand)]
crates/cli/src/commands/auth.rs
+41
-2
@@ -1,7 +1,13 @@
1
use {
2
- crate::{cli::AuthCommand, config, context::Ctx, ui},
3
- anyhow::{anyhow, Result},
2
+ crate::{
3
+ cli::{AuthCommand, GitCredentialOperation},
4
+ config,
5
+ context::Ctx,
6
+ credential, ui,
7
+ },
8
+ anyhow::{anyhow, Context, Result},
9
sigit_si_api::{account::incomplete_reason, models::AccountStatus},
10
+ std::io::{self, Write},
11
};
12
13
pub async fn run(ctx: &Ctx, command: AuthCommand) -> Result<()> {
@@ -9,9 +15,42 @@ pub async fn run(ctx: &Ctx, command: AuthCommand) -> Result<()> {
15
AuthCommand::Login { email } => login(ctx, email).await,
16
AuthCommand::Logout => logout(ctx).await,
17
AuthCommand::Status => status(ctx).await,
18
+ AuthCommand::SetupGit => setup_git(ctx),
19
+ AuthCommand::GitCredential { operation } => git_credential(ctx, operation).await,
20
}
21
}
22
23
+fn setup_git(ctx: &Ctx) -> Result<()> {
24
+ let exe = std::env::current_exe().context("Could not locate the `si` executable.")?;
25
+ let base_url = ctx.client.base_url();
26
+ credential::setup_global_helper(base_url, &exe)?;
27
+ ui::success(format!(
28
+ "Git will now sign in to {} through `si`.",
29
+ ui::highlight(base_url)
30
+ ));
31
+ Ok(())
32
+}
33
+
34
+/// Answer git's credential protocol. `store` and `erase` do nothing, since the
35
+/// password is minted on demand and never kept. Anything this helper can't
36
+/// answer for stays silent so git moves on to the next helper.
37
+async fn git_credential(ctx: &Ctx, operation: GitCredentialOperation) -> Result<()> {
38
+ if !matches!(operation, GitCredentialOperation::Get) {
39
+ return Ok(());
40
+ }
41
+
42
+ let request = credential::parse_request(io::stdin().lock());
43
+ if ctx.client.token().is_none() || !credential::is_for_host(&request, ctx.client.base_url()) {
44
+ return Ok(());
45
+ }
46
+
47
+ let minted = ctx.client.git_credential().await?;
48
+ let mut stdout = io::stdout().lock();
49
+ stdout.write_all(credential::response(&minted.username, &minted.git_token).as_bytes())?;
50
+ stdout.flush()?;
51
+ Ok(())
52
+}
53
+
54
async fn login(ctx: &Ctx, email: Option<String>) -> Result<()> {
55
let email = match email {
56
Some(email) => email,
crates/cli/src/commands/repo.rs
+21
-1
@@ -2,13 +2,25 @@ use {
2
crate::{
3
cli::RepoCommand,
4
context::Ctx,
5
+ credential,
6
+ git::RepoSlug,
7
ui::{self, prompt},
8
},
7
- anyhow::Result,
9
+ anyhow::{Context, Result},
10
sigit_si_api::NewRepository,
11
};
12
13
pub async fn run(ctx: &Ctx, command: RepoCommand) -> Result<()> {
14
+ // A public repository clones without signing in.
15
+ if let RepoCommand::Clone {
16
+ repo,
17
+ dir,
18
+ git_args,
19
+ } = command
20
+ {
21
+ return clone(ctx, &repo, dir.as_deref(), &git_args);
22
+ }
23
+
24
ctx.require_token()?;
25
26
match command {
@@ -22,9 +34,17 @@ pub async fn run(ctx: &Ctx, command: RepoCommand) -> Result<()> {
34
yes,
35
} => create(ctx, name, private, description, yes).await,
36
RepoCommand::Browse { repo } => browse(ctx, repo).await,
37
+ RepoCommand::Clone { .. } => unreachable!("handled before the token check"),
38
}
39
}
40
41
+fn clone(ctx: &Ctx, repo: &str, dir: Option<&str>, git_args: &[String]) -> Result<()> {
42
+ let slug = RepoSlug::parse(repo)?;
43
+ let exe = std::env::current_exe().context("Could not locate the `si` executable.")?;
44
+ let args = credential::clone_args(ctx.client.base_url(), &exe, &slug, dir, git_args);
45
+ credential::clone(&args)
46
+}
47
+
48
async fn list(ctx: &Ctx) -> Result<()> {
49
let repos = ctx.client.repos().await?;
50
ui::emit(ctx.json, &repos, |repos| ui::render::repos(repos))
crates/cli/src/credential.rs
new
+241
@@ -0,0 +1,241 @@
1
+//! Git's credential helper protocol, and the `git` command lines built around
2
+//! it.
3
+//!
4
+//! Git asks a helper for a password by writing `key=value` lines to its stdin,
5
+//! ended by a blank line, and reads `key=value` lines back. `si` answers for
6
+//! the sigit.si host only, with a short-lived token minted on demand, so no
7
+//! credential is ever stored.
8
+
9
+use {
10
+ crate::git::{hosts_match, RepoSlug},
11
+ anyhow::{anyhow, Context, Result},
12
+ std::{collections::HashMap, io::BufRead, path::Path, process::Command},
13
+};
14
+
15
+/// The attributes of one credential request, e.g. `protocol`, `host`, `path`.
16
+pub type Request = HashMap<String, String>;
17
+
18
+/// Read a request up to the first blank line, or the end of input.
19
+pub fn parse_request(input: impl BufRead) -> Request {
20
+ let mut request = Request::new();
21
+ for line in input.lines().map_while(|line| line.ok()) {
22
+ let line = line.trim_end_matches('\r');
23
+ if line.is_empty() {
24
+ break;
25
+ }
26
+ if let Some((key, value)) = line.split_once('=') {
27
+ request.insert(key.to_string(), value.to_string());
28
+ }
29
+ }
30
+ request
31
+}
32
+
33
+/// Whether the request is for `base_url`, such as `https://sigit.si`. A
34
+/// request for another host is none of our business, and a request over a
35
+/// different scheme must not get a token that was meant for the secure one.
36
+pub fn is_for_host(request: &Request, base_url: &str) -> bool {
37
+ let Some(host) = request.get("host") else {
38
+ return false;
39
+ };
40
+ if !hosts_match(host, base_url) {
41
+ return false;
42
+ }
43
+ match (request.get("protocol"), base_url.split_once("://")) {
44
+ (Some(protocol), Some((scheme, _))) => protocol.eq_ignore_ascii_case(scheme),
45
+ _ => true,
46
+ }
47
+}
48
+
49
+/// The reply git expects: two attributes and a blank line.
50
+pub fn response(username: &str, password: &str) -> String {
51
+ format!("username={username}\npassword={password}\n\n")
52
+}
53
+
54
+/// `credential.<base>.helper`, the config key that scopes a helper to one
55
+/// host.
56
+pub fn helper_key(base_url: &str) -> String {
57
+ format!("credential.{base_url}.helper")
58
+}
59
+
60
+/// The helper command git runs, as a shell snippet: git appends the operation.
61
+pub fn helper_command(exe: &Path) -> String {
62
+ let exe = exe.to_string_lossy().replace('\'', r"'\''");
63
+ format!("!'{exe}' auth git-credential")
64
+}
65
+
66
+/// The arguments for `git clone`. The leading empty `helper` entry clears any
67
+/// helper inherited from the user's config, so the one that follows is the only
68
+/// one asked.
69
+pub fn clone_args(
70
+ base_url: &str,
71
+ exe: &Path,
72
+ slug: &RepoSlug,
73
+ dir: Option<&str>,
74
+ extra: &[String],
75
+) -> Vec<String> {
76
+ let key = helper_key(base_url);
77
+ let mut args = vec![
78
+ "-c".to_string(),
79
+ format!("{key}="),
80
+ "-c".to_string(),
81
+ format!("{key}={}", helper_command(exe)),
82
+ "clone".to_string(),
83
+ ];
84
+ args.extend(extra.iter().cloned());
85
+ args.push(format!("{base_url}/{}/{}.git", slug.owner, slug.name));
86
+ args.extend(dir.map(str::to_string));
87
+ args
88
+}
89
+
90
+fn git() -> Command {
91
+ Command::new("git")
92
+}
93
+
94
+fn not_found(error: std::io::Error) -> anyhow::Error {
95
+ if error.kind() == std::io::ErrorKind::NotFound {
96
+ anyhow!("`git` was not found on your PATH. Install git and try again.")
97
+ } else {
98
+ anyhow!("Could not run git: {error}")
99
+ }
100
+}
101
+
102
+/// Run `git clone` with the helper in place.
103
+pub fn clone(args: &[String]) -> Result<()> {
104
+ let status = git().args(args).status().map_err(not_found)?;
105
+ if status.success() {
106
+ Ok(())
107
+ } else {
108
+ Err(anyhow!("git clone failed ({status})."))
109
+ }
110
+}
111
+
112
+/// Register the helper for `base_url` in the global git config, replacing any
113
+/// earlier `si` entry. The empty entry first keeps a system-wide helper (such
114
+/// as the macOS keychain) from answering for this host as well.
115
+pub fn setup_global_helper(base_url: &str, exe: &Path) -> Result<()> {
116
+ let key = helper_key(base_url);
117
+
118
+ // Clear what we wrote before; exit code 5 only means there was none.
119
+ git()
120
+ .args(["config", "--global", "--unset-all", &key])
121
+ .status()
122
+ .map_err(not_found)?;
123
+
124
+ for value in [String::new(), helper_command(exe)] {
125
+ let status = git()
126
+ .args(["config", "--global", "--add", &key, &value])
127
+ .status()
128
+ .map_err(not_found)
129
+ .context("Could not write the global git config.")?;
130
+ if !status.success() {
131
+ return Err(anyhow!("`git config --global` failed ({status})."));
132
+ }
133
+ }
134
+ Ok(())
135
+}
136
+
137
+#[cfg(test)]
138
+mod tests {
139
+ use super::*;
140
+
141
+ fn request(input: &str) -> Request {
142
+ parse_request(input.as_bytes())
143
+ }
144
+
145
+ #[test]
146
+ fn a_request_is_read_up_to_the_blank_line() {
147
+ let request = request("protocol=https\nhost=sigit.si\n\nignored=yes\n");
148
+ assert_eq!(request["host"], "sigit.si");
149
+ assert_eq!(request["protocol"], "https");
150
+ assert!(!request.contains_key("ignored"));
151
+ }
152
+
153
+ #[test]
154
+ fn a_request_may_end_without_a_blank_line() {
155
+ assert_eq!(request("host=sigit.si")["host"], "sigit.si");
156
+ }
157
+
158
+ #[test]
159
+ fn values_may_contain_equals_signs() {
160
+ assert_eq!(request("path=a=b\n")["path"], "a=b");
161
+ }
162
+
163
+ #[test]
164
+ fn the_configured_host_matches() {
165
+ let request = request("protocol=https\nhost=sigit.si\n\n");
166
+ assert!(is_for_host(&request, "https://sigit.si"));
167
+ }
168
+
169
+ #[test]
170
+ fn other_hosts_are_ignored() {
171
+ let request = request("protocol=https\nhost=github.com\n\n");
172
+ assert!(!is_for_host(&request, "https://sigit.si"));
173
+ }
174
+
175
+ #[test]
176
+ fn a_request_without_a_host_is_ignored() {
177
+ assert!(!is_for_host(
178
+ &request("protocol=https\n\n"),
179
+ "https://sigit.si"
180
+ ));
181
+ }
182
+
183
+ #[test]
184
+ fn a_plain_http_request_does_not_get_a_token_for_an_https_host() {
185
+ let request = request("protocol=http\nhost=sigit.si\n\n");
186
+ assert!(!is_for_host(&request, "https://sigit.si"));
187
+ }
188
+
189
+ #[test]
190
+ fn a_dev_host_matches_with_its_port() {
191
+ let request = request("protocol=http\nhost=localhost:3000\n\n");
192
+ assert!(is_for_host(&request, "http://localhost:3000"));
193
+ }
194
+
195
+ #[test]
196
+ fn the_response_ends_with_a_blank_line() {
197
+ assert_eq!(
198
+ response("x-access-token", "abc"),
199
+ "username=x-access-token\npassword=abc\n\n"
200
+ );
201
+ }
202
+
203
+ #[test]
204
+ fn the_helper_command_quotes_the_executable() {
205
+ let command = helper_command(Path::new("/opt/it's here/si"));
206
+ assert_eq!(command, r"!'/opt/it'\''s here/si' auth git-credential");
207
+ }
208
+
209
+ #[test]
210
+ fn clone_resets_the_helper_before_setting_ours() {
211
+ let slug = RepoSlug::parse("seto/demo").unwrap();
212
+ let args = clone_args(
213
+ "https://sigit.si",
214
+ Path::new("/bin/si"),
215
+ &slug,
216
+ Some("out"),
217
+ &["--depth".to_string(), "1".to_string()],
218
+ );
219
+ assert_eq!(
220
+ args,
221
+ [
222
+ "-c",
223
+ "credential.https://sigit.si.helper=",
224
+ "-c",
225
+ "credential.https://sigit.si.helper=!'/bin/si' auth git-credential",
226
+ "clone",
227
+ "--depth",
228
+ "1",
229
+ "https://sigit.si/seto/demo.git",
230
+ "out",
231
+ ]
232
+ );
233
+ }
234
+
235
+ #[test]
236
+ fn clone_without_a_directory_leaves_the_choice_to_git() {
237
+ let slug = RepoSlug::parse("seto/demo").unwrap();
238
+ let args = clone_args("https://sigit.si", Path::new("/bin/si"), &slug, None, &[]);
239
+ assert_eq!(args.last().unwrap(), "https://sigit.si/seto/demo.git");
240
+ }
241
+}
crates/cli/src/git.rs
+1
-1
@@ -133,7 +133,7 @@ fn split_host_and_path(url: &str) -> Option<(String, String)> {
133
134
/// Compare hosts ignoring the port and a leading `www.`, so a dev remote on
135
/// `localhost:3000` matches a `localhost` base URL and vice versa.
136
-fn hosts_match(a: &str, b: &str) -> bool {
136
+pub fn hosts_match(a: &str, b: &str) -> bool {
137
fn normalize(host: &str) -> String {
138
let host = host.trim().to_ascii_lowercase();
139
let host = host
crates/cli/src/main.rs
+1
@@ -2,6 +2,7 @@ mod cli;
2
mod commands;
3
mod config;
4
mod context;
5
+mod credential;
6
mod git;
7
mod mcp;
8
mod ui;