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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use derive_builder::Builder;
use git_checks_core::impl_prelude::*;

use crate::binary_format;

/// Checks whether a file's executable permissions matches its contents.
///
/// Files which look executable but are not marked as such or vice versa are rejected.
#[derive(Builder, Debug, Default, Clone)]
#[builder(field(private))]
pub struct CheckExecutablePermissions {
    #[builder(private)]
    #[builder(setter(name = "_extensions"))]
    #[builder(default)]
    extensions: Vec<String>,
}

impl CheckExecutablePermissionsBuilder {
    /// Extensions considered to indicate an executable file.
    ///
    /// Really only intended for Windows where executable permissions do not exist.
    ///
    /// Configuration: Optional
    /// Default: `Vec::new()`
    pub fn extensions<I>(&mut self, extensions: I) -> &mut Self
    where
        I: IntoIterator,
        I::Item: Into<String>,
    {
        self.extensions = Some(extensions.into_iter().map(Into::into).collect());
        self
    }
}

impl CheckExecutablePermissions {
    /// Create a new builder.
    pub fn builder() -> CheckExecutablePermissionsBuilder {
        CheckExecutablePermissionsBuilder::default()
    }
}

impl ContentCheck for CheckExecutablePermissions {
    fn name(&self) -> &str {
        "check-executable-permissions"
    }

    fn check(
        &self,
        ctx: &CheckGitContext,
        content: &dyn Content,
    ) -> Result<CheckResult, Box<dyn Error>> {
        let mut result = CheckResult::new();

        for diff in content.diffs() {
            match diff.status {
                StatusChange::Added | StatusChange::Modified(_) => (),
                _ => continue,
            }

            // Ignore files which haven't changed their modes.
            if diff.old_mode == diff.new_mode {
                continue;
            }

            let is_executable = match diff.new_mode.as_str() {
                "100755" => true,
                "100644" => false,
                _ => continue,
            };

            // LFS pointer files are defined as per its spec to have the same permission bit as the
            // content it points to. Since this check can only access the pointer content, it is
            // likely to be wrong here. Just ignore files specified to use the `lfs` filter.
            let filter_attr = ctx.check_attr("filter", diff.name.as_path())?;
            if let AttributeState::Value(filter_name) = filter_attr {
                if filter_name == "lfs" {
                    continue;
                }
            }

            let executable_ext = self
                .extensions
                .iter()
                .any(|ext| diff.name.as_str().ends_with(ext));
            let looks_executable = if executable_ext {
                true
            } else {
                let cat_file = ctx
                    .git()
                    .arg("cat-file")
                    .arg("blob")
                    .arg(diff.new_blob.as_str())
                    .output()
                    .map_err(|err| GitError::subcommand("cat-file", err))?;
                let content = &cat_file.stdout;
                let shebang = content.starts_with(b"#!/") || content.starts_with(b"#! /");
                if shebang {
                    true
                } else {
                    binary_format::detect_binary_format(content)
                        .map_or(false, |fmt| fmt.is_executable())
                }
            };

            let err = match (is_executable, looks_executable) {
                (true, false) => {
                    Some("with executable permissions, but the file does not look executable")
                },
                (false, true) => {
                    Some("without executable permissions, but the file looks executable")
                },
                _ => None,
            };

            if let Some(msg) = err {
                result.add_error(format!(
                    "{}adds `{}` {}.",
                    commit_prefix(content),
                    diff.name,
                    msg,
                ));
            }
        }

        Ok(result)
    }
}

#[cfg(feature = "config")]
pub(crate) mod config {
    use git_checks_config::{register_checks, CommitCheckConfig, IntoCheck, TopicCheckConfig};
    use serde::Deserialize;
    #[cfg(test)]
    use serde_json::json;

    use crate::CheckExecutablePermissions;

    /// Configuration for the `CheckExecutablePermissions` check.
    ///
    /// The `extensions` key is a list of strings, defaulting to an empty list. These extensions
    /// are used to detect executable files on Windows since other platforms can usually be
    /// detected by the file contents.
    ///
    /// This check is registered as a commit check with the name `"check_executable_permissions"
    /// and as a topic check with the name `"check_executable_permissions/topic"`.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///     "extensions": [
    ///         "bat",
    ///         "exe",
    ///         "cmd"
    ///     ]
    /// }
    /// ```
    #[derive(Deserialize, Debug)]
    pub struct CheckExecutablePermissionsConfig {
        #[serde(default)]
        extensions: Option<Vec<String>>,
    }

    impl IntoCheck for CheckExecutablePermissionsConfig {
        type Check = CheckExecutablePermissions;

        fn into_check(self) -> Self::Check {
            let mut builder = CheckExecutablePermissions::builder();

            if let Some(extensions) = self.extensions {
                builder.extensions(extensions);
            }

            builder
                .build()
                .expect("configuration mismatch for `CheckExecutablePermissions`")
        }
    }

    register_checks! {
        CheckExecutablePermissionsConfig {
            "check_executable_permissions" => CommitCheckConfig,
            "check_executable_permissions/topic" => TopicCheckConfig,
        },
    }

    #[test]
    fn test_check_executable_permissions_config_empty() {
        let json = json!({});
        let check: CheckExecutablePermissionsConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.extensions, None);

        let check = check.into_check();

        itertools::assert_equal(&check.extensions, &[] as &[&str]);
    }

    #[test]
    fn test_check_executable_permissions_config_all_fields() {
        let exp_ext: String = "md".into();
        let json = json!({
            "extensions": [exp_ext],
        });
        let check: CheckExecutablePermissionsConfig = serde_json::from_value(json).unwrap();

        itertools::assert_equal(&check.extensions, &Some([exp_ext.clone()]));

        let check = check.into_check();

        itertools::assert_equal(&check.extensions, &[exp_ext]);
    }
}

#[cfg(test)]
mod tests {
    use git_checks_core::{Check, TopicCheck};

    use crate::test::*;
    use crate::CheckExecutablePermissions;

    const BAD_TOPIC: &str = "6ad8d4932466efc57ecccd3c80def3737b5d7e9a";
    const BINARY_TOPIC: &str = "f81d125d44faeb76d8d06de1394f35ab03d4ebf8";
    const DELETE_TOPIC: &str = "8e007a6e84b7b2ecc2f613a653997c436c6671f4";
    const DELETE_BINARY_TOPIC: &str = "02ba9984453024e1ca70fb1ab4c51ebd41801c47";
    const FIX_TOPIC: &str = "bea46a67f75380f1c17c25c7f89ffa9f47b27c06";
    const BINARY_FIX_TOPIC: &str = "3ddce524eb8aff0e6e0b7b6475d64347d0d6a57f";
    const LFS_TOPIC: &str = "58b4868402bf3f2e6160af345052c812f4cbe36f";
    const SYMLINK_COMMIT: &str = "00ffdf352196c16a453970de022a8b4343610ccf";

    #[test]
    fn test_check_executable_permissions_builder_default() {
        assert!(CheckExecutablePermissions::builder().build().is_ok());
    }

    #[test]
    fn test_check_executable_permissions_name_commit() {
        let check = CheckExecutablePermissions::default();
        assert_eq!(Check::name(&check), "check-executable-permissions");
    }

    #[test]
    fn test_check_executable_permissions_name_topic() {
        let check = CheckExecutablePermissions::default();
        assert_eq!(TopicCheck::name(&check), "check-executable-permissions");
    }

    fn check_executable_permissions_check(ext: &str) -> CheckExecutablePermissions {
        CheckExecutablePermissions::builder()
            .extensions([ext].iter().cloned())
            .build()
            .unwrap()
    }

    #[test]
    fn test_check_executable_permissions() {
        let check = check_executable_permissions_check(".exe");
        let result = run_check("test_check_executable_permissions", BAD_TOPIC, check);
        test_result_errors(
            result,
            &[
                "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `is-exec` with executable \
                 permissions, but the file does not look executable.",
                "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `not-exec-shebang` without \
                 executable permissions, but the file looks executable.",
                "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `not-exec.exe` without \
                 executable permissions, but the file looks executable.",
            ],
        );
    }

    #[test]
    fn test_check_executable_permissions_binary() {
        let check = check_executable_permissions_check(".exe");
        let result = run_check(
            "test_check_executable_permissions_binary",
            BINARY_TOPIC,
            check,
        );
        test_result_errors(result, &[
            "commit f5fd493ca51556d6cd0c42dfc8003925d77441f3 adds `elf-header` without executable \
             permissions, but the file looks executable.",
            "commit f5fd493ca51556d6cd0c42dfc8003925d77441f3 adds `macho-cigam-header` without \
             executable permissions, but the file looks executable.",
            "commit f5fd493ca51556d6cd0c42dfc8003925d77441f3 adds `macho-fat-cigam-header` \
             without executable permissions, but the file looks executable.",
            "commit f5fd493ca51556d6cd0c42dfc8003925d77441f3 adds `macho-fat-magic-header` \
             without executable permissions, but the file looks executable.",
            "commit f5fd493ca51556d6cd0c42dfc8003925d77441f3 adds `macho-magic-header` without \
             executable permissions, but the file looks executable.",
            "commit f3ea55a336feec4bc6c970695c5662fadea67054 adds `ar-header` with executable \
             permissions, but the file does not look executable.",
            "commit f81d125d44faeb76d8d06de1394f35ab03d4ebf8 adds `pe-le-header` without \
             executable permissions, but the file looks executable.",
        ]);
    }

    #[test]
    fn test_check_executable_permissions_delete_files() {
        let check = check_executable_permissions_check(".exe");
        let conf = make_check_conf(&check);

        let result = test_check_base(
            "test_check_executable_permissions_delete_files",
            DELETE_TOPIC,
            BAD_TOPIC,
            &conf,
        );
        test_result_ok(result);
    }

    #[test]
    fn test_check_executable_permissions_binary_delete_files() {
        let check = check_executable_permissions_check(".exe");
        let conf = make_check_conf(&check);

        let result = test_check_base(
            "test_check_executable_permissions_binary_delete_files",
            DELETE_BINARY_TOPIC,
            BINARY_TOPIC,
            &conf,
        );
        test_result_ok(result);
    }

    #[test]
    fn test_check_executable_permissions_topic() {
        let check = check_executable_permissions_check(".exe");
        let result = run_topic_check("test_check_executable_permissions_topic", BAD_TOPIC, check);
        test_result_errors(
            result,
            &[
                "adds `is-exec` with executable permissions, but the file does not look \
                 executable.",
                "adds `not-exec-shebang` without executable permissions, but the file looks \
                 executable.",
                "adds `not-exec.exe` without executable permissions, but the file looks \
                 executable.",
            ],
        );
    }

    #[test]
    fn test_check_executable_permissions_topic_delete_files() {
        let check = check_executable_permissions_check(".exe");
        run_topic_check_ok(
            "test_check_executable_permissions_topic_delete_files",
            DELETE_TOPIC,
            check,
        );
    }

    #[test]
    fn test_check_executable_permissions_topic_binary_delete_files() {
        let check = check_executable_permissions_check(".exe");
        run_topic_check_ok(
            "test_check_executable_permissions_topic_binary_delete_files",
            DELETE_BINARY_TOPIC,
            check,
        );
    }

    #[test]
    fn test_check_executable_permissions_topic_fixed() {
        let check = check_executable_permissions_check(".exe");
        run_topic_check_ok(
            "test_check_executable_permissions_topic_fixed",
            FIX_TOPIC,
            check,
        );
    }

    #[test]
    fn test_check_executable_permissions_topic_binary_fixed() {
        let check = check_executable_permissions_check(".exe");
        run_topic_check_ok(
            "test_check_executable_permissions_topic_binary_fixed",
            BINARY_FIX_TOPIC,
            check,
        );
    }

    #[test]
    fn test_check_executable_permissions_lfs() {
        let check = check_executable_permissions_check(".lfs");
        let conf = make_check_conf(&check);
        let result = test_check_base(
            "test_check_executable_permissions_lfs",
            LFS_TOPIC,
            BAD_TOPIC,
            &conf,
        );
        test_result_ok(result);
    }

    #[test]
    fn test_check_executable_permissions_ignore_symlinks() {
        let check = CheckExecutablePermissions::default();
        run_check_ok(
            "test_check_executable_permissions_ignore_symlinks",
            SYMLINK_COMMIT,
            check,
        );
    }

    #[test]
    fn test_check_executable_permissions_ignore_symlinks_topic() {
        let check = CheckExecutablePermissions::default();
        run_topic_check_ok(
            "test_check_executable_permissions_ignore_symlinks_topic",
            SYMLINK_COMMIT,
            check,
        );
    }
}