1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use crate::error::*;
use oci_spec::distribution::ErrorResponse;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fs, io, path::*};
use url::Url;

/// Authentication info stored in filesystem
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct StoredAuth {
    auths: HashMap<String, Auth>,
}

impl StoredAuth {
    /// Load authentication info stored by ocipkg
    pub fn load() -> Result<Self> {
        let mut auth = StoredAuth::default();
        if let Some(path) = auth_path() {
            let new = Self::from_path(&path)?;
            auth.append(new)?;
        }
        Ok(auth)
    }

    /// Load authentication info with docker and podman setting
    pub fn load_all() -> Result<Self> {
        let mut auth = StoredAuth::default();
        if let Some(path) = docker_auth_path() {
            if let Ok(new) = Self::from_path(&path) {
                auth.append(new)?;
            }
        }
        if let Some(path) = podman_auth_path() {
            if let Ok(new) = Self::from_path(&path) {
                auth.append(new)?;
            }
        }
        if let Some(path) = auth_path() {
            let new = Self::from_path(&path)?;
            auth.append(new)?;
        }
        Ok(auth)
    }

    pub fn insert(&mut self, domain: &str, octet: String) {
        self.auths.insert(domain.to_string(), Auth { auth: octet });
    }

    pub fn save(&self) -> Result<()> {
        let path = auth_path().ok_or(Error::NoValidRuntimeDirectory)?;
        let parent = path.parent().unwrap();
        if !parent.exists() {
            fs::create_dir_all(parent)?;
        }
        let f = fs::File::create(&path)?;
        serde_json::to_writer_pretty(f, self)?;
        Ok(())
    }

    /// Get token by trying to access API root `/v2/`
    ///
    /// Returns `None` if no authentication is required.
    pub fn get_token(&self, url: &url::Url) -> Result<Option<String>> {
        let test_url = url.join("/v2/").unwrap();
        let www_auth = match ureq::get(test_url.as_str()).call() {
            Ok(_) => return Ok(None),
            Err(ureq::Error::Status(status, res)) => {
                if status == 401 {
                    res.header("www-authenticate").unwrap().to_string()
                } else {
                    let err = res.into_json::<ErrorResponse>()?;
                    return Err(Error::RegistryError(err));
                }
            }
            Err(ureq::Error::Transport(e)) => return Err(Error::NetworkError(e)),
        };

        let challenge = AuthChallenge::from_header(&www_auth)?;
        self.challenge(&challenge).map(Some)
    }

    /// Get token based on WWW-Authentication header
    pub fn challenge(&self, challenge: &AuthChallenge) -> Result<String> {
        let token_url = Url::parse(&challenge.url)?;
        let domain = token_url
            .domain()
            .expect("www-authenticate header returns invalid URL");

        let mut req = ureq::get(token_url.as_str()).set("Accept", "application/json");
        if let Some(auth) = self.auths.get(domain) {
            req = req.set("Authorization", &format!("Basic {}", auth.auth))
        }
        req = req
            .query("scope", &challenge.scope)
            .query("service", &challenge.service);
        match req.call() {
            Ok(res) => {
                let token = res.into_json::<Token>()?;
                Ok(token.token)
            }
            Err(ureq::Error::Status(..)) => Err(Error::AuthorizationFailed(token_url.clone())),
            Err(ureq::Error::Transport(e)) => Err(Error::NetworkError(e)),
        }
    }

    pub fn append(&mut self, other: Self) -> Result<()> {
        for (key, value) in other.auths.into_iter() {
            self.auths.insert(key, value);
        }
        Ok(())
    }

    fn from_path(path: &Path) -> Result<Self> {
        if path.is_file() {
            let f = fs::File::open(path)?;
            Ok(serde_json::from_reader(io::BufReader::new(f))?)
        } else {
            Ok(Self::default())
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Auth {
    auth: String,
}

fn auth_path() -> Option<PathBuf> {
    directories::ProjectDirs::from("", "", "ocipkg")
        .and_then(|dirs| Some(dirs.runtime_dir()?.join("auth.json")))
        .or_else(|| {
            // Most of container does not set XDG_RUNTIME_DIR,
            // and then this fallback to `~/.ocipkg/config.json` like docker.
            let dirs = directories::BaseDirs::new()?;
            Some(dirs.home_dir().join(".ocipkg/config.json"))
        })
}

fn docker_auth_path() -> Option<PathBuf> {
    let dirs = directories::BaseDirs::new()?;
    Some(dirs.home_dir().join(".docker/config.json"))
}

fn podman_auth_path() -> Option<PathBuf> {
    let dirs = directories::ProjectDirs::from("", "", "containers")?;
    Some(dirs.runtime_dir()?.join("auth.json"))
}

/// WWW-Authentication challenge
///
/// ```
/// use ocipkg::distribution::AuthChallenge;
///
/// let auth = AuthChallenge::from_header(
///   r#"Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:termoshtt/ocipkg/rust-lib:pull""#,
/// ).unwrap();
///
/// assert_eq!(auth, AuthChallenge {
///   url: "https://ghcr.io/token".to_string(),
///   service: "ghcr.io".to_string(),
///   scope: "repository:termoshtt/ocipkg/rust-lib:pull".to_string(),
/// });
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthChallenge {
    pub url: String,
    pub service: String,
    pub scope: String,
}

impl AuthChallenge {
    pub fn from_header(header: &str) -> Result<Self> {
        let err = || Error::UnSupportedAuthHeader(header.to_string());
        let (ty, realm) = header.split_once(' ').ok_or_else(err)?;
        if ty != "Bearer" {
            return Err(err());
        }

        let mut url = None;
        let mut service = None;
        let mut scope = None;
        for param in realm.split(',') {
            let (key, value) = param.split_once('=').ok_or_else(err)?;
            let value = value.trim_matches('"').to_string();
            match key {
                "realm" => url = Some(value),
                "service" => service = Some(value),
                "scope" => scope = Some(value),
                _ => continue,
            }
        }
        Ok(Self {
            url: url.ok_or_else(err)?,
            service: service.ok_or_else(err)?,
            scope: scope.ok_or_else(err)?,
        })
    }
}

#[derive(Deserialize)]
struct Token {
    token: String,
}