| 1 |
|
- |
//! Forge repository management, clone, import and git credential helper
|
| 2 |
|
- |
//! Talking to real `/api/v1` routes and executing git processes
|
|
1
|
+ |
//! Forge repository management, git execution, and the git credential helper.
|
|
2
|
+ |
//!
|
|
3
|
+ |
//! Every command here either reads the server's own answer or refuses. There is
|
|
4
|
+ |
//! no default repository, no assumed visibility, and no invented clone URL: a
|
|
5
|
+ |
//! repository the API did not describe is one this CLI cannot describe either.
|
| 3 |
6
|
|
|
|
7
|
+ |
use crate::auth::{api_error_detail, AuthError, Secret};
|
| 4 |
8
|
|
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
|
| 5 |
9
|
|
use serde::{Deserialize, Serialize};
|
|
10
|
+ |
use std::io::Read;
|
| 6 |
11
|
|
use std::path::Path;
|
|
12
|
+ |
use std::process::Command as SyncCommand;
|
|
13
|
+ |
use std::time::{Duration, Instant};
|
| 7 |
14
|
|
use tokio::process::Command;
|
| 8 |
15
|
|
|
|
16
|
+ |
// ---------------------------------------------------------------------------
|
|
17
|
+ |
// contract
|
|
18
|
+ |
// ---------------------------------------------------------------------------
|
|
19
|
+ |
|
|
20
|
+ |
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
21
|
+ |
pub struct RepositoryOwner {
|
|
22
|
+ |
pub id: serde_json::Value,
|
|
23
|
+ |
pub login: String,
|
|
24
|
+ |
#[serde(default)]
|
|
25
|
+ |
pub r#type: String,
|
|
26
|
+ |
}
|
|
27
|
+ |
|
|
28
|
+ |
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
29
|
+ |
pub struct RepositoryPermissions {
|
|
30
|
+ |
pub admin: bool,
|
|
31
|
+ |
pub push: bool,
|
|
32
|
+ |
pub pull: bool,
|
|
33
|
+ |
}
|
|
34
|
+ |
|
|
35
|
+ |
/// The repository as `openagents.repositories.v1` describes it.
|
|
36
|
+ |
///
|
|
37
|
+ |
/// Nothing here has a serde default. A response missing `lifecycle_state` or
|
|
38
|
+ |
/// `clone_url` is a response this CLI cannot report on, and saying so is the
|
|
39
|
+ |
/// point: the alternative is printing `Provisioning: ready` about a repository
|
|
40
|
+ |
/// whose state the server never sent.
|
| 9 |
41
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
| 10 |
42
|
|
pub struct Repository {
|
| 11 |
43
|
|
pub id: String,
|
| 12 |
|
- |
pub slug: String,
|
| 13 |
|
- |
pub is_private: bool,
|
|
44
|
+ |
pub name: String,
|
|
45
|
+ |
pub full_name: String,
|
|
46
|
+ |
pub owner: RepositoryOwner,
|
|
47
|
+ |
pub private: bool,
|
|
48
|
+ |
pub visibility: String,
|
|
49
|
+ |
pub description: Option<String>,
|
| 14 |
50
|
|
pub default_branch: String,
|
|
51
|
+ |
pub lifecycle_state: String,
|
|
52
|
+ |
pub provision_error_code: Option<String>,
|
|
53
|
+ |
pub clone_url: String,
|
|
54
|
+ |
pub html_url: String,
|
|
55
|
+ |
pub permissions: RepositoryPermissions,
|
|
56
|
+ |
pub created_at: String,
|
|
57
|
+ |
pub updated_at: String,
|
|
58
|
+ |
}
|
|
59
|
+ |
|
|
60
|
+ |
impl Repository {
|
|
61
|
+ |
/// The block `oa repo view` prints, field for field with the TypeScript CLI.
|
|
62
|
+ |
pub fn human_lines(&self) -> Vec<String> {
|
|
63
|
+ |
vec![
|
|
64
|
+ |
self.full_name.clone(),
|
|
65
|
+ |
format!(
|
|
66
|
+ |
"Visibility: {}",
|
|
67
|
+ |
if self.private { "private" } else { "public" }
|
|
68
|
+ |
),
|
|
69
|
+ |
format!("Default branch: {}", self.default_branch),
|
|
70
|
+ |
format!("Provisioning: {}", self.lifecycle_state),
|
|
71
|
+ |
]
|
|
72
|
+ |
}
|
| 15 |
73
|
|
}
|
| 16 |
74
|
|
|
|
75
|
+ |
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
76
|
+ |
pub struct RepositoryImport {
|
|
77
|
+ |
pub id: String,
|
|
78
|
+ |
pub provider: String,
|
|
79
|
+ |
pub source_full_name: String,
|
|
80
|
+ |
pub state: String,
|
|
81
|
+ |
#[serde(default)]
|
|
82
|
+ |
pub attempt_count: i64,
|
|
83
|
+ |
#[serde(default)]
|
|
84
|
+ |
pub lfs_warning: bool,
|
|
85
|
+ |
pub error_code: Option<String>,
|
|
86
|
+ |
}
|
|
87
|
+ |
|
|
88
|
+ |
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
89
|
+ |
pub struct RepositoryList {
|
|
90
|
+ |
pub repositories: Vec<Repository>,
|
|
91
|
+ |
pub next_cursor: Option<String>,
|
|
92
|
+ |
}
|
|
93
|
+ |
|
|
94
|
+ |
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
95
|
+ |
pub struct AuthenticatedNamespace {
|
|
96
|
+ |
pub id: serde_json::Value,
|
|
97
|
+ |
pub login: String,
|
|
98
|
+ |
pub r#type: String,
|
|
99
|
+ |
}
|
|
100
|
+ |
|
|
101
|
+ |
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
102
|
+ |
pub struct AuthenticatedUser {
|
|
103
|
+ |
pub id: i64,
|
|
104
|
+ |
pub login: String,
|
|
105
|
+ |
pub token_expires_at: String,
|
|
106
|
+ |
pub namespaces: Vec<AuthenticatedNamespace>,
|
|
107
|
+ |
}
|
|
108
|
+ |
|
|
109
|
+ |
// ---------------------------------------------------------------------------
|
|
110
|
+ |
// name validation
|
|
111
|
+ |
// ---------------------------------------------------------------------------
|
|
112
|
+ |
|
|
113
|
+ |
/// `[a-z0-9](?:[a-z0-9_-]|\.(?=[a-z0-9])){0,63}` written out, because a dot has
|
|
114
|
+ |
/// to be followed by an alphanumeric and Rust's regex engine has no lookahead.
|
|
115
|
+ |
pub fn validate_repository_name(name: &str) -> Result<String, AuthError> {
|
|
116
|
+ |
let normalized = name.trim().to_ascii_lowercase();
|
|
117
|
+ |
let bytes = normalized.as_bytes();
|
|
118
|
+ |
let mut valid = (1..=64).contains(&bytes.len()) && bytes[0].is_ascii_alphanumeric();
|
|
119
|
+ |
let mut index = 1;
|
|
120
|
+ |
while valid && index < bytes.len() {
|
|
121
|
+ |
let byte = bytes[index];
|
|
122
|
+ |
valid = byte.is_ascii_lowercase()
|
|
123
|
+ |
|| byte.is_ascii_digit()
|
|
124
|
+ |
|| byte == b'_'
|
|
125
|
+ |
|| byte == b'-'
|
|
126
|
+ |
|| (byte == b'.'
|
|
127
|
+ |
&& bytes
|
|
128
|
+ |
.get(index + 1)
|
|
129
|
+ |
.is_some_and(|next| next.is_ascii_lowercase() || next.is_ascii_digit()));
|
|
130
|
+ |
index += 1;
|
|
131
|
+ |
}
|
|
132
|
+ |
if !valid {
|
|
133
|
+ |
return Err(AuthError::new(format!(
|
|
134
|
+ |
"invalid repository name {name}. Names must match \
|
|
135
|
+ |
[a-z0-9](?:[a-z0-9_-]|\\.(?=[a-z0-9])){{0,63}}"
|
|
136
|
+ |
)));
|
|
137
|
+ |
}
|
|
138
|
+ |
Ok(normalized)
|
|
139
|
+ |
}
|
|
140
|
+ |
|
|
141
|
+ |
/// `[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})`, the GitHub namespace shape.
|
|
142
|
+ |
pub fn validate_owner(owner: &str) -> Result<String, AuthError> {
|
|
143
|
+ |
let normalized = owner.trim().to_string();
|
|
144
|
+ |
let bytes = normalized.as_bytes();
|
|
145
|
+ |
let valid = (1..=39).contains(&bytes.len())
|
|
146
|
+ |
&& bytes[0].is_ascii_alphanumeric()
|
|
147
|
+ |
&& bytes[1..]
|
|
148
|
+ |
.iter()
|
|
149
|
+ |
.all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-');
|
|
150
|
+ |
if !valid {
|
|
151
|
+ |
return Err(AuthError::new(format!(
|
|
152
|
+ |
"invalid GitHub-backed namespace: {owner}"
|
|
153
|
+ |
)));
|
|
154
|
+ |
}
|
|
155
|
+ |
Ok(normalized)
|
|
156
|
+ |
}
|
|
157
|
+ |
|
|
158
|
+ |
pub fn parse_repository_target(full_name: &str) -> Result<(String, String), AuthError> {
|
|
159
|
+ |
let parts: Vec<&str> = full_name.trim().split('/').collect();
|
|
160
|
+ |
if parts.len() != 2 {
|
|
161
|
+ |
return Err(AuthError::new("use the repository format OWNER/REPO"));
|
|
162
|
+ |
}
|
|
163
|
+ |
Ok((
|
|
164
|
+ |
validate_owner(parts[0])?,
|
|
165
|
+ |
validate_repository_name(parts[1])?,
|
|
166
|
+ |
))
|
|
167
|
+ |
}
|
|
168
|
+ |
|
|
169
|
+ |
// ---------------------------------------------------------------------------
|
|
170
|
+ |
// client
|
|
171
|
+ |
// ---------------------------------------------------------------------------
|
|
172
|
+ |
|
| 17 |
173
|
|
pub struct RepoClient {
|
| 18 |
|
- |
pub api_base: String,
|
| 19 |
|
- |
pub token: Option<String>,
|
| 20 |
|
- |
pub http: reqwest::Client,
|
|
174
|
+ |
origin: String,
|
|
175
|
+ |
token: Option<Secret>,
|
|
176
|
+ |
http: reqwest::Client,
|
| 21 |
177
|
|
}
|
| 22 |
178
|
|
|
| 23 |
179
|
|
impl RepoClient {
|
| 24 |
|
- |
pub fn new(api_base: &str, token: Option<String>) -> Self {
|
|
180
|
+ |
/// `origin` is a bare API origin, such as `https://openagents.com`.
|
|
181
|
+ |
pub fn new(origin: &str, token: Option<Secret>) -> Self {
|
| 25 |
182
|
|
Self {
|
| 26 |
|
- |
api_base: api_base.trim_end_matches('/').to_string(),
|
|
183
|
+ |
origin: origin.trim_end_matches('/').to_string(),
|
| 27 |
184
|
|
token,
|
| 28 |
|
- |
http: reqwest::Client::new(),
|
|
185
|
+ |
http: reqwest::Client::builder()
|
|
186
|
+ |
.timeout(Duration::from_secs(60))
|
|
187
|
+ |
.build()
|
|
188
|
+ |
.unwrap_or_default(),
|
| 29 |
189
|
|
}
|
| 30 |
190
|
|
}
|
| 31 |
191
|
|
|
| 32 |
|
- |
fn headers(&self) -> HeaderMap {
|
|
192
|
+ |
pub fn origin(&self) -> &str {
|
|
193
|
+ |
&self.origin
|
|
194
|
+ |
}
|
|
195
|
+ |
|
|
196
|
+ |
fn headers(&self, idempotency_key: Option<&str>) -> HeaderMap {
|
| 33 |
197
|
|
let mut map = HeaderMap::new();
|
| 34 |
198
|
|
map.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
| 35 |
|
- |
if let Some(tok) = &self.token {
|
| 36 |
|
- |
if let Ok(val) = HeaderValue::from_str(&format!("Bearer {}", tok)) {
|
| 37 |
|
- |
map.insert(AUTHORIZATION, val);
|
|
199
|
+ |
if let Some(token) = &self.token {
|
|
200
|
+ |
if let Ok(value) = HeaderValue::from_str(&format!("Bearer {}", token.expose())) {
|
|
201
|
+ |
map.insert(AUTHORIZATION, value);
|
|
202
|
+ |
}
|
|
203
|
+ |
}
|
|
204
|
+ |
if let Some(key) = idempotency_key {
|
|
205
|
+ |
if let Ok(value) = HeaderValue::from_str(key) {
|
|
206
|
+ |
map.insert("idempotency-key", value);
|
| 38 |
207
|
|
}
|
| 39 |
208
|
|
}
|
| 40 |
209
|
|
map
|
| 41 |
210
|
|
}
|
| 42 |
211
|
|
|
| 43 |
|
- |
pub async fn list_repos(&self) -> Result<Vec<Repository>, Box<dyn std::error::Error + Send + Sync>> {
|
| 44 |
|
- |
let url = format!("{}/user/repos", self.api_base);
|
| 45 |
|
- |
let resp = self.http.get(&url).headers(self.headers()).send().await?;
|
| 46 |
|
- |
|
| 47 |
|
- |
if resp.status().is_success() {
|
| 48 |
|
- |
let body: serde_json::Value = resp.json().await?;
|
| 49 |
|
- |
let items = body.get("repositories").and_then(|v| v.as_array()).cloned().unwrap_or_else(|| {
|
| 50 |
|
- |
if let Some(arr) = body.as_array() { arr.clone() } else { Vec::new() }
|
| 51 |
|
- |
});
|
| 52 |
|
- |
|
| 53 |
|
- |
let mut repos = Vec::new();
|
| 54 |
|
- |
for item in items {
|
| 55 |
|
- |
let id = item.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
| 56 |
|
- |
let full_name = item.get("full_name").or_else(|| item.get("slug")).and_then(|v| v.as_str()).unwrap_or("").to_string();
|
| 57 |
|
- |
let is_private = item.get("private").and_then(|v| v.as_bool()).unwrap_or(false);
|
| 58 |
|
- |
let default_branch = item.get("default_branch").and_then(|v| v.as_str()).unwrap_or("main").to_string();
|
| 59 |
|
- |
|
| 60 |
|
- |
repos.push(Repository {
|
| 61 |
|
- |
id,
|
| 62 |
|
- |
slug: full_name,
|
| 63 |
|
- |
is_private,
|
| 64 |
|
- |
default_branch,
|
| 65 |
|
- |
});
|
| 66 |
|
- |
}
|
| 67 |
|
- |
Ok(repos)
|
| 68 |
|
- |
} else {
|
| 69 |
|
- |
Ok(Vec::new())
|
|
212
|
+ |
/// Issue one request and refuse on anything the caller did not admit.
|
|
213
|
+ |
///
|
|
214
|
+ |
/// The refusal carries the server's own status, code, and request id. A
|
|
215
|
+ |
/// caller that fell back to an empty list here would report "no
|
|
216
|
+ |
/// repositories" for a token the server rejected.
|
|
217
|
+ |
async fn request(
|
|
218
|
+ |
&self,
|
|
219
|
+ |
operation: &str,
|
|
220
|
+ |
method: reqwest::Method,
|
|
221
|
+ |
path: &str,
|
|
222
|
+ |
body: Option<serde_json::Value>,
|
|
223
|
+ |
idempotency_key: Option<&str>,
|
|
224
|
+ |
admitted: &[u16],
|
|
225
|
+ |
) -> Result<serde_json::Value, AuthError> {
|
|
226
|
+ |
let url = format!("{}{}", self.origin, path);
|
|
227
|
+ |
let mut builder = self
|
|
228
|
+ |
.http
|
|
229
|
+ |
.request(method, &url)
|
|
230
|
+ |
.headers(self.headers(idempotency_key));
|
|
231
|
+ |
if let Some(value) = body {
|
|
232
|
+ |
builder = builder.json(&value);
|
| 70 |
233
|
|
}
|
|
234
|
+ |
let response = builder.send().await.map_err(|error| {
|
|
235
|
+ |
AuthError::new(format!("could not {operation} at {}: {error}", self.origin))
|
|
236
|
+ |
})?;
|
|
237
|
+ |
let status = response.status().as_u16();
|
|
238
|
+ |
let text = response.text().await.unwrap_or_default();
|
|
239
|
+ |
let value: serde_json::Value =
|
|
240
|
+ |
serde_json::from_str(&text).unwrap_or(serde_json::Value::Null);
|
|
241
|
+ |
if !admitted.contains(&status) {
|
|
242
|
+ |
return Err(AuthError::new(format!(
|
|
243
|
+ |
"could not {operation} ({status}{})",
|
|
244
|
+ |
api_error_detail(&value)
|
|
245
|
+ |
)));
|
|
246
|
+ |
}
|
|
247
|
+ |
Ok(value)
|
|
248
|
+ |
}
|
|
249
|
+ |
|
|
250
|
+ |
fn decode<T: serde::de::DeserializeOwned>(
|
|
251
|
+ |
operation: &str,
|
|
252
|
+ |
value: serde_json::Value,
|
|
253
|
+ |
) -> Result<T, AuthError> {
|
|
254
|
+ |
serde_json::from_value(value).map_err(|error| {
|
|
255
|
+ |
AuthError::new(format!(
|
|
256
|
+ |
"the API response did not match the {operation} contract: {error}"
|
|
257
|
+ |
))
|
|
258
|
+ |
})
|
|
259
|
+ |
}
|
|
260
|
+ |
|
|
261
|
+ |
pub async fn authenticated_user(&self) -> Result<AuthenticatedUser, AuthError> {
|
|
262
|
+ |
let value = self
|
|
263
|
+ |
.request(
|
|
264
|
+ |
"read the authenticated user",
|
|
265
|
+ |
reqwest::Method::GET,
|
|
266
|
+ |
"/api/v1/user",
|
|
267
|
+ |
None,
|
|
268
|
+ |
None,
|
|
269
|
+ |
&[200],
|
|
270
|
+ |
)
|
|
271
|
+ |
.await?;
|
|
272
|
+ |
Self::decode("read authenticated user", value)
|
| 71 |
273
|
|
}
|
| 72 |
274
|
|
|
| 73 |
|
- |
pub async fn create_repo(&self, name: &str, is_private: bool) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
|
| 74 |
|
- |
let url = format!("{}/user/repos", self.api_base);
|
| 75 |
|
- |
let resp = self.http.post(&url).headers(self.headers()).json(&serde_json::json!({
|
|
275
|
+ |
pub async fn list(
|
|
276
|
+ |
&self,
|
|
277
|
+ |
namespace: Option<&str>,
|
|
278
|
+ |
limit: u32,
|
|
279
|
+ |
after: Option<&str>,
|
|
280
|
+ |
) -> Result<RepositoryList, AuthError> {
|
|
281
|
+ |
if !(1..=100).contains(&limit) {
|
|
282
|
+ |
return Err(AuthError::new("--limit must be between 1 and 100"));
|
|
283
|
+ |
}
|
|
284
|
+ |
let mut query = format!("per_page={limit}");
|
|
285
|
+ |
if let Some(namespace) = namespace {
|
|
286
|
+ |
query.push_str(&format!("&namespace={}", validate_owner(namespace)?));
|
|
287
|
+ |
}
|
|
288
|
+ |
if let Some(after) = after {
|
|
289
|
+ |
query.push_str(&format!("&after={}", urlencode(after)));
|
|
290
|
+ |
}
|
|
291
|
+ |
let value = self
|
|
292
|
+ |
.request(
|
|
293
|
+ |
"list repositories",
|
|
294
|
+ |
reqwest::Method::GET,
|
|
295
|
+ |
&format!("/api/v1/user/repos?{query}"),
|
|
296
|
+ |
None,
|
|
297
|
+ |
None,
|
|
298
|
+ |
&[200],
|
|
299
|
+ |
)
|
|
300
|
+ |
.await?;
|
|
301
|
+ |
Self::decode("list repositories", value)
|
|
302
|
+ |
}
|
|
303
|
+ |
|
|
304
|
+ |
pub async fn view(&self, owner: &str, repo: &str) -> Result<Repository, AuthError> {
|
|
305
|
+ |
let owner = validate_owner(owner)?;
|
|
306
|
+ |
let repo = validate_repository_name(repo)?;
|
|
307
|
+ |
let value = self
|
|
308
|
+ |
.request(
|
|
309
|
+ |
&format!("view {owner}/{repo}"),
|
|
310
|
+ |
reqwest::Method::GET,
|
|
311
|
+ |
&format!("/api/v1/repos/{}/{}", urlencode(&owner), urlencode(&repo)),
|
|
312
|
+ |
None,
|
|
313
|
+ |
None,
|
|
314
|
+ |
&[200],
|
|
315
|
+ |
)
|
|
316
|
+ |
.await?;
|
|
317
|
+ |
Self::decode("view repository", value)
|
|
318
|
+ |
}
|
|
319
|
+ |
|
|
320
|
+ |
pub async fn remove(&self, owner: &str, repo: &str) -> Result<(), AuthError> {
|
|
321
|
+ |
let owner = validate_owner(owner)?;
|
|
322
|
+ |
let repo = validate_repository_name(repo)?;
|
|
323
|
+ |
self.request(
|
|
324
|
+ |
&format!("delete {owner}/{repo}"),
|
|
325
|
+ |
reqwest::Method::DELETE,
|
|
326
|
+ |
&format!("/api/v1/repos/{}/{}", urlencode(&owner), urlencode(&repo)),
|
|
327
|
+ |
None,
|
|
328
|
+ |
None,
|
|
329
|
+ |
&[200, 202, 204],
|
|
330
|
+ |
)
|
|
331
|
+ |
.await?;
|
|
332
|
+ |
Ok(())
|
|
333
|
+ |
}
|
|
334
|
+ |
|
|
335
|
+ |
#[allow(clippy::too_many_arguments)]
|
|
336
|
+ |
pub async fn create(
|
|
337
|
+ |
&self,
|
|
338
|
+ |
owner: Option<&str>,
|
|
339
|
+ |
name: &str,
|
|
340
|
+ |
private: bool,
|
|
341
|
+ |
description: Option<&str>,
|
|
342
|
+ |
default_branch: &str,
|
|
343
|
+ |
wait: Duration,
|
|
344
|
+ |
) -> Result<Repository, AuthError> {
|
|
345
|
+ |
let name = validate_repository_name(name)?;
|
|
346
|
+ |
let owner = owner.map(validate_owner).transpose()?;
|
|
347
|
+ |
let mut body = serde_json::json!({
|
| 76 |
348
|
|
"name": name,
|
| 77 |
|
- |
"private": is_private,
|
| 78 |
|
- |
})).send().await?;
|
| 79 |
|
- |
Ok(resp.status().is_success())
|
|
349
|
+ |
"private": private,
|
|
350
|
+ |
"default_branch": default_branch,
|
|
351
|
+ |
});
|
|
352
|
+ |
if let Some(description) = description {
|
|
353
|
+ |
body["description"] = serde_json::Value::String(description.to_string());
|
|
354
|
+ |
}
|
|
355
|
+ |
let path = match &owner {
|
|
356
|
+ |
None => "/api/v1/user/repos".to_string(),
|
|
357
|
+ |
Some(owner) => format!("/api/v1/orgs/{}/repos", urlencode(owner)),
|
|
358
|
+ |
};
|
|
359
|
+ |
let value = self
|
|
360
|
+ |
.request(
|
|
361
|
+ |
"create the repository",
|
|
362
|
+ |
reqwest::Method::POST,
|
|
363
|
+ |
&path,
|
|
364
|
+ |
Some(body),
|
|
365
|
+ |
Some(&idempotency_key()),
|
|
366
|
+ |
&[200, 201, 202],
|
|
367
|
+ |
)
|
|
368
|
+ |
.await?;
|
|
369
|
+ |
let repository: Repository = Self::decode("create repository", value)?;
|
|
370
|
+ |
if repository.lifecycle_state == "ready" || wait.is_zero() {
|
|
371
|
+ |
return Ok(repository);
|
|
372
|
+ |
}
|
|
373
|
+ |
self.wait_for_repository(&repository.owner.login, &repository.name, wait)
|
|
374
|
+ |
.await
|
| 80 |
375
|
|
}
|
| 81 |
376
|
|
|
| 82 |
|
- |
pub async fn clone_repo(slug: &str, destination: Option<&Path>) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
|
| 83 |
|
- |
let repo_url = format!("https://openagents.com/{}.git", slug);
|
| 84 |
|
- |
let mut cmd = Command::new("git");
|
| 85 |
|
- |
cmd.arg("clone").arg(&repo_url);
|
| 86 |
|
- |
if let Some(dest) = destination {
|
| 87 |
|
- |
cmd.arg(dest);
|
|
377
|
+ |
async fn wait_for_repository(
|
|
378
|
+ |
&self,
|
|
379
|
+ |
owner: &str,
|
|
380
|
+ |
repo: &str,
|
|
381
|
+ |
wait: Duration,
|
|
382
|
+ |
) -> Result<Repository, AuthError> {
|
|
383
|
+ |
let started = Instant::now();
|
|
384
|
+ |
loop {
|
|
385
|
+ |
let repository = self.view(owner, repo).await?;
|
|
386
|
+ |
match repository.lifecycle_state.as_str() {
|
|
387
|
+ |
"ready" => return Ok(repository),
|
|
388
|
+ |
"failed" => {
|
|
389
|
+ |
return Err(AuthError::new(format!(
|
|
390
|
+ |
"provisioning failed for {owner}/{repo}{}",
|
|
391
|
+ |
repository
|
|
392
|
+ |
.provision_error_code
|
|
393
|
+ |
.map(|code| format!(": {code}"))
|
|
394
|
+ |
.unwrap_or_default()
|
|
395
|
+ |
)))
|
|
396
|
+ |
}
|
|
397
|
+ |
_ => {}
|
|
398
|
+ |
}
|
|
399
|
+ |
if started.elapsed() >= wait {
|
|
400
|
+ |
return Err(AuthError::new(format!(
|
|
401
|
+ |
"{owner}/{repo} is still provisioning after {} s. Provisioning continues on the server",
|
|
402
|
+ |
wait.as_secs()
|
|
403
|
+ |
)));
|
|
404
|
+ |
}
|
|
405
|
+ |
eprintln!(
|
|
406
|
+ |
"Repository provisioning: {} ({}s elapsed).",
|
|
407
|
+ |
repository.lifecycle_state,
|
|
408
|
+ |
started.elapsed().as_secs()
|
|
409
|
+ |
);
|
|
410
|
+ |
tokio::time::sleep(Duration::from_secs(1)).await;
|
|
411
|
+ |
}
|
|
412
|
+ |
}
|
|
413
|
+ |
|
|
414
|
+ |
pub async fn import(
|
|
415
|
+ |
&self,
|
|
416
|
+ |
owner: Option<&str>,
|
|
417
|
+ |
source: &str,
|
|
418
|
+ |
name: Option<&str>,
|
|
419
|
+ |
private: Option<bool>,
|
|
420
|
+ |
wait: Duration,
|
|
421
|
+ |
) -> Result<(Repository, RepositoryImport), AuthError> {
|
|
422
|
+ |
let (source_owner, source_repo) = parse_repository_target(source)?;
|
|
423
|
+ |
let owner = owner.map(validate_owner).transpose()?;
|
|
424
|
+ |
let name = name.map(validate_repository_name).transpose()?;
|
|
425
|
+ |
let mut body = serde_json::json!({
|
|
426
|
+ |
"source": { "provider": "github", "repository": format!("{source_owner}/{source_repo}") },
|
|
427
|
+ |
});
|
|
428
|
+ |
if let Some(private) = private {
|
|
429
|
+ |
body["private"] = serde_json::Value::Bool(private);
|
|
430
|
+ |
}
|
|
431
|
+ |
if let Some(name) = &name {
|
|
432
|
+ |
body["name"] = serde_json::Value::String(name.clone());
|
|
433
|
+ |
}
|
|
434
|
+ |
let path = match &owner {
|
|
435
|
+ |
None => "/api/v1/user/repos/imports".to_string(),
|
|
436
|
+ |
Some(owner) => format!("/api/v1/orgs/{}/repos/imports", urlencode(owner)),
|
|
437
|
+ |
};
|
|
438
|
+ |
let value = self
|
|
439
|
+ |
.request(
|
|
440
|
+ |
"import the repository",
|
|
441
|
+ |
reqwest::Method::POST,
|
|
442
|
+ |
&path,
|
|
443
|
+ |
Some(body),
|
|
444
|
+ |
Some(&idempotency_key()),
|
|
445
|
+ |
&[200, 201, 202],
|
|
446
|
+ |
)
|
|
447
|
+ |
.await?;
|
|
448
|
+ |
let repository: Repository = Self::decode("import repository", value.clone())?;
|
|
449
|
+ |
let repository_import: RepositoryImport = serde_json::from_value(
|
|
450
|
+ |
value
|
|
451
|
+ |
.get("import")
|
|
452
|
+ |
.cloned()
|
|
453
|
+ |
.unwrap_or(serde_json::Value::Null),
|
|
454
|
+ |
)
|
|
455
|
+ |
.map_err(|error| {
|
|
456
|
+ |
AuthError::new(format!(
|
|
457
|
+ |
"the API response did not match the import repository contract: {error}"
|
|
458
|
+ |
))
|
|
459
|
+ |
})?;
|
|
460
|
+ |
if repository_import.state == "completed" || wait.is_zero() {
|
|
461
|
+ |
return Ok((repository, repository_import));
|
|
462
|
+ |
}
|
|
463
|
+ |
self.wait_for_import(&repository_import.id, wait).await
|
|
464
|
+ |
}
|
|
465
|
+ |
|
|
466
|
+ |
async fn wait_for_import(
|
|
467
|
+ |
&self,
|
|
468
|
+ |
import_id: &str,
|
|
469
|
+ |
wait: Duration,
|
|
470
|
+ |
) -> Result<(Repository, RepositoryImport), AuthError> {
|
|
471
|
+ |
let started = Instant::now();
|
|
472
|
+ |
loop {
|
|
473
|
+ |
let value = self
|
|
474
|
+ |
.request(
|
|
475
|
+ |
"read the repository import",
|
|
476
|
+ |
reqwest::Method::GET,
|
|
477
|
+ |
&format!("/api/v1/repository-imports/{}", urlencode(import_id)),
|
|
478
|
+ |
None,
|
|
479
|
+ |
None,
|
|
480
|
+ |
&[200],
|
|
481
|
+ |
)
|
|
482
|
+ |
.await?;
|
|
483
|
+ |
let repository: Repository = Self::decode(
|
|
484
|
+ |
"read repository import",
|
|
485
|
+ |
value
|
|
486
|
+ |
.get("repository")
|
|
487
|
+ |
.cloned()
|
|
488
|
+ |
.unwrap_or(serde_json::Value::Null),
|
|
489
|
+ |
)?;
|
|
490
|
+ |
let repository_import: RepositoryImport = Self::decode(
|
|
491
|
+ |
"read repository import",
|
|
492
|
+ |
value
|
|
493
|
+ |
.get("import")
|
|
494
|
+ |
.cloned()
|
|
495
|
+ |
.unwrap_or(serde_json::Value::Null),
|
|
496
|
+ |
)?;
|
|
497
|
+ |
match repository_import.state.as_str() {
|
|
498
|
+ |
"completed" => return Ok((repository, repository_import)),
|
|
499
|
+ |
"failed" => {
|
|
500
|
+ |
return Err(AuthError::new(format!(
|
|
501
|
+ |
"repository import {import_id} failed{}",
|
|
502
|
+ |
repository_import
|
|
503
|
+ |
.error_code
|
|
504
|
+ |
.map(|code| format!(": {code}"))
|
|
505
|
+ |
.unwrap_or_default()
|
|
506
|
+ |
)))
|
|
507
|
+ |
}
|
|
508
|
+ |
_ => {}
|
|
509
|
+ |
}
|
|
510
|
+ |
if started.elapsed() >= wait {
|
|
511
|
+ |
return Err(AuthError::new(format!(
|
|
512
|
+ |
"repository import {import_id} is still running after {} s. The import continues on the server",
|
|
513
|
+ |
wait.as_secs()
|
|
514
|
+ |
)));
|
|
515
|
+ |
}
|
|
516
|
+ |
eprintln!(
|
|
517
|
+ |
"Repository import: {} (shallow snapshot, attempt {}, {}s elapsed).",
|
|
518
|
+ |
repository_import.state,
|
|
519
|
+ |
repository_import.attempt_count,
|
|
520
|
+ |
started.elapsed().as_secs()
|
|
521
|
+ |
);
|
|
522
|
+ |
tokio::time::sleep(Duration::from_secs(1)).await;
|
| 88 |
523
|
|
}
|
| 89 |
|
- |
let status = cmd.status().await?;
|
| 90 |
|
- |
Ok(status.success())
|
|
524
|
+ |
}
|
|
525
|
+ |
|
|
526
|
+ |
/// The repository and the URL to clone it from, after checking that the URL
|
|
527
|
+ |
/// the API returned is on the origin this invocation is talking to. A clone
|
|
528
|
+ |
/// URL pointing elsewhere would send the credential helper's token to
|
|
529
|
+ |
/// whatever host the response named.
|
|
530
|
+ |
pub async fn clone_info(
|
|
531
|
+ |
&self,
|
|
532
|
+ |
owner: &str,
|
|
533
|
+ |
repo: &str,
|
|
534
|
+ |
) -> Result<(Repository, String), AuthError> {
|
|
535
|
+ |
let repository = self.view(owner, repo).await?;
|
|
536
|
+ |
let url = reqwest::Url::parse(&repository.clone_url).map_err(|error| {
|
|
537
|
+ |
AuthError::new(format!("the API returned an invalid clone URL: {error}"))
|
|
538
|
+ |
})?;
|
|
539
|
+ |
let expected = format!(
|
|
540
|
+ |
"/{}/{}.git",
|
|
541
|
+ |
urlencode(&repository.owner.login),
|
|
542
|
+ |
urlencode(&repository.name)
|
|
543
|
+ |
);
|
|
544
|
+ |
let origin_matches = url_origin(&url)
|
|
545
|
+ |
.map(|value| value == self.origin)
|
|
546
|
+ |
.unwrap_or(false);
|
|
547
|
+ |
if !origin_matches
|
|
548
|
+ |
|| !url.username().is_empty()
|
|
549
|
+ |
|| url.password().is_some()
|
|
550
|
+ |
|| url.query().is_some()
|
|
551
|
+ |
|| url.fragment().is_some()
|
|
552
|
+ |
|| url.path() != expected
|
|
553
|
+ |
{
|
|
554
|
+ |
return Err(AuthError::new(
|
|
555
|
+ |
"the API returned a clone URL outside the selected OpenAgents origin",
|
|
556
|
+ |
));
|
|
557
|
+ |
}
|
|
558
|
+ |
Ok((repository, url.to_string()))
|
| 91 |
559
|
|
}
|
| 92 |
560
|
|
}
|
| 93 |
561
|
|
|
| 94 |
|
- |
pub fn handle_git_credential(operation: &str, host: &str, token: Option<&str>) -> String {
|
| 95 |
|
- |
match operation {
|
| 96 |
|
- |
"get" => {
|
| 97 |
|
- |
if let Some(tok) = token {
|
| 98 |
|
- |
format!("protocol=https\nhost={}\nusername=openagents-token\npassword={}\n", host, tok)
|
| 99 |
|
- |
} else {
|
| 100 |
|
- |
"".to_string()
|
|
562
|
+ |
fn url_origin(url: &reqwest::Url) -> Option<String> {
|
|
563
|
+ |
let host = url.host_str()?;
|
|
564
|
+ |
Some(match url.port() {
|
|
565
|
+ |
Some(port) => format!("{}://{}:{}", url.scheme(), host, port),
|
|
566
|
+ |
None => format!("{}://{}", url.scheme(), host),
|
|
567
|
+ |
})
|
|
568
|
+ |
}
|
|
569
|
+ |
|
|
570
|
+ |
fn urlencode(value: &str) -> String {
|
|
571
|
+ |
let mut out = String::with_capacity(value.len());
|
|
572
|
+ |
for byte in value.bytes() {
|
|
573
|
+ |
match byte {
|
|
574
|
+ |
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
|
575
|
+ |
out.push(byte as char)
|
| 101 |
576
|
|
}
|
|
577
|
+ |
_ => out.push_str(&format!("%{byte:02X}")),
|
| 102 |
578
|
|
}
|
| 103 |
|
- |
_ => "".to_string(),
|
|
579
|
+ |
}
|
|
580
|
+ |
out
|
|
581
|
+ |
}
|
|
582
|
+ |
|
|
583
|
+ |
/// A fresh idempotency key, so a retried mutation does not create a second
|
|
584
|
+ |
/// repository. Derived from the clock and the process, not from a constant: a
|
|
585
|
+ |
/// hardcoded key would make every machine's create collide with every other's.
|
|
586
|
+ |
fn idempotency_key() -> String {
|
|
587
|
+ |
let nanos = std::time::SystemTime::now()
|
|
588
|
+ |
.duration_since(std::time::UNIX_EPOCH)
|
|
589
|
+ |
.map(|d| d.as_nanos())
|
|
590
|
+ |
.unwrap_or(0);
|
|
591
|
+ |
format!("oa-{:x}-{:x}", std::process::id(), nanos)
|
|
592
|
+ |
}
|
|
593
|
+ |
|
|
594
|
+ |
// ---------------------------------------------------------------------------
|
|
595
|
+ |
// git
|
|
596
|
+ |
// ---------------------------------------------------------------------------
|
|
597
|
+ |
|
|
598
|
+ |
/// Quote a value for the shell git runs a `!`-prefixed helper through.
|
|
599
|
+ |
fn shell_argument(value: &str) -> String {
|
|
600
|
+ |
let plain = !value.is_empty()
|
|
601
|
+ |
&& value
|
|
602
|
+ |
.bytes()
|
|
603
|
+ |
.all(|byte| byte.is_ascii_alphanumeric() || b"_./:@=-".contains(&byte));
|
|
604
|
+ |
if plain {
|
|
605
|
+ |
value.to_string()
|
|
606
|
+ |
} else {
|
|
607
|
+ |
format!("'{}'", value.replace('\'', "'\"'\"'"))
|
|
608
|
+ |
}
|
|
609
|
+ |
}
|
|
610
|
+ |
|
|
611
|
+ |
/// The path of the running binary, which is the program the credential helper
|
|
612
|
+ |
/// names.
|
|
613
|
+ |
///
|
|
614
|
+ |
/// A bare `oa` would be resolved by the shell against `PATH`, and on a machine
|
|
615
|
+ |
/// that also has an older `oa` installed — the common case while this port
|
|
616
|
+ |
/// lands — git would run that one instead, which does not understand
|
|
617
|
+ |
/// `--api-url` and answers nothing. Naming the path makes the helper this CLI.
|
|
618
|
+ |
pub fn cli_program_path() -> String {
|
|
619
|
+ |
std::env::current_exe()
|
|
620
|
+ |
.ok()
|
|
621
|
+ |
.and_then(|path| path.canonicalize().ok())
|
|
622
|
+ |
.map(|path| path.display().to_string())
|
|
623
|
+ |
.unwrap_or_else(|| "oa".to_string())
|
|
624
|
+ |
}
|
|
625
|
+ |
|
|
626
|
+ |
/// The git credential helper line this CLI installs.
|
|
627
|
+ |
///
|
|
628
|
+ |
/// The `!` makes git run it as a shell command with the operation appended, so
|
|
629
|
+ |
/// `credential.<origin>.helper` resolves to `<oa> --api-url <origin> auth
|
|
630
|
+ |
/// git-credential get`.
|
|
631
|
+ |
pub fn credential_helper_command(origin: &str) -> String {
|
|
632
|
+ |
format!(
|
|
633
|
+ |
"!{} --api-url {origin} auth git-credential",
|
|
634
|
+ |
shell_argument(&cli_program_path())
|
|
635
|
+ |
)
|
|
636
|
+ |
}
|
|
637
|
+ |
|
|
638
|
+ |
pub fn credential_helper_key(origin: &str) -> String {
|
|
639
|
+ |
format!("credential.{origin}.helper")
|
|
640
|
+ |
}
|
|
641
|
+ |
|
|
642
|
+ |
fn run_git_sync(args: &[&str], directory: Option<&Path>) -> Result<(i32, String), AuthError> {
|
|
643
|
+ |
let mut command = SyncCommand::new("git");
|
|
644
|
+ |
if let Some(directory) = directory {
|
|
645
|
+ |
command.arg("-C").arg(directory);
|
|
646
|
+ |
}
|
|
647
|
+ |
command.args(args);
|
|
648
|
+ |
let output = command
|
|
649
|
+ |
.output()
|
|
650
|
+ |
.map_err(|error| AuthError::new(format!("could not run git: {error}")))?;
|
|
651
|
+ |
Ok((
|
|
652
|
+ |
output.status.code().unwrap_or(-1),
|
|
653
|
+ |
String::from_utf8_lossy(&output.stdout).to_string(),
|
|
654
|
+ |
))
|
|
655
|
+ |
}
|
|
656
|
+ |
|
|
657
|
+ |
/// Write `credential.<origin>.helper` into the local or global git config.
|
|
658
|
+ |
///
|
|
659
|
+ |
/// `directory` selects the checkout for `--local`; `None` means the working
|
|
660
|
+ |
/// directory, which is what `oa auth setup-git --local` wants.
|
|
661
|
+ |
pub fn configure_credential_helper(
|
|
662
|
+ |
origin: &str,
|
|
663
|
+ |
scope: &str,
|
|
664
|
+ |
directory: Option<&Path>,
|
|
665
|
+ |
) -> Result<(), AuthError> {
|
|
666
|
+ |
let scope_flag = if scope == "local" {
|
|
667
|
+ |
"--local"
|
|
668
|
+ |
} else {
|
|
669
|
+ |
"--global"
|
|
670
|
+ |
};
|
|
671
|
+ |
let key = credential_helper_key(origin);
|
|
672
|
+ |
let (reset, _) = run_git_sync(
|
|
673
|
+ |
&["config", scope_flag, "--replace-all", &key, ""],
|
|
674
|
+ |
directory,
|
|
675
|
+ |
)?;
|
|
676
|
+ |
if reset != 0 {
|
|
677
|
+ |
return Err(AuthError::new(format!(
|
|
678
|
+ |
"git config exited with status {reset}. Run oa auth setup-git --local inside a git repository"
|
|
679
|
+ |
)));
|
|
680
|
+ |
}
|
|
681
|
+ |
let helper = credential_helper_command(origin);
|
|
682
|
+ |
let (added, _) = run_git_sync(&["config", scope_flag, "--add", &key, &helper], directory)?;
|
|
683
|
+ |
if added != 0 {
|
|
684
|
+ |
return Err(AuthError::new(format!(
|
|
685
|
+ |
"git config exited with status {added}"
|
|
686
|
+ |
)));
|
|
687
|
+ |
}
|
|
688
|
+ |
Ok(())
|
|
689
|
+ |
}
|
|
690
|
+ |
|
|
691
|
+ |
/// Whether the helper is configured locally, globally, or not at all.
|
|
692
|
+ |
pub fn credential_helper_state(origin: &str, directory: Option<&Path>) -> (bool, bool) {
|
|
693
|
+ |
let expected = credential_helper_command(origin);
|
|
694
|
+ |
let key = credential_helper_key(origin);
|
|
695
|
+ |
let configured = |scope: &str| {
|
|
696
|
+ |
run_git_sync(&["config", scope, "--get-all", &key], directory)
|
|
697
|
+ |
.map(|(code, out)| code == 0 && out.lines().any(|line| line == expected))
|
|
698
|
+ |
.unwrap_or(false)
|
|
699
|
+ |
};
|
|
700
|
+ |
(configured("--local"), configured("--global"))
|
|
701
|
+ |
}
|
|
702
|
+ |
|
|
703
|
+ |
/// `git clone` with this CLI wired in as the only credential helper for the
|
|
704
|
+ |
/// origin, so a private repository clones without any other credential present.
|
|
705
|
+ |
pub fn git_clone_argv(url: &str, directory: Option<&str>) -> Vec<String> {
|
|
706
|
+ |
let origin = reqwest::Url::parse(url)
|
|
707
|
+ |
.ok()
|
|
708
|
+ |
.and_then(|parsed| url_origin(&parsed))
|
|
709
|
+ |
.unwrap_or_default();
|
|
710
|
+ |
let mut argv = vec![
|
|
711
|
+ |
"-c".to_string(),
|
|
712
|
+ |
"credential.helper=".to_string(),
|
|
713
|
+ |
"-c".to_string(),
|
|
714
|
+ |
format!(
|
|
715
|
+ |
"{}={}",
|
|
716
|
+ |
credential_helper_key(&origin),
|
|
717
|
+ |
credential_helper_command(&origin)
|
|
718
|
+ |
),
|
|
719
|
+ |
"clone".to_string(),
|
|
720
|
+ |
"--".to_string(),
|
|
721
|
+ |
url.to_string(),
|
|
722
|
+ |
];
|
|
723
|
+ |
if let Some(directory) = directory {
|
|
724
|
+ |
argv.push(directory.to_string());
|
|
725
|
+ |
}
|
|
726
|
+ |
argv
|
|
727
|
+ |
}
|
|
728
|
+ |
|
|
729
|
+ |
pub async fn git_clone(url: &str, directory: Option<&str>) -> Result<(), AuthError> {
|
|
730
|
+ |
let status = Command::new("git")
|
|
731
|
+ |
.args(git_clone_argv(url, directory))
|
|
732
|
+ |
.status()
|
|
733
|
+ |
.await
|
|
734
|
+ |
.map_err(|error| AuthError::new(format!("could not run git: {error}")))?;
|
|
735
|
+ |
if !status.success() {
|
|
736
|
+ |
return Err(AuthError::new(format!(
|
|
737
|
+ |
"git clone exited with status {}",
|
|
738
|
+ |
status.code().unwrap_or(-1)
|
|
739
|
+ |
)));
|
|
740
|
+ |
}
|
|
741
|
+ |
Ok(())
|
|
742
|
+ |
}
|
|
743
|
+ |
|
|
744
|
+ |
pub fn parse_git_remotes(output: &str) -> Vec<(String, String)> {
|
|
745
|
+ |
let mut remotes: Vec<(String, String)> = Vec::new();
|
|
746
|
+ |
for line in output.lines() {
|
|
747
|
+ |
let mut fields = line.split_whitespace();
|
|
748
|
+ |
let (Some(name), Some(url)) = (fields.next(), fields.next()) else {
|
|
749
|
+ |
continue;
|
|
750
|
+ |
};
|
|
751
|
+ |
if !remotes.iter().any(|(existing, _)| existing == name) {
|
|
752
|
+ |
remotes.push((name.to_string(), url.to_string()));
|
|
753
|
+ |
}
|
|
754
|
+ |
}
|
|
755
|
+ |
remotes
|
|
756
|
+ |
}
|
|
757
|
+ |
|
|
758
|
+ |
/// The `OWNER/REPO` a remote URL names, when the URL is a repository on `origin`.
|
|
759
|
+ |
///
|
|
760
|
+ |
/// A remote's *name* is a local convention — this project names the forge
|
|
761
|
+ |
/// `openagents` and reserves `origin` for the GitHub mirror, other checkouts do
|
|
762
|
+ |
/// the reverse — so the URL is what decides. A mirror is never inferred.
|
|
763
|
+ |
pub fn repository_from_remote_url(origin: &str, remote_url: &str) -> Result<String, AuthError> {
|
|
764
|
+ |
let url = reqwest::Url::parse(remote_url)
|
|
765
|
+ |
.map_err(|_| AuthError::new("that git remote URL is not an OpenAgents repository URL"))?;
|
|
766
|
+ |
let parts: Vec<&str> = url.path().split('/').collect();
|
|
767
|
+ |
let matches_origin = url_origin(&url)
|
|
768
|
+ |
.map(|value| value == origin)
|
|
769
|
+ |
.unwrap_or(false);
|
|
770
|
+ |
if !matches_origin
|
|
771
|
+ |
|| !url.username().is_empty()
|
|
772
|
+ |
|| url.password().is_some()
|
|
773
|
+ |
|| url.query().is_some()
|
|
774
|
+ |
|| url.fragment().is_some()
|
|
775
|
+ |
|| parts.len() != 3
|
|
776
|
+ |
|| !parts[2].ends_with(".git")
|
|
777
|
+ |
{
|
|
778
|
+ |
return Err(AuthError::new(
|
|
779
|
+ |
"that git remote URL is not an OpenAgents repository URL",
|
|
780
|
+ |
));
|
|
781
|
+ |
}
|
|
782
|
+ |
let owner = parts[1];
|
|
783
|
+ |
let repo = &parts[2][..parts[2].len() - 4];
|
|
784
|
+ |
if owner.is_empty() || repo.is_empty() {
|
|
785
|
+ |
return Err(AuthError::new(
|
|
786
|
+ |
"that git remote URL is not an OpenAgents repository URL",
|
|
787
|
+ |
));
|
|
788
|
+ |
}
|
|
789
|
+ |
Ok(format!("{owner}/{repo}"))
|
|
790
|
+ |
}
|
|
791
|
+ |
|
|
792
|
+ |
/// The repository this checkout belongs to, or a refusal that names what it
|
|
793
|
+ |
/// looked at. Never a guess.
|
|
794
|
+ |
pub fn infer_repository(origin: &str, directory: Option<&Path>) -> Result<String, AuthError> {
|
|
795
|
+ |
let (code, listed) = run_git_sync(&["remote", "-v"], directory)?;
|
|
796
|
+ |
if code != 0 {
|
|
797
|
+ |
return Err(AuthError::new(
|
|
798
|
+ |
"could not read the git remotes of this directory. Pass OWNER/REPO instead",
|
|
799
|
+ |
));
|
|
800
|
+ |
}
|
|
801
|
+ |
let remotes = parse_git_remotes(&listed);
|
|
802
|
+ |
if remotes.is_empty() {
|
|
803
|
+ |
return Err(AuthError::new(format!(
|
|
804
|
+ |
"this checkout has no git remotes. Pass OWNER/REPO, or add a remote for {origin}"
|
|
805
|
+ |
)));
|
|
806
|
+ |
}
|
|
807
|
+ |
// Prefer the forge remote by name only as a tie-break among admitted URLs.
|
|
808
|
+ |
let mut ordered: Vec<&(String, String)> = Vec::new();
|
|
809
|
+ |
for preferred in ["openagents", "origin", "upstream"] {
|
|
810
|
+ |
if let Some(remote) = remotes.iter().find(|(name, _)| name == preferred) {
|
|
811
|
+ |
ordered.push(remote);
|
|
812
|
+ |
}
|
|
813
|
+ |
}
|
|
814
|
+ |
for remote in &remotes {
|
|
815
|
+ |
if !ordered.iter().any(|(name, _)| *name == remote.0) {
|
|
816
|
+ |
ordered.push(remote);
|
|
817
|
+ |
}
|
|
818
|
+ |
}
|
|
819
|
+ |
let mut rejected: Vec<String> = Vec::new();
|
|
820
|
+ |
for (name, url) in ordered {
|
|
821
|
+ |
match repository_from_remote_url(origin, url) {
|
|
822
|
+ |
Ok(repository) => return Ok(repository),
|
|
823
|
+ |
Err(_) => rejected.push(format!("{name} {url}")),
|
|
824
|
+ |
}
|
|
825
|
+ |
}
|
|
826
|
+ |
Err(AuthError::new(format!(
|
|
827
|
+ |
"no git remote of this checkout is a repository on {origin}: {}. \
|
|
828
|
+ |
A remote's name does not decide this; its URL does. Pass OWNER/REPO instead",
|
|
829
|
+ |
rejected.join("; ")
|
|
830
|
+ |
)))
|
|
831
|
+ |
}
|
|
832
|
+ |
|
|
833
|
+ |
// ---------------------------------------------------------------------------
|
|
834
|
+ |
// git credential helper protocol
|
|
835
|
+ |
// ---------------------------------------------------------------------------
|
|
836
|
+ |
|
|
837
|
+ |
/// Parse git's `key=value` credential request, keeping only the fields that
|
|
838
|
+ |
/// decide admission.
|
|
839
|
+ |
pub fn parse_git_credential_request(input: &str) -> Vec<(String, String)> {
|
|
840
|
+ |
let mut fields = Vec::new();
|
|
841
|
+ |
for line in input.split(['\n', '\r']) {
|
|
842
|
+ |
let Some(separator) = line.find('=') else {
|
|
843
|
+ |
continue;
|
|
844
|
+ |
};
|
|
845
|
+ |
if separator == 0 {
|
|
846
|
+ |
continue;
|
|
847
|
+ |
}
|
|
848
|
+ |
let key = &line[..separator];
|
|
849
|
+ |
let value = &line[separator + 1..];
|
|
850
|
+ |
if matches!(key, "protocol" | "host" | "path") {
|
|
851
|
+ |
fields.push((key.to_string(), value.to_string()));
|
|
852
|
+ |
}
|
|
853
|
+ |
}
|
|
854
|
+ |
fields
|
|
855
|
+ |
}
|
|
856
|
+ |
|
|
857
|
+ |
/// Whether this request is for the endpoint the CLI holds a token for.
|
|
858
|
+ |
///
|
|
859
|
+ |
/// git asks every configured helper for every host. Answering one for
|
|
860
|
+ |
/// `github.com` would hand an OpenAgents token to GitHub.
|
|
861
|
+ |
pub fn admitted_credential_request(origin: &str, fields: &[(String, String)]) -> bool {
|
|
862
|
+ |
let Ok(url) = reqwest::Url::parse(origin) else {
|
|
863
|
+ |
return false;
|
|
864
|
+ |
};
|
|
865
|
+ |
let Some(host) = url.host_str() else {
|
|
866
|
+ |
return false;
|
|
867
|
+ |
};
|
|
868
|
+ |
let authority = match url.port() {
|
|
869
|
+ |
Some(port) => format!("{host}:{port}"),
|
|
870
|
+ |
None => host.to_string(),
|
|
871
|
+ |
};
|
|
872
|
+ |
let field = |key: &str| {
|
|
873
|
+ |
fields
|
|
874
|
+ |
.iter()
|
|
875
|
+ |
.find(|(name, _)| name == key)
|
|
876
|
+ |
.map(|(_, value)| value.as_str())
|
|
877
|
+ |
};
|
|
878
|
+ |
field("protocol") == Some(url.scheme()) && field("host") == Some(authority.as_str())
|
|
879
|
+ |
}
|
|
880
|
+ |
|
|
881
|
+ |
/// The answer written on stdout for an admitted `get`. The username is ignored
|
|
882
|
+ |
/// by the forge; the token travels as the password.
|
|
883
|
+ |
pub fn credential_answer(token: &Secret) -> String {
|
|
884
|
+ |
format!("username=openagents\npassword={}\n\n", token.expose())
|
|
885
|
+ |
}
|
|
886
|
+ |
|
|
887
|
+ |
/// Run the helper protocol against a store.
|
|
888
|
+ |
///
|
|
889
|
+ |
/// Returns the bytes to write on stdout, which is empty for every case that is
|
|
890
|
+ |
/// not an admitted `get` holding a token. Silence is the protocol's way of
|
|
891
|
+ |
/// saying "I have nothing", and it is the only honest answer when there is no
|
|
892
|
+ |
/// credential: an invented one would make git retry against the server with a
|
|
893
|
+ |
/// password that was never issued.
|
|
894
|
+ |
pub fn run_git_credential_helper(
|
|
895
|
+ |
origin: &str,
|
|
896
|
+ |
operation: &str,
|
|
897
|
+ |
input: &str,
|
|
898
|
+ |
store: &crate::auth::CredentialStore,
|
|
899
|
+ |
) -> Result<String, AuthError> {
|
|
900
|
+ |
if input.len() > 8_192 {
|
|
901
|
+ |
return Err(AuthError::new(
|
|
902
|
+ |
"the git credential request exceeded 8192 bytes",
|
|
903
|
+ |
));
|
|
904
|
+ |
}
|
|
905
|
+ |
let fields = parse_git_credential_request(input);
|
|
906
|
+ |
if !admitted_credential_request(origin, &fields) {
|
|
907
|
+ |
return Ok(String::new());
|
|
908
|
+ |
}
|
|
909
|
+ |
match operation {
|
|
910
|
+ |
"erase" => {
|
|
911
|
+ |
store.remove()?;
|
|
912
|
+ |
Ok(String::new())
|
|
913
|
+ |
}
|
|
914
|
+ |
"store" => Ok(String::new()),
|
|
915
|
+ |
"get" => match store.find_token()? {
|
|
916
|
+ |
Some(stored) => Ok(credential_answer(&stored.token)),
|
|
917
|
+ |
None => Ok(String::new()),
|
|
918
|
+ |
},
|
|
919
|
+ |
other => Err(AuthError::new(format!(
|
|
920
|
+ |
"unknown git credential operation {other}. Use get, store, or erase"
|
|
921
|
+ |
))),
|
|
922
|
+ |
}
|
|
923
|
+ |
}
|
|
924
|
+ |
|
|
925
|
+ |
/// Read git's request from stdin, bounded.
|
|
926
|
+ |
pub fn read_credential_stdin() -> Result<String, AuthError> {
|
|
927
|
+ |
let mut buffer = Vec::new();
|
|
928
|
+ |
std::io::stdin()
|
|
929
|
+ |
.take(8_193)
|
|
930
|
+ |
.read_to_end(&mut buffer)
|
|
931
|
+ |
.map_err(|error| {
|
|
932
|
+ |
AuthError::new(format!(
|
|
933
|
+ |
"the credential helper could not read git input: {error}"
|
|
934
|
+ |
))
|
|
935
|
+ |
})?;
|
|
936
|
+ |
Ok(String::from_utf8_lossy(&buffer).to_string())
|
|
937
|
+ |
}
|
|
938
|
+ |
|
|
939
|
+ |
#[cfg(test)]
|
|
940
|
+ |
mod tests {
|
|
941
|
+ |
use super::*;
|
|
942
|
+ |
|
|
943
|
+ |
#[test]
|
|
944
|
+ |
fn names_and_targets_are_validated() {
|
|
945
|
+ |
assert_eq!(
|
|
946
|
+ |
validate_repository_name("OpenAgents").unwrap(),
|
|
947
|
+ |
"openagents"
|
|
948
|
+ |
);
|
|
949
|
+ |
assert_eq!(
|
|
950
|
+ |
validate_repository_name("open.agents").unwrap(),
|
|
951
|
+ |
"open.agents"
|
|
952
|
+ |
);
|
|
953
|
+ |
assert!(validate_repository_name("open.").is_err());
|
|
954
|
+ |
assert!(validate_repository_name("-open").is_err());
|
|
955
|
+ |
assert!(validate_repository_name("").is_err());
|
|
956
|
+ |
assert_eq!(
|
|
957
|
+ |
parse_repository_target("OpenAgentsInc/openagents").unwrap(),
|
|
958
|
+ |
("OpenAgentsInc".to_string(), "openagents".to_string())
|
|
959
|
+ |
);
|
|
960
|
+ |
assert!(parse_repository_target("openagents").is_err());
|
|
961
|
+ |
assert!(parse_repository_target("a/b/c").is_err());
|
|
962
|
+ |
}
|
|
963
|
+ |
|
|
964
|
+ |
#[test]
|
|
965
|
+ |
fn only_the_selected_origin_is_admitted() {
|
|
966
|
+ |
let fields = parse_git_credential_request("protocol=https\nhost=openagents.com\n\n");
|
|
967
|
+ |
assert!(admitted_credential_request(
|
|
968
|
+ |
"https://openagents.com",
|
|
969
|
+ |
&fields
|
|
970
|
+ |
));
|
|
971
|
+ |
assert!(!admitted_credential_request(
|
|
972
|
+ |
"https://staging.openagents.com",
|
|
973
|
+ |
&fields
|
|
974
|
+ |
));
|
|
975
|
+ |
let github = parse_git_credential_request("protocol=https\nhost=github.com\n");
|
|
976
|
+ |
assert!(!admitted_credential_request(
|
|
977
|
+ |
"https://openagents.com",
|
|
978
|
+ |
&github
|
|
979
|
+ |
));
|
|
980
|
+ |
}
|
|
981
|
+ |
|
|
982
|
+ |
#[test]
|
|
983
|
+ |
fn remote_urls_decide_the_repository_not_remote_names() {
|
|
984
|
+ |
assert_eq!(
|
|
985
|
+ |
repository_from_remote_url(
|
|
986
|
+ |
"https://openagents.com",
|
|
987
|
+ |
"https://openagents.com/OpenAgentsInc/openagents.git"
|
|
988
|
+ |
)
|
|
989
|
+ |
.unwrap(),
|
|
990
|
+ |
"OpenAgentsInc/openagents"
|
|
991
|
+ |
);
|
|
992
|
+ |
assert!(repository_from_remote_url(
|
|
993
|
+ |
"https://openagents.com",
|
|
994
|
+ |
"https://github.com/OpenAgentsInc/openagents.git"
|
|
995
|
+ |
)
|
|
996
|
+ |
.is_err());
|
|
997
|
+ |
assert!(repository_from_remote_url(
|
|
998
|
+ |
"https://openagents.com",
|
|
999
|
+ |
"https://openagents.com/OpenAgentsInc/openagents"
|
|
1000
|
+ |
)
|
|
1001
|
+ |
.is_err());
|
|
1002
|
+ |
}
|
|
1003
|
+ |
|
|
1004
|
+ |
#[test]
|
|
1005
|
+ |
fn clone_argv_pins_this_cli_as_the_only_helper() {
|
|
1006
|
+ |
let argv = git_clone_argv("https://openagents.com/a/b.git", Some("dest"));
|
|
1007
|
+ |
assert_eq!(argv[0], "-c");
|
|
1008
|
+ |
assert_eq!(argv[1], "credential.helper=");
|
|
1009
|
+ |
assert_eq!(
|
|
1010
|
+ |
argv[3],
|
|
1011
|
+ |
format!(
|
|
1012
|
+ |
"credential.https://openagents.com.helper={}",
|
|
1013
|
+ |
credential_helper_command("https://openagents.com")
|
|
1014
|
+ |
)
|
|
1015
|
+ |
);
|
|
1016
|
+ |
// The helper names this binary, not a bare `oa` the shell would resolve
|
|
1017
|
+ |
// against PATH — where an older install would answer instead.
|
|
1018
|
+ |
assert!(argv[3].contains(&cli_program_path()), "{}", argv[3]);
|
|
1019
|
+ |
assert_eq!(argv[argv.len() - 1], "dest");
|
| 104 |
1020
|
|
}
|
| 105 |
1021
|
|
}
|