diff --git a/.github/workflows/gitleaks.yml b/.github/workflows/gitleaks.yml new file mode 100644 index 0000000..e3471a2 --- /dev/null +++ b/.github/workflows/gitleaks.yml @@ -0,0 +1,7 @@ +name: gitleaks +on: [push, workflow_dispatch] +jobs: + call-workflow: + uses: nhsbsa-data-analytics/.github/.github/workflows/org-gitleaks-check.yml@main + secrets: + GITLEAKS_LICENSE_PASSED: ${{ secrets.GITLEAKS_LICENSE }} diff --git a/.github/workflows/org-gitleaks-check.yml b/.github/workflows/org-gitleaks-check.yml index 5c26a35..3790fe6 100644 --- a/.github/workflows/org-gitleaks-check.yml +++ b/.github/workflows/org-gitleaks-check.yml @@ -36,4 +36,4 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE_PASSED }} # UPDATED: Point to the config file inside the folder from Step 2 - GITLEAKS_CONFIG: ".github-config/gitleaks.toml" + GITLEAKS_CONFIG: ".github-config/gitleaks/gitleaks.toml" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7ea8c4e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +scripts/outputs/ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..954974a --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,136 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, colour, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behaviour that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behaviour include: + +* The use of sexualised language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behaviour and will take appropriate and fair corrective action in +response to any behaviour that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations + +## Comments on this policy + +If you have suggestions on how this policy could be improved, please submit a pull request. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b20be0d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,56 @@ +# Contributing to .github + +.github is released under the [Apache 2 license](LICENCE.txt). If you would like to contribute +something, or simply want to hack on the code this document should help you get started. + +## Code of Conduct + +This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). +By participating, you are expected to uphold this code. + +Please report unacceptable behaviour to + +## Using GitHub Issues + +We use GitHub issues to track community reported bugs and enhancements. + +If you are reporting a bug, please help to speed up problem diagnosis by providing as +much information as possible. Ideally, that would include a small sample project that +reproduces the problem. + +## Reporting Security Vulnerabilities + +If you think you have found a security vulnerability in this codebase please follow +our guidance on [reporting security vulnerabilities](SECURITY.md). + +## Contributor privacy + +The NHSBSA take privacy seriously. All contributors may protect their identity when pushing code to our open sourced repositories by choosing an anonymous name and email. Contributors are responsible for configuring their local accounts to preserve their privacy. Commits containing contributor identifiable information may not be removed by rewriting history, once merged into `main`. + +## A quick guide on how to contribute + +1. Fork the project + +2. Clone the repo from your own space + +3. Configure [secrets detection](/SECRETS.md) + +5. Create a branch + +7. Add your functionality or bug fix. + +9. Push to your fork, and submit a merge request. + +## Cloning the git repository on Windows + +Some files in the git repository may exceed the Windows maximum file path (260 +characters), depending on where you clone the repository. If you get `Filename too long` +errors, set the `core.longPaths=true` git option: + +```bash +git clone -c core.longPaths=true {project URL} +``` + +## Comments on this policy + +If you have suggestions on how this policy could be improved, please submit a pull request. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..429be24 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2025] Crown Copyright (NHS Business Services Authority) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5c9719d --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# `.github` + +## About this repo + +This repo is a central place to store organisation wide files such as callable workflows and standard templates to be used in other repos. + +## Quick start + +### Building the application + +TODO + +### Running the application + +TODO + +## Contributions + +We operate a [code of conduct](CODE_OF_CONDUCT.md) for all contributors. + +See our [contributing guide](CONTRIBUTING.md) for guidance on how to contribute. + +## License + +Released under the [Apache 2 license](LICENCE.txt). diff --git a/SECRETS.md b/SECRETS.md new file mode 100644 index 0000000..3f0e895 --- /dev/null +++ b/SECRETS.md @@ -0,0 +1,59 @@ +# Configuring secrets detection + +The NHSBSA takes security seriously. We require: + +* contributors to install and configure secrets detection tooling before committing code +* maintainers risk assess potential for sensitive data leaks and configure detection tooling accordingly + +We use a dual-layer approach - check before code is pushed (`pre-commit` hook) and check when code arrives in GitHub (GitHub Action). + +## `pre-commit` + +Install the following: + +* [`gitleaks`](https://github.com/gitleaks/gitleaks/releases) is a secret detection tool to help prevent accidental commit of sensitive data in a local development environment Git repository. +* [`pre-commit`](https://pre-commit.com/) is a framework for managing and maintaining multi-language `pre-commit` hooks + +Although aimed at NHSBSA colleagues, the guide [Setting up a `pre-commit hook` to run `gitleaks`](docs/pre-commit-gitleaks.md) may help external contributors also. + +## Pre-commit hook + +A `pre-commit` hook for `gitleaks` is defined in [`.pre-commit-config.yaml`](repo_files/.pre-commit-config.yaml). This should be placed in the root directory of your repository. + +You can test the `pre-commit` hook is working by attempting to add and commit the [`gitleaks_tests` file](test/gitleaks_test). + +## Maintainers + +### New rules + +Any additional rules needed, identified from a sensitive data risk assessment for example, must be added to [`gitleaks.toml`](gitleaks/gitleaks.toml). This ensures that the new rules will be used in `pre-commit` checks by all repos. + +Whenever a new rule is added it should be tested by + +* adding sensitive data to one of your existing source files +* attempting to commit the file + +### Existing repos should scan history + +If you maintain a repo that has not had `gitleaks` set-up since it was created, you should scan the history. + +* Add `gitleaks.json` to the `.gitignore` file +* Open a command terminal in your repository directory and run command + +```bash +gitleaks detect -r gitleaks.json +``` + +If `gitleaks` detects any secrets, you can find details in the `gitleaks.json` file + +__If you detect a secret, you must immediately follow the remediation plan from your risk assessment and take steps to remove the secret from wherever they are used. Additionally, where possible, a new rule should be added to the `gitleaks` TOML file.__ + +## GitHub Action + +This repo contains a callable workflow to run `gitleaks` ([`org-gitleaks-check.yml`](.github/workflows/org-gitleaks-check.yml). All repos should have the workflow [`gitleaks.yml`](.github/workflows/gitleaks.yml), which calls the former. + +__IMPORTANT!__ Private repos require a `gitleaks` license. If you do not know how to find and set this, email for help. + +## Comments on this policy + +If you have suggestions on how this policy could be improved, please submit a pull request. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..6d31e2c --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Reporting Security Vulnerabilities + +The NHSBSA take security seriously. We appreciate your efforts to responsibly disclose your findings. + +If you think you have found a security vulnerability in this codebase please *DO NOT* +disclose it publicly until we've had a chance to fix it. We strongly encourage people to report +security vulnerabilities privately to our security team before disclosing them in a public forum. + +Please do not report security vulnerabilities as a defect. + +To report a security issue, please view our [security vulnerability disclosure policy](https://www.nhsbsa.nhs.uk/our-policies/policies-and-procedures/security-vulnerability-disclosure-policy). + +Report security bugs in third-party modules to the person or team maintaining the module. + +## Comments on this policy + +If you have suggestions on how this policy could be improved, please submit a pull request. diff --git a/docs/pre-commit-gitleaks.md b/docs/pre-commit-gitleaks.md new file mode 100644 index 0000000..4d867cb --- /dev/null +++ b/docs/pre-commit-gitleaks.md @@ -0,0 +1,213 @@ +# Setting up a `pre-commit` hook to run gitleaks + +Pre-commit hooks are scripts that execute before a code commit is finalised. Their purpose is to perform some action whenever a commit is made. This takes place before the actual commit is added, and depending on the hook result, may block the commit being made. Hooks can be set up to validate the code, check for formatting errors, ensure that tests pass, and perform various other checks you can define. Here we are just using it to run a `gitleaks` check on all files included in a commit. + +This guide is intended as a 'how-to' for aligning with the [guidance in the DDaT playbook](https://nhsbsa.github.io/nhsbsa-digital-playbook/development/coding-secrets-detection/). See also our [SECRETS page](../SECRETS.md). + +## `pre-commit` installation + +### AVD environment + +1. Create a new `conda` environment with the `pre-commit` package. Can name it whatever you like, I use `dev`. + +```bash +conda create -n dev -c conda-forge python=3.11 pre-commit +``` + +2. Activate the new environment. + +```bash +conda activate dev +``` + +3. Make `pre-commit` active. This tells `git` to run any defined `pre-commit` hooks on every commit. The hooks will be defined in a YAML config, called `pre-commit-config.yaml`, which is placed in each `git` repo - see "Congifuration" below. + +```bash +pre-commit install +``` + +4. Deactivate the `conda` environment. + +```bash +conda deactivate +``` + +You do not need to activate the environment for `pre-commit` to run in future. If you need to temporarily disable `pre-commit` (for example, to test the GitHub action for `gitleaks` is working correctly), you can run + +```bash +conda activate dev +pre-commit uninstall +``` + +then turn it back on with + +```bash +pre-commit install +``` + + +### Laptop + +Getting `pre-commit` installed on laptop is not as straightforward as on AVD. + +- MS Store python - The Microsoft Store version of python is what is installed on laptops. This is a poor version for development. The issue here seems to be the 256 character limit on file paths. The solution was to use `conda` to create a dedicated virtual environment with it's own python (just like done on the AVD). +- Installing `conda` - Above issue lead to the need to install `conda` on my laptop. I tried several methods, but the one that finally worked was to install [`miniforge`](https://github.com/conda-forge/miniforge?tab=readme-ov-file#miniforge3). Unfortunately, without further setup that I did not feel like trying (as may not be possible as non-admin) this means using the command line interface that comes with `miniforge`. This is worse to use than git bash, but at least it works for this use case, and is not needed other than starting/stopping `pre-commit`. + +Once you have got some form of `conda` running, follow the same steps as as for AVD. + + +## `gitleaks` installation + +1. Go to the [Gitleaks Releases Page](https://github.com/gitleaks/gitleaks/releases). +2. Download the latest windows archive (e.g., gitleaks_8.30.0_windows_x64.zip) - you may need to click the 'Show all asses' link. +3. Extract the zip. +4. Place it in a folder of your choice (e.g., `C:\ProgramData`). +5. Add the full path to your user `PATH` environment variable (e.g. `C:\ProgramData\gitleaks_8.30.0_windows_x64`). You can do this by searching for "env" in the Windows search and choosing the "Edit environment variables for your account" option, then finding and clicking "Edit" for the `PATH` variable. + +This will make `gitleaks` globally available for you. + + +## Configuration + +Each repo that you wish to have the `pre-commit` hook run for requires a file named `pre-commit-config.yaml`. This file can contain any number of hooks. For our use case of running `gitleaks` we use + +```yaml +repos: +- repo: local + hooks: + - id: gitleaks + name: Detect hardcoded secrets + description: Detect hardcoded secrets using Gitleaks with centralised NHSBSA config + entry: > + bash -c ' + mkdir -p .github-config && + curl -f -s https://raw.githubusercontent.com/nhsbsa-data-analytics/.github/main/gitleaks.toml -o .github-config/gitleaks.toml && + curl -f -s https://raw.githubusercontent.com/nhsbsa-data-analytics/.github/main/gitleaks-nhsbsa.toml -o .github-config/gitleaks-nhsbsa.toml && + gitleaks protect --config=".github-config/gitleaks.toml" --verbose --redact --staged; + EXIT_CODE=$?; + rm -rf .github-config; + exit $EXIT_CODE' + language: system + pass_filenames: false + +``` + +This can be copied from the `repo_files` folder of the organisation's [.github repo](https://github.com/nhsbsa-data-analytics/.github). + +This hook will initiate the following actions every time you run `git commit ...`: + +1. Create a temporary folder `.github-config`. +2. Download the `gitleaks` definition files (TOMLs) from our `.github` repo. +3. Run `gitleaks` using those definitions. +4. Save the output of the run. +5. Delete the temporary folder. +6. Finally, output the `gitleaks` messages. + +If the hook passes, it means no secrets were detected and the commit is allowed. If the hook fails, it means some secrets were discovered - `gitleaks` will output details of the leaks and also prevent the commit from actually happening. Resolve accordingly before trying to commit again. + + +## Examples of usage + +The nice thing about `pre-commit` hooks is that once setup, they run automatically. So you just use git as you usually would. + +### Fail scenario + +We try to add a file `gitleaks_tests` with content + +```r +NHS number: + +1234567890 + +DB creds: + +DB_DALP_USERNAME = "ABCDE" +DB_DALP_PASSWORD = "qwertyuiop" +``` + +Commit it (`-am` means add all files and use given message) + +```bash +git commit -am "Expect to fail" +``` + +The output is + +``` +Detect hardcoded secrets.................................................Failed +- hook id: gitleaks +- exit code: 1 + +○ + │╲ + │ ○ + ○ ░ + ░ gitleaks + +Finding: REDACTED +Secret: REDACTED +RuleID: nhs-number +Entropy: 3.321928 +Tags: [secret pii nhs] +File: gitleaks_tests +Line: 4 +Fingerprint: gitleaks_tests:nhs-number:4 + +Finding: DB_DALP_USERNAME = "REDACTED" +Secret: REDACTED +RuleID: database-connection-strings +Entropy: 2.321928 +Tags: [secret credential database] +File: gitleaks_tests +Line: 19 +Fingerprint: gitleaks_tests:database-connection-strings:19 + +Finding: DB_DALP_PASSWORD = "REDACTED" +Secret: REDACTED +RuleID: database-connection-strings +Entropy: 3.321928 +Tags: [secret credential database] +File: gitleaks_tests +Line: 20 +Fingerprint: gitleaks_tests:database-connection-strings:20 + +12:34PM INF 0 commits scanned. +12:34PM INF scanned ~88 bytes (88 bytes) in 121ms +12:34PM WRN leaks found: 3 +``` + +This gives you details of all potential leaks, so you can easily see why they were flagged and where they are in your code. For how to allow a false positive, see "Allowing fallse positives below". + +### Success scenario + +When no potential secrets are found the output will show the check passed, along with the normal output from making a commit, since the commit was allowed. + +``` +Detect hardcoded secrets.................................................Passed +[gitleaks-update 2ca6879] Expect to pass + 1 file changed, 3 insertions(+) +``` + +### Unstaged files + +Because the `gitleaks` command is set to run only on files to be committed, it will temporarily stash unstaged files, run the check and then pop the stash to restore the unstaged files. It looks like + +``` +[WARNING] Unstaged files detected. +[INFO] Stashing unstaged files to C:\Users\MAMCP\.cache\pre-commit\patch1764593063-8128. +Detect hardcoded secrets.............................(no files to check)Skipped +[INFO] Restored changes from C:\Users\MAMCP\.cache\pre-commit\patch1764593063-8128. +[gitleaks-update 277fab8] Empty commit +``` + +### Allowing false positives below + +It is possible that your code includes something that matches a `gitleaks` rule, but is not a leaked secret. These can be selectively allowed. You can use the `#gitleaks:allow` comment on the line. + +```r +fake_nhs_number = 1234567890 #gitleaks:allow +``` + +An [alternative, but experimental, method](https://github.com/gitleaks/gitleaks?tab=readme-ov-file#gitleaksignore) is to use a `.gitleaksignore` file and add the Fingerprint from the `gitleaks` detection output (e.g. `gitleaks_tests:nhs-number:4`, given as the Fingerprint for the first secret detected in the fail scenario above). + +The allow comment is the better method if you have one or a few isolated cases. But if you had something like a lot of fake data for tests, then the ignore file may be better. diff --git a/gitleaks-nhsbsa.toml b/gitleaks/gitleaks-nhsbsa.toml similarity index 100% rename from gitleaks-nhsbsa.toml rename to gitleaks/gitleaks-nhsbsa.toml diff --git a/gitleaks.toml b/gitleaks/gitleaks.toml similarity index 97% rename from gitleaks.toml rename to gitleaks/gitleaks.toml index 1188e2f..b216956 100644 --- a/gitleaks.toml +++ b/gitleaks/gitleaks.toml @@ -4,7 +4,7 @@ title = "Additional gitleaks config" [extend] -path = ".github-config/gitleaks-nhsbsa.toml" +path = ".github-config/gitleaks/gitleaks-nhsbsa.toml" # ================================================================= # Rule for detecting National Health Service (NHS) numbers diff --git a/repo_files/.github/workflows/gitleaks.yml b/repo_files/.github/workflows/gitleaks.yml new file mode 100644 index 0000000..e3471a2 --- /dev/null +++ b/repo_files/.github/workflows/gitleaks.yml @@ -0,0 +1,7 @@ +name: gitleaks +on: [push, workflow_dispatch] +jobs: + call-workflow: + uses: nhsbsa-data-analytics/.github/.github/workflows/org-gitleaks-check.yml@main + secrets: + GITLEAKS_LICENSE_PASSED: ${{ secrets.GITLEAKS_LICENSE }} diff --git a/repo_files/.pre-commit-config.yaml b/repo_files/.pre-commit-config.yaml new file mode 100644 index 0000000..4f37f34 --- /dev/null +++ b/repo_files/.pre-commit-config.yaml @@ -0,0 +1,17 @@ +repos: +- repo: local + hooks: + - id: gitleaks + name: Detect hardcoded secrets + description: Detect hardcoded secrets using Gitleaks with centralised NHSBSA config + entry: > + bash -c ' + mkdir -p .github-config && + curl -f -s https://raw.githubusercontent.com/nhsbsa-data-analytics/.github/main/gitleaks/gitleaks.toml -o .github-config/gitleaks/gitleaks.toml && + curl -f -s https://raw.githubusercontent.com/nhsbsa-data-analytics/.github/main/gitleaks/gitleaks-nhsbsa.toml -o .github-config/gitleaks/gitleaks-nhsbsa.toml && + gitleaks protect --config=".github-config/gitleaks/gitleaks.toml" --verbose --redact --staged; + EXIT_CODE=$?; + rm -rf .github-config; + exit $EXIT_CODE' + language: system + pass_filenames: false diff --git a/scripts/check_gitleaks_secrets.sh b/scripts/check_gitleaks_secrets.sh new file mode 100644 index 0000000..e477b8c --- /dev/null +++ b/scripts/check_gitleaks_secrets.sh @@ -0,0 +1,62 @@ +#!/bin/bash + +# --- Configuration --- +ORG_NAME="nhsbsa-data-analytics" +SECRET_NAME="GITLEAKS_LICENSE" +OUTPUT_FILE="outputs/repos_gitleaks_status.csv" + +# --- Script --- + +echo "Fetching repository list for organization: $ORG_NAME..." + +# Initialize CSV file with headers +echo "repo_name,visibility,has_gitleaks_workflow,has_gitleaks_secret" > "$OUTPUT_FILE" + +# Get all repositories with name and visibility. +# We format the output as "name|visibility" to easily split it later. +# We limit to 4000 to catch everything. +REPO_DATA=$(gh repo list "$ORG_NAME" --limit 4000 --source --json name,visibility --jq '.[] | "\(.name)|\(.visibility)"') + +if [ -z "$REPO_DATA" ]; then + echo "No repositories found or error fetching list." + exit 1 +fi + +# Count lines for progress tracking +TOTAL_REPOS=$(echo "$REPO_DATA" | wc -l) +CURRENT_COUNT=0 + +echo "Scanning $TOTAL_REPOS repositories..." + +# Loop through each line of the repository data +while IFS="|" read -r REPO_NAME VISIBILITY; do + ((CURRENT_COUNT++)) + FULL_REPO="$ORG_NAME/$REPO_NAME" + + # Progress indicator + # \r = Move to start of line + # \033[K = Clear to end of line (Removes the "ghost" text) + printf "\r\033[K[%d/%d] Checking %s..." "$CURRENT_COUNT" "$TOTAL_REPOS" "$REPO_NAME" + + # 1. Check for files containing "gitleaks" in .github/workflows + if gh api "repos/$FULL_REPO/contents/.github/workflows" --jq '.[].name' 2>/dev/null | grep -iq "gitleaks"; then + HAS_GITLEAKS_WORKFLOW="TRUE" + else + HAS_GITLEAKS_WORKFLOW="FALSE" + fi + + # 2. Check if the specific Secret exists + if gh secret list --repo "$FULL_REPO" --json name --jq '.[].name' 2>/dev/null | grep -q "^${SECRET_NAME}$"; then + HAS_SECRET="TRUE" + else + HAS_SECRET="FALSE" + fi + + # Append to CSV + echo "$REPO_NAME,$VISIBILITY,$HAS_GITLEAKS_WORKFLOW,$HAS_SECRET" >> "$OUTPUT_FILE" + +done <<< "$REPO_DATA" + +echo -e "\n------------------------------------------------" +echo "Scan complete." +echo "Results saved to: $OUTPUT_FILE" diff --git a/scripts/set_gitleaks_license.sh b/scripts/set_gitleaks_license.sh new file mode 100644 index 0000000..d157b36 --- /dev/null +++ b/scripts/set_gitleaks_license.sh @@ -0,0 +1,79 @@ +#!/bin/bash + +# --- Configuration --- +ORG_NAME="nhsbsa-data-analytics" +SECRET_NAME="GITLEAKS_LICENSE" + +# --- Safety Check --- +if [ -z "$GITLEAKS_LICENSE_VALUE" ]; then + echo "Error: GITLEAKS_LICENSE_VALUE environment variable is not set." + echo "Usage: GITLEAKS_LICENSE_VALUE=\"your-key\" ./set_gitleaks_secrets.sh" + exit 1 +fi + +echo "Fetching repository list for organization: $ORG_NAME..." + +# Get all repositories with name and visibility. +# --source ensures we don't try to set secrets on forks. +# --limit 4000 ensures we get everything. +REPO_DATA=$(gh repo list "$ORG_NAME" --limit 4000 --source --json name,visibility --jq '.[] | "\(.name)|\(.visibility)"') + +if [ -z "$REPO_DATA" ]; then + echo "No repositories found or error fetching list." + exit 1 +fi + +# Count lines for progress tracking +TOTAL_REPOS=$(echo "$REPO_DATA" | wc -l) +CURRENT_COUNT=0 +UPDATED_COUNT=0 +SKIPPED_PUBLIC_COUNT=0 +SKIPPED_EXISTING_COUNT=0 + +echo "Processing $TOTAL_REPOS repositories..." + +# Loop through each line of the repository data +while IFS="|" read -r REPO_NAME VISIBILITY; do + ((CURRENT_COUNT++)) + FULL_REPO="$ORG_NAME/$REPO_NAME" + + # 1. VISIBILITY CHECK: Only proceed if the repo is PRIVATE + # Note: 'gh' returns visibility in lowercase (public/private/internal) + if [[ "$VISIBILITY" != "private" ]]; then + ((SKIPPED_PUBLIC_COUNT++)) + # Clear line and print skip message transiently + printf "\r\033[K[%d/%d] Skipping %s (%s)..." "$CURRENT_COUNT" "$TOTAL_REPOS" "$REPO_NAME" "$VISIBILITY" + continue + fi + + # 2. EXISTENCE CHECK: Check if secret already exists + # We use grep -q for a silent check + if gh secret list --repo "$FULL_REPO" --json name --jq '.[].name' 2>/dev/null | grep -q "^${SECRET_NAME}$"; then + ((SKIPPED_EXISTING_COUNT++)) + printf "\r\033[K[%d/%d] Skipping %s (Secret already exists)..." "$CURRENT_COUNT" "$TOTAL_REPOS" "$REPO_NAME" + else + # 3. ACTION: Set the secret + printf "\r\033[K[%d/%d] Setting secret for %s..." "$CURRENT_COUNT" "$TOTAL_REPOS" "$REPO_NAME" + + # We pipe the env var into gh secret set + echo "$GITLEAKS_LICENSE_VALUE" | gh secret set "$SECRET_NAME" --repo "$FULL_REPO" + + if [ $? -eq 0 ]; then + ((UPDATED_COUNT++)) + echo "" # New line to confirm success permanently on screen + echo " -> Successfully set secret for $REPO_NAME" + else + echo "" + echo " -> Error: Failed to set secret for $REPO_NAME" + fi + fi + +done <<< "$REPO_DATA" + +echo -e "\n------------------------------------------------" +echo "Process complete." +echo "Total Repos Scanned: $TOTAL_REPOS" +echo "Secrets Set: $UPDATED_COUNT" +echo "Skipped (Public): $SKIPPED_PUBLIC_COUNT" +echo "Skipped (Exists): $SKIPPED_EXISTING_COUNT" + diff --git a/test/gitleaks_tests b/test/gitleaks_tests new file mode 100644 index 0000000..0697428 --- /dev/null +++ b/test/gitleaks_tests @@ -0,0 +1,14 @@ +NHS number: + +(10 digits) +1234567890 +( > 10 digits) +12345678901234 +(3-3-4 dashes) +123-456-7890 +(3-3-4 spaces) +123 456 7890 +(3-3-4 multi spaced) +123 456 7890 +(3-3-4 spaced dashes) +123 - 456 - 7890