aboutsummaryrefslogtreecommitdiffstats
path: root/git-lfs-authenticate/src/main.rs
blob: 36d78181efb2f618cc7ef719be16f9d25ddb5222 (plain) (blame)
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use std::{fmt, process::ExitCode, time::Duration};

use chrono::Utc;
use common::{Operation, ParseOperationError};

fn help() {
    eprintln!("Usage: git-lfs-authenticate <REPO> upload/download");
}

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
enum RepoNameError {
    TooLong,
    UnresolvedPath,
    AbsolutePath,
    MissingGitSuffix,
}

impl fmt::Display for RepoNameError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::TooLong => write!(f, "too long (more than 100 characters)"),
            Self::UnresolvedPath => {
                write!(f, "contains path one or more path elements '.' and '..'")
            }
            Self::AbsolutePath => {
                write!(f, "starts with '/', which is not allowed")
            }
            Self::MissingGitSuffix => write!(f, "misses '.git' suffix"),
        }
    }
}

// Using `Result<(), E>` here instead of `Option<E>` because `None` typically signifies some error
// state with no further details provided. If we were to return an `Option` type, the user would
// have to first transform it into a `Result` type in order to use the `?` operator, meaning that
// they would have to the following operation to get the type into the right shape:
// `validate_repo_path(path).map_or(Ok(()), Err)`. That would not be very ergonomic.
fn validate_repo_path(path: &str) -> Result<(), RepoNameError> {
    if path.len() > 100 {
        return Err(RepoNameError::TooLong);
    }
    if path.contains("//")
        || path.contains("/./")
        || path.contains("/../")
        || path.starts_with("./")
        || path.starts_with("../")
    {
        return Err(RepoNameError::UnresolvedPath);
    }
    if path.starts_with('/') {
        return Err(RepoNameError::AbsolutePath);
    }
    if !path.ends_with(".git") {
        return Err(RepoNameError::MissingGitSuffix);
    }
    Ok(())
}

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
enum ParseCmdlineError {
    UnknownOperation(ParseOperationError),
    InvalidRepoName(RepoNameError),
    UnexpectedArgCount(ArgCountError),
}

impl From<RepoNameError> for ParseCmdlineError {
    fn from(value: RepoNameError) -> Self {
        Self::InvalidRepoName(value)
    }
}

impl From<ParseOperationError> for ParseCmdlineError {
    fn from(value: ParseOperationError) -> Self {
        Self::UnknownOperation(value)
    }
}

impl From<ArgCountError> for ParseCmdlineError {
    fn from(value: ArgCountError) -> Self {
        Self::UnexpectedArgCount(value)
    }
}

impl fmt::Display for ParseCmdlineError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::UnknownOperation(e) => write!(f, "unknown operation: {e}"),
            Self::InvalidRepoName(e) => write!(f, "invalid repository name: {e}"),
            Self::UnexpectedArgCount(e) => e.fmt(f),
        }
    }
}

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
struct ArgCountError {
    provided: usize,
    expected: usize,
}

impl fmt::Display for ArgCountError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "got {} argument(s), expected {}",
            self.provided, self.expected
        )
    }
}

fn get_cmdline_args<const N: usize>() -> Result<[String; N], ArgCountError> {
    let args = std::env::args();
    if args.len() - 1 != N {
        return Err(ArgCountError {
            provided: args.len() - 1,
            expected: N,
        });
    }

    // Does not allocate.
    const EMPTY_STRING: String = String::new();
    let mut values = [EMPTY_STRING; N];

    // Skip the first element; we do not care about the program name.
    for (i, arg) in args.skip(1).enumerate() {
        values[i] = arg
    }
    Ok(values)
}

fn parse_cmdline() -> Result<(String, Operation), ParseCmdlineError> {
    let [repo_path, op_str] = get_cmdline_args::<2>()?;
    let op: Operation = op_str.parse()?;
    validate_repo_path(&repo_path)?;
    Ok((repo_path.to_string(), op))
}

fn repo_exists(name: &str) -> bool {
    match std::fs::metadata(name) {
        Ok(metadata) => metadata.is_dir(),
        _ => false,
    }
}

struct Config {
    href_base: String,
    key_path: String,
}

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
enum LoadConfigError {
    BaseUrlNotProvided,
    BaseUrlSlashSuffixMissing,
    KeyPathNotProvided,
}

impl fmt::Display for LoadConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BaseUrlNotProvided => write!(f, "base URL not provided"),
            Self::BaseUrlSlashSuffixMissing => write!(f, "base URL does not end with slash"),
            Self::KeyPathNotProvided => write!(f, "key path not provided"),
        }
    }
}

fn load_config() -> Result<Config, LoadConfigError> {
    let Ok(href_base) = std::env::var("GITOLFS3_HREF_BASE") else {
        return Err(LoadConfigError::BaseUrlNotProvided);
    };
    if !href_base.ends_with('/') {
        return Err(LoadConfigError::BaseUrlSlashSuffixMissing);
    }
    let Ok(key_path) = std::env::var("GITOLFS3_KEY_PATH") else {
        return Err(LoadConfigError::KeyPathNotProvided);
    };
    Ok(Config {
        href_base,
        key_path,
    })
}

fn main() -> ExitCode {
    let config = match load_config() {
        Ok(config) => config,
        Err(e) => {
            eprintln!("Failed to load config: {e}");
            return ExitCode::FAILURE;
        }
    };
    let key = match common::load_key(&config.key_path) {
        Ok(key) => key,
        Err(e) => {
            eprintln!("Failed to load key: {e}");
            return ExitCode::FAILURE;
        }
    };

    let (repo_name, operation) = match parse_cmdline() {
        Ok(args) => args,
        Err(e) => {
            eprintln!("Error: {e}\n");
            help();
            // Exit code 2 signifies bad usage of CLI.
            return ExitCode::from(2);
        }
    };

    if !repo_exists(&repo_name) {
        eprintln!("Error: repository does not exist");
        return ExitCode::FAILURE;
    }

    let expires_at = Utc::now() + Duration::from_secs(5 * 60);
    let Some(tag) = common::generate_tag(
        common::Claims {
            specific_claims: common::SpecificClaims::BatchApi(operation),
            repo_path: &repo_name,
            expires_at,
        },
        key,
    ) else {
        eprintln!("Failed to generate validation tag");
        return ExitCode::FAILURE;
    };

    println!(
        "{{\"header\":{{\"Authorization\":\"Gitolfs3-Hmac-Sha256 {tag} {}\"}},\
        \"expires_at\":\"{}\",\"href\":\"{}{}/info/lfs\"}}",
        expires_at.timestamp(),
        common::EscJsonFmt(&expires_at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
        common::EscJsonFmt(&config.href_base),
        common::EscJsonFmt(&repo_name),
    );

    ExitCode::SUCCESS
}