Debian Codegraph @

src/launchpad.rs

raw symbols SCIP
1 //! Launchpad PPA (Personal Package Archive) integration
2 //!
3 //! This module provides functionality for handling Personal Package Archives (PPAs) in a
4 //! Debian/Ubuntu context, including API integration using launchpadlib for authenticated access.
5
6 use launchpadlib::blocking::v1_0::{self, ArchiveFull, PersonOrTeam};
7 use launchpadlib::blocking::Client;
8 use launchpadlib::Error as WadlError;
9 use std::fmt;
10 use url::Url;
11
12 const CONSUMER_KEY: &str = "apt-add-repository";
13
14 /// Default URL for Launchpad PPAs
15 pub const LAUNCHPAD_PPA_URL: &str = "https://ppa.launchpadcontent.net";
16
17 /// Valid components for PPAs
18 pub const VALID_PPA_COMPONENTS: &[&str] = &["main", "main/debug"];
19
20 /// Information about a PPA (Personal Package Archive)
21 #[derive(Debug, Clone)]
22 pub struct PpaInfo {
23 /// The PPA owner's username
24 pub user: String,
25 /// The PPA name
26 pub name: String,
27 }
28
29 impl PpaInfo {
30 /// Parse a PPA specification string (e.g., "ppa:user/ppa-name")
31 pub fn parse(ppa_spec: &str) -> Result<PpaInfo, String> {
32 if !ppa_spec.starts_with("ppa:") {
33 return Err("Not a PPA format".to_string());
34 }
35
36 let ppa_part = &ppa_spec[4..];
37 let parts: Vec<&str> = ppa_part.split('/').collect();
38
39 if parts.len() != 2 {
40 return Err("Invalid PPA format. Expected ppa:user/ppa-name".to_string());
41 }
42
43 Ok(PpaInfo {
44 user: parts[0].to_string(),
45 name: parts[1].to_string(),
46 })
47 }
48
49 /// Try to extract PPA info from a Repository by parsing its URLs
50 ///
51 /// Returns `Some(PpaInfo)` if the repository URL matches the PPA URL pattern.
52 pub fn from_repository(repo: &crate::Repository) -> Option<PpaInfo> {
53 for uri in &repo.uris {
54 let url_str = uri.as_str();
55 // Check for PPA URLs like:
56 // https://ppa.launchpadcontent.net/user/ppa-name/ubuntu
57 // http://ppa.launchpad.net/user/ppa-name/ubuntu
58 if url_str.contains("ppa.launchpadcontent.net") || url_str.contains("ppa.launchpad.net")
59 {
60 let path = uri.path();
61 let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
62 if parts.len() >= 2 {
63 return Some(PpaInfo {
64 user: parts[0].to_string(),
65 name: parts[1].to_string(),
66 });
67 }
68 }
69 }
70 None
71 }
72
73 /// Generate the repository URL for this PPA
74 pub fn repository_url(&self, _codename: &str) -> Result<Url, String> {
75 Url::parse(&format!(
76 "{}/{}/{}/ubuntu",
77 LAUNCHPAD_PPA_URL, self.user, self.name
78 ))
79 .map_err(|e| format!("Failed to construct PPA URL: {e}"))
80 }
81
82 /// Generate a filename for this PPA
83 pub fn filename(&self, extension: &str) -> String {
84 format!("{}-ubuntu-{}.{}", self.user, self.name, extension)
85 }
86
87 /// Generate a keyring filename for this PPA
88 pub fn keyring_filename(&self) -> String {
89 format!("{}-{}-keyring.asc", self.user, self.name)
90 }
91 }
92
93 /// Result of validating a PPA
94 #[derive(Debug, Clone)]
95 pub struct PpaValidationResult {
96 /// Whether the PPA exists
97 pub exists: bool,
98 /// Whether the PPA is private
99 pub is_private: bool,
100 /// Whether the PPA publishes debug symbols
101 pub publishes_debug_symbols: bool,
102 /// Display name of the PPA
103 pub display_name: String,
104 }
105
106 /// Validate PPA components
107 pub fn validate_ppa_components(components: &[String]) -> Result<(), String> {
108 for component in components {
109 if !VALID_PPA_COMPONENTS.contains(&component.as_str()) {
110 return Err(format!(
111 "Invalid component '{}' for PPA.\n\
112 Valid components are: {}\n\
113 Suggestion: Use 'main' for regular packages or 'main/debug' for debug symbols.",
114 component,
115 VALID_PPA_COMPONENTS.join(", ")
116 ));
117 }
118 }
119 Ok(())
120 }
121
122 /// Errors that can occur when interacting with the Launchpad API
123 #[derive(Debug)]
124 pub enum Error {
125 /// Failed to authenticate with Launchpad
126 Authentication(String),
127 /// Failed to connect to Launchpad API
128 Api(WadlError),
129 /// The requested user was not found
130 UserNotFound(String),
131 /// The requested PPA was not found
132 PpaNotFound {
133 /// The user or team name
134 user: String,
135 /// The PPA name
136 name: String,
137 },
138 /// No signing key is configured for the PPA
139 NoSigningKey,
140 /// Failed to download the signing key
141 KeyDownload(reqwest::Error),
142 /// The keyserver returned an error status
143 KeyserverError(reqwest::StatusCode),
144 /// Failed to read key data
145 KeyRead(reqwest::Error),
146 /// Key fingerprint verification failed
147 #[cfg(feature = "key-management")]
148 KeyVerification(String),
149 /// Not authenticated - no current user available
150 NotAuthenticated,
151 /// PPA has no self link
152 MissingSelfLink,
153 /// Failed to get subscription URL
154 SubscriptionUrl(WadlError),
155 /// Invalid subscription URL returned by API
156 InvalidSubscriptionUrl {
157 /// The invalid URL string
158 url: String,
159 /// The parse error
160 error: url::ParseError,
161 },
162 /// Failed to create HTTP client
163 HttpClient(reqwest::Error),
164 /// Launchpad API returned unexpected response
165 UnexpectedResponse(String),
166 }
167
168 impl fmt::Display for Error {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 match self {
171 Error::Authentication(msg) => {
172 write!(f, "Failed to authenticate with Launchpad: {}", msg)
173 }
174 Error::Api(e) => write!(f, "Launchpad API error: {}", e),
175 Error::UserNotFound(user) => write!(f, "User '{}' not found on Launchpad", user),
176 Error::PpaNotFound { user, name } => {
177 write!(f, "PPA '{}/{}' not found", user, name)
178 }
179 Error::NoSigningKey => write!(f, "PPA has no signing key configured"),
180 Error::KeyDownload(e) => write!(f, "Failed to download signing key: {}", e),
181 Error::KeyserverError(status) => {
182 write!(f, "Keyserver returned error status: {}", status)
183 }
184 Error::KeyRead(e) => write!(f, "Failed to read key data: {}", e),
185 #[cfg(feature = "key-management")]
186 Error::KeyVerification(msg) => {
187 write!(f, "Key fingerprint verification failed: {}", msg)
188 }
189 Error::NotAuthenticated => {
190 write!(f, "Not authenticated - no current user available")
191 }
192 Error::MissingSelfLink => write!(f, "PPA has no self link"),
193 Error::SubscriptionUrl(e) => write!(f, "Failed to get subscription URL: {}", e),
194 Error::InvalidSubscriptionUrl { url, error } => {
195 write!(f, "Invalid subscription URL '{}': {}", url, error)
196 }
197 Error::HttpClient(e) => write!(f, "Failed to create HTTP client: {}", e),
198 Error::UnexpectedResponse(msg) => {
199 write!(f, "Unexpected response from Launchpad: {}", msg)
200 }
201 }
202 }
203 }
204
205 impl std::error::Error for Error {
206 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
207 match self {
208 Error::Api(e) => Some(e),
209 Error::KeyDownload(e) => Some(e),
210 Error::KeyRead(e) => Some(e),
211 Error::SubscriptionUrl(e) => Some(e),
212 Error::InvalidSubscriptionUrl { error, .. } => Some(error),
213 Error::HttpClient(e) => Some(e),
214 _ => None,
215 }
216 }
217 }
218
219 impl From<WadlError> for Error {
220 fn from(e: WadlError) -> Self {
221 Error::Api(e)
222 }
223 }
224
225 /// Result of downloading a PPA signing key
226 #[derive(Debug, Clone)]
227 pub struct PpaSigningKey {
228 /// The armored GPG key data
229 pub key_data: String,
230 /// The key fingerprint
231 pub fingerprint: String,
232 }
233
234 /// Get a PPA by user and name
235 fn get_ppa(client: &Client, user: &str, name: &str) -> Result<ArchiveFull, Error> {
236 let service_root = v1_0::service_root(client)?;
237
238 let people = service_root
239 .people()
240 .ok_or_else(|| Error::UnexpectedResponse("No people collection".to_string()))?;
241
242 let person_or_team = people.get_by_name(client, user).map_err(|e| {
243 // Check if this is a 404 (user not found) or another error
244 if matches!(e, WadlError::UnhandledStatus(s) if s.as_u16() == 404) {
245 Error::UserNotFound(user.to_string())
246 } else {
247 Error::Api(e)
248 }
249 })?;
250
251 // Note: get_ppaby_name is on Person/Team, not PersonFull/TeamFull
252 let ppa = match person_or_team {
253 PersonOrTeam::Person(person) => person.get_ppaby_name(client, None, name).map_err(|e| {
254 if matches!(e, WadlError::UnhandledStatus(s) if s.as_u16() == 404) {
255 Error::PpaNotFound {
256 user: user.to_string(),
257 name: name.to_string(),
258 }
259 } else {
260 Error::Api(e)
261 }
262 })?,
263 PersonOrTeam::Team(team) => team.get_ppaby_name(client, None, name).map_err(|e| {
264 if matches!(e, WadlError::UnhandledStatus(s) if s.as_u16() == 404) {
265 Error::PpaNotFound {
266 user: user.to_string(),
267 name: name.to_string(),
268 }
269 } else {
270 Error::Api(e)
271 }
272 })?,
273 };
274
275 Ok(ppa)
276 }
277
278 /// Validate a PPA using launchpadlib
279 ///
280 /// This provides authenticated access to Launchpad, which is required for private PPAs.
281 pub fn validate_ppa(ppa_info: &PpaInfo, auth_required: bool) -> Result<PpaValidationResult, Error> {
282 let client = if auth_required {
283 Client::authenticated(None, CONSUMER_KEY)
284 .map_err(|e| Error::Authentication(e.to_string()))?
285 } else {
286 Client::anonymous(CONSUMER_KEY)
287 };
288
289 match get_ppa(&client, &ppa_info.user, &ppa_info.name) {
290 Ok(ppa) => Ok(PpaValidationResult {
291 exists: true,
292 is_private: ppa.private,
293 publishes_debug_symbols: false, // Not available in API
294 display_name: ppa.displayname,
295 }),
296 Err(Error::PpaNotFound { .. }) | Err(Error::UserNotFound(_)) => Ok(PpaValidationResult {
297 exists: false,
298 is_private: false,
299 publishes_debug_symbols: false,
300 display_name: String::new(),
301 }),
302 Err(e) => Err(e),
303 }
304 }
305
306 /// Get the subscription URL for a private PPA
307 ///
308 /// This requires authentication with Launchpad and returns the URL that includes
309 /// the user's subscription credentials.
310 pub fn get_private_ppa_url(ppa_info: &PpaInfo) -> Result<Url, Error> {
311 let client = Client::authenticated(None, CONSUMER_KEY)
312 .map_err(|e| Error::Authentication(e.to_string()))?;
313
314 // Get the service root and the current user
315 let service_root = v1_0::service_root(&client)?;
316
317 let me = service_root.me().ok_or(Error::NotAuthenticated)?;
318
319 // Get the PPA
320 let ppa = get_ppa(&client, &ppa_info.user, &ppa_info.name)?;
321
322 // Get the Archive reference from the PPA
323 let archive = ppa.self_().ok_or(Error::MissingSelfLink)?;
324
325 // Get the subscription URL for this archive
326 let subscription_url = me
327 .get_archive_subscription_url(&client, &archive)
328 .map_err(Error::SubscriptionUrl)?;
329
330 Url::parse(&subscription_url).map_err(|e| Error::InvalidSubscriptionUrl {
331 url: subscription_url,
332 error: e,
333 })
334 }
335
336 /// Download PPA signing key using launchpadlib
337 ///
338 /// This provides authenticated access which may be required for private PPAs.
339 /// Returns the key data and fingerprint for verification and logging.
340 pub fn download_ppa_signing_key(
341 ppa_info: &PpaInfo,
342 auth_required: bool,
343 ) -> Result<PpaSigningKey, Error> {
344 let client = if auth_required {
345 Client::authenticated(None, CONSUMER_KEY)
346 .map_err(|e| Error::Authentication(e.to_string()))?
347 } else {
348 Client::anonymous(CONSUMER_KEY)
349 };
350
351 let ppa = get_ppa(&client, &ppa_info.user, &ppa_info.name)?;
352
353 let fingerprint = ppa.signing_key_fingerprint;
354 if fingerprint.is_empty() {
355 return Err(Error::NoSigningKey);
356 }
357
358 // Download the key data from the keyserver
359 // The key is available at: https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{fingerprint}
360 let key_url = format!(
361 "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{}",
362 fingerprint
363 );
364
365 let http_client = reqwest::blocking::Client::builder()
366 .timeout(std::time::Duration::from_secs(30))
367 .build()
368 .map_err(Error::HttpClient)?;
369
370 let response = http_client
371 .get(&key_url)
372 .send()
373 .map_err(Error::KeyDownload)?;
374
375 if !response.status().is_success() {
376 return Err(Error::KeyserverError(response.status()));
377 }
378
379 let key_data = response.text().map_err(Error::KeyRead)?;
380
381 // Verify the key fingerprint matches
382 #[cfg(feature = "key-management")]
383 crate::key_management::verify_key_fingerprint(&key_data, &fingerprint)
384 .map_err(|e| Error::KeyVerification(e.to_string()))?;
385
386 Ok(PpaSigningKey {
387 key_data,
388 fingerprint,
389 })
390 }
391
392 #[cfg(test)]
393 mod tests {
394 use super::*;
395
396 #[test]
397 fn test_parse_ppa_format() {
398 // Valid PPA
399 let ppa = PpaInfo::parse("ppa:user/repo").unwrap();
400 assert_eq!(ppa.user, "user");
401 assert_eq!(ppa.name, "repo");
402
403 // Invalid formats
404 assert!(PpaInfo::parse("not-a-ppa").is_err());
405 assert!(PpaInfo::parse("ppa:invalid").is_err());
406 assert!(PpaInfo::parse("ppa:too/many/parts").is_err());
407 }
408
409 #[test]
410 fn test_validate_ppa_components() {
411 assert!(validate_ppa_components(&["main".to_string()]).is_ok());
412 assert!(validate_ppa_components(&["main/debug".to_string()]).is_ok());
413 assert!(validate_ppa_components(&["invalid".to_string()]).is_err());
414 }
415
416 #[test]
417 fn test_ppa_filename() {
418 let ppa = PpaInfo {
419 user: "test-user".to_string(),
420 name: "test-repo".to_string(),
421 };
422
423 assert_eq!(ppa.filename("list"), "test-user-ubuntu-test-repo.list");
424 assert_eq!(
425 ppa.filename("sources"),
426 "test-user-ubuntu-test-repo.sources"
427 );
428
429 // Test with empty extension
430 assert_eq!(ppa.filename(""), "test-user-ubuntu-test-repo.");
431
432 // Test with special characters (they remain as-is)
433 let ppa_special = PpaInfo {
434 user: "user_123".to_string(),
435 name: "repo-name".to_string(),
436 };
437 assert_eq!(
438 ppa_special.filename("list"),
439 "user_123-ubuntu-repo-name.list"
440 );
441 }
442 }