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
// Copyright 2016 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 impl_prelude::*;

#[derive(Debug)]
/// 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.
pub struct CheckExecutablePermissions {
    /// Extensions considered to indicate an executable file.
    ///
    /// Really only intended for Windows where executable permissions do not exist.
    extensions: Vec<String>,
}

impl CheckExecutablePermissions {
    /// Create a new check which checks for executable permissions.
    ///
    /// Files which end in the given extension are assumed to be executable.
    pub fn new<E: ToString>(extensions: &[E]) -> Self {
        CheckExecutablePermissions {
            extensions: extensions.iter().map(ToString::to_string).collect(),
        }
    }
}

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

    fn check(&self, ctx: &CheckGitContext, commit: &Commit) -> Result<CheckResult> {
        let mut result = CheckResult::new();

        for diff in &commit.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,
            };

            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()
                    .chain_err(|| "failed to contruct cat-file command")?;
                let content = String::from_utf8_lossy(&cat_file.stdout);
                content.starts_with("#!/") || content.starts_with("#! /")
            };

            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!("commit {} adds `{}` {}.", commit.sha1, diff.name, msg));
            }
        }

        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use checks::CheckExecutablePermissions;
    use checks::test::*;

    static BAD_TOPIC: &'static str = "6ad8d4932466efc57ecccd3c80def3737b5d7e9a";

    #[test]
    fn test_check_executable_permissions() {
        let check = CheckExecutablePermissions::new(&[".exe"]);
        let mut conf = GitCheckConfiguration::new();

        conf.add_check(&check);

        let result = test_check("test_check_executable_permissions", BAD_TOPIC, &conf);

        assert_eq!(result.warnings().len(), 0);
        assert_eq!(result.alerts().len(), 0);
        assert_eq!(result.errors().len(), 3);
        assert_eq!(result.errors()[0],
                   "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `is-exec` with \
                    executable permissions, but the file does not look executable.");
        assert_eq!(result.errors()[1],
                   "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `not-exec-shebang` \
                    without executable permissions, but the file looks executable.");
        assert_eq!(result.errors()[2],
                   "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `not-exec.exe` without \
                    executable permissions, but the file looks executable.");
        assert_eq!(result.temporary(), false);
        assert_eq!(result.allowed(), false);
        assert_eq!(result.pass(), false);
    }
}