├── .eslintignore ├── .eslintrc.json ├── .github └── workflows │ ├── ci.yml │ └── release.yml ├── .gitignore ├── .prettierignore ├── .releaserc.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── __tests__ ├── config.test.ts ├── github.test.ts ├── main.test.ts ├── secrets.test.ts └── utils.test.ts ├── action.yml ├── dist ├── .gitkeep └── index.js ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── config.ts ├── github.ts ├── index.ts ├── main.ts ├── secrets.ts └── utils.ts └── tsconfig.json /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | lib/ 3 | node_modules/ -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": ["jest", "@typescript-eslint"], 3 | "extends": ["plugin:github/es6"], 4 | "parser": "@typescript-eslint/parser", 5 | "parserOptions": { 6 | "ecmaVersion": 9, 7 | "sourceType": "module", 8 | "project": "./tsconfig.json" 9 | }, 10 | "rules": { 11 | "eslint-comments/no-use": "off", 12 | "import/no-namespace": "off", 13 | "no-unused-vars": "off", 14 | "@typescript-eslint/no-unused-vars": "error", 15 | "@typescript-eslint/explicit-member-accessibility": ["error", {"accessibility": "no-public"}], 16 | "@typescript-eslint/no-require-imports": "error", 17 | "@typescript-eslint/array-type": "error", 18 | "@typescript-eslint/await-thenable": "error", 19 | "@typescript-eslint/ban-ts-ignore": "warn", 20 | "camelcase": "off", 21 | "@typescript-eslint/camelcase": "warn", 22 | "@typescript-eslint/class-name-casing": "error", 23 | "@typescript-eslint/explicit-function-return-type": ["error", {"allowExpressions": true}], 24 | "@typescript-eslint/func-call-spacing": ["error", "never"], 25 | "@typescript-eslint/generic-type-naming": ["error", "^[A-Z][A-Za-z]*$"], 26 | "@typescript-eslint/no-array-constructor": "error", 27 | "@typescript-eslint/no-empty-interface": "error", 28 | "@typescript-eslint/no-explicit-any": "warn", 29 | "@typescript-eslint/no-extraneous-class": "error", 30 | "@typescript-eslint/no-for-in-array": "error", 31 | "@typescript-eslint/no-inferrable-types": "error", 32 | "@typescript-eslint/no-misused-new": "error", 33 | "@typescript-eslint/no-namespace": "error", 34 | "@typescript-eslint/no-non-null-assertion": "warn", 35 | "@typescript-eslint/no-object-literal-type-assertion": "error", 36 | "@typescript-eslint/no-unnecessary-qualifier": "error", 37 | "@typescript-eslint/no-unnecessary-type-assertion": "error", 38 | "@typescript-eslint/no-useless-constructor": "error", 39 | "@typescript-eslint/no-var-requires": "error", 40 | "@typescript-eslint/prefer-for-of": "warn", 41 | "@typescript-eslint/prefer-function-type": "warn", 42 | "@typescript-eslint/prefer-includes": "error", 43 | "@typescript-eslint/prefer-interface": "error", 44 | "@typescript-eslint/prefer-string-starts-ends-with": "error", 45 | "@typescript-eslint/promise-function-async": "warn", 46 | "@typescript-eslint/require-array-sort-compare": "error", 47 | "@typescript-eslint/restrict-plus-operands": "error", 48 | "@typescript-eslint/type-annotation-spacing": "error", 49 | "@typescript-eslint/unbound-method": "error" 50 | }, 51 | "env": { 52 | "node": true, 53 | "es6": true, 54 | "jest/globals": true 55 | } 56 | } -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: "Build" 2 | on: 3 | [push, pull_request] 4 | jobs: 5 | build: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | - run: | 10 | npm i 11 | npm run all 12 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: "Release" 2 | on: 3 | push: 4 | branches: 5 | - master 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | with: 12 | ref: 'master' 13 | - name: Keep dist up-to-date 14 | run: | 15 | npm i 16 | npm run build 17 | npm run pack 18 | git config --local user.email "action@github.com" 19 | git config --local user.name "GitHub Action" 20 | git add dist/index.js 21 | git commit -m "chore: publish dist" || echo "nothing to commit" 22 | git push origin master 23 | - uses: actions/checkout@v2 24 | with: 25 | ref: master 26 | - name: Test Action 27 | uses: ./ 28 | with: 29 | SECRETS: | 30 | ^FOO$ 31 | ^GITHUB_.* 32 | REPOSITORIES: | 33 | ^jpoehnelt/nodelete$ 34 | DRY_RUN: true 35 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN_NO_SCOPES }} 36 | env: 37 | FOO: ${{github.run_id}} 38 | FOOBAR: BAZ 39 | - name: Checkout 40 | uses: actions/checkout@v2 41 | with: 42 | ref: master 43 | - name: Semantic Release 44 | run: | 45 | npm ci 46 | npx semantic-release 47 | env: 48 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependency directory 2 | node_modules 3 | lib/ 4 | 5 | # Rest pulled from https://github.com/github/gitignore/blob/master/Node.gitignore 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # Diagnostic reports (https://nodejs.org/api/report.html) 15 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 16 | 17 | # Runtime data 18 | pids 19 | *.pid 20 | *.seed 21 | *.pid.lock 22 | 23 | # Directory for instrumented libs generated by jscoverage/JSCover 24 | lib-cov 25 | 26 | # Coverage directory used by tools like istanbul 27 | coverage 28 | *.lcov 29 | 30 | # nyc test coverage 31 | .nyc_output 32 | 33 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 34 | .grunt 35 | 36 | # Bower dependency directory (https://bower.io/) 37 | bower_components 38 | 39 | # node-waf configuration 40 | .lock-wscript 41 | 42 | # Compiled binary addons (https://nodejs.org/api/addons.html) 43 | build/Release 44 | 45 | # Dependency directories 46 | jspm_packages/ 47 | 48 | # TypeScript v1 declaration files 49 | typings/ 50 | 51 | # TypeScript cache 52 | *.tsbuildinfo 53 | 54 | # Optional npm cache directory 55 | .npm 56 | 57 | # Optional eslint cache 58 | .eslintcache 59 | 60 | # Optional REPL history 61 | .node_repl_history 62 | 63 | # Output of 'npm pack' 64 | *.tgz 65 | 66 | # Yarn Integrity file 67 | .yarn-integrity 68 | 69 | # dotenv environment variables file 70 | .env 71 | .env.test 72 | 73 | # parcel-bundler cache (https://parceljs.org/) 74 | .cache 75 | 76 | # next.js build output 77 | .next 78 | 79 | # nuxt.js build output 80 | .nuxt 81 | 82 | # vuepress build output 83 | .vuepress/dist 84 | 85 | # Serverless directories 86 | .serverless/ 87 | 88 | # FuseBox cache 89 | .fusebox/ 90 | 91 | # DynamoDB Local files 92 | .dynamodb/ 93 | 94 | # OS metadata 95 | .DS_Store 96 | Thumbs.db 97 | 98 | # Ignore built ts files 99 | __tests__/runner/* 100 | lib/**/* -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | lib/ 3 | node_modules/ -------------------------------------------------------------------------------- /.releaserc.yml: -------------------------------------------------------------------------------- 1 | branches: 2 | - master 3 | plugins: 4 | - "@semantic-release/commit-analyzer" 5 | - "@semantic-release/release-notes-generator" 6 | - "@semantic-release/git" 7 | - "@semantic-release/github" -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | **Table of contents** 4 | 5 | * [Contributor License Agreements](#contributor-license-agreements) 6 | * [Contributing a patch](#contributing-a-patch) 7 | * [Running the tests](#running-the-tests) 8 | * [Releasing the library](#releasing-the-library) 9 | 10 | ## Contributor License Agreements 11 | 12 | We'd love to accept your sample apps and patches! Before we can take them, we 13 | have to jump a couple of legal hurdles. 14 | 15 | Please fill out either the individual or corporate Contributor License Agreement 16 | (CLA). 17 | 18 | * If you are an individual writing original source code and you're sure you 19 | own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). 20 | * If you work for a company that wants to allow you to contribute your work, 21 | then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). 22 | 23 | Follow either of the two links above to access the appropriate CLA and 24 | instructions for how to sign and return it. Once we receive it, we'll be able to 25 | accept your pull requests. 26 | 27 | ## Contributing A Patch 28 | 29 | 1. Submit an issue describing your proposed change to the repo in question. 30 | 1. The repo owner will respond to your issue promptly. 31 | 1. If your proposed change is accepted, and you haven't already done so, sign a 32 | Contributor License Agreement (see details above). 33 | 1. Fork the desired repo, develop and test your code changes. 34 | 1. Ensure that your code adheres to the existing style in the code to which 35 | you are contributing. 36 | 1. Ensure that your code has an appropriate set of tests which all pass. 37 | 1. Title your pull request following [Conventional Commits](https://www.conventionalcommits.org/) styling. 38 | 1. Submit a pull request. 39 | 40 | ## Running the tests 41 | 42 | 1. [Prepare your environment for Node.js setup][setup]. 43 | 44 | 1. Install dependencies: 45 | 46 | npm install 47 | 48 | 1. Run the tests: 49 | 50 | # Run unit tests. 51 | npm test 52 | 53 | # Run lint check. 54 | npm run lint 55 | 56 | 1. Lint (and maybe fix) any changes: 57 | 58 | npm run format 59 | npm run lint-fix 60 | 61 | [setup]: https://cloud.google.com/nodejs/docs/setup -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Secrets Sync Action 2 | 3 | ![Build](https://github.com/jpoehnelt/secrets-sync-action/workflows/Build/badge.svg) 4 | ![Release](https://github.com/jpoehnelt/secrets-sync-action/workflows/Release/badge.svg) 5 | [![codecov](https://codecov.io/gh/jpoehnelt/secrets-sync-action/branch/master/graph/badge.svg)](https://codecov.io/gh/jpoehnelt/secrets-sync-action) 6 | ![GitHub contributors](https://img.shields.io/github/contributors/jpoehnelt/secrets-sync-action?color=green) 7 | [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) 8 | 9 | A Github Action that can sync secrets from one repository to many others. This action allows a maintainer to define and rotate secrets in a single repository and have them synced to all other repositories in the Github organization or beyond. Secrets do not need to be sensitive and could also be specific build settings that would apply to all repositories and become available to all actions. Regex is used to select the secrets and the repositories. Exclude is currently not supported and it is recommended to use a bot user if possible. 10 | 11 | ## Inputs 12 | 13 | ### `github_token` 14 | 15 | **Required**, Token to use to get repos and write secrets. `${{secrets.GITHUB_TOKEN}}` will **not** work as it does not have the necessary scope for other repositories. This should be a classic PAT with the full "repo" scope, or a fine-grained PAT or app installation token with "Secrets" set to "Read and write". In older instances of GitHub, a fine-grained token may not support the required GraphQL API and a "Classic" personal access token would be required. As this is deprecated, please try a fine-grained token first. 16 | 17 | ### `repositories` 18 | 19 | **Required**, Newline delimited regex expressions to select repositories. Repositories are limited to those in which the token user is an owner or collaborator. Set `repositories_list_regex` to `False` to use a hardcoded list of repositories. Archived repositories will be ignored. 20 | 21 | ### `github_api_url` 22 | 23 | Override default GitHub API URL. When not provided, the action will attempt to use an environment variable provided by the GitHub Action runner environment defaults. 24 | 25 | ### `repositories_list_regex` 26 | 27 | If this value is `true` (default), the action will find all repositories available to the token user and filter based upon the regex provided. If it is `false`, it is expected that `repositories` will be a newline delimited list in the form of org/name. 28 | 29 | ### `secrets` 30 | 31 | **Required**, Newline delimited regex expressions to select values from `process.env`. Use the action env to pass secrets from the repository in which this action runs with the `env` attribute of the step. 32 | 33 | ### `retries` 34 | 35 | The number of retries to attempt when making Github calls when triggering rate limits or abuse limits. Defaults to 3. 36 | 37 | ### `concurrency` 38 | 39 | The number of allowed concurrent calls to the set secret endpoint. Lower this number to avoid abuse limits. Defaults to 10. 40 | 41 | ### `dry_run` 42 | 43 | Run everything except for secret create and update functionality. 44 | 45 | ### `delete` 46 | 47 | When set to `true`, the action will find and delete the selected secrets from repositories. Defaults to `false`. 48 | 49 | ### `environment` 50 | 51 | If this value is set to the name of a valid environment in the target repositories, the action will not set repository secrets but instead only set environment secrets for the specified environment. When not set, will set repository secrets only. Only works if `target` is set to `actions` (default). 52 | 53 | ### `target` 54 | 55 | Target where secrets should be stored: `actions` (default), `codespaces` or `dependabot`. 56 | 57 | ## Usage 58 | 59 | ```yaml 60 | uses: jpoehnelt/secrets-sync-action@[insert version or commit] 61 | with: 62 | SECRETS: | 63 | ^FOO$ 64 | ^GITHUB_.* 65 | REPOSITORIES: | 66 | ${{github.repository}} 67 | DRY_RUN: true 68 | GITHUB_TOKEN: ${{ secrets.PERSONAL_GITHUB_TOKEN_CLASSIC }} 69 | GITHUB_API_URL: ${{ secrets.CUSTOM_GITHUB_API_URL }} 70 | CONCURRENCY: 10 71 | env: 72 | FOO: ${{github.run_id}} 73 | FOOBAR: BAZ 74 | ``` 75 | 76 | See the workflows in this repository for another example. 77 | -------------------------------------------------------------------------------- /__tests__/config.test.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { getConfig } from "../src/config"; 18 | 19 | function clearInputs() { 20 | Object.keys(process.env) 21 | .filter((k) => k.match(/INPUT_.*/)) 22 | .forEach((k) => { 23 | process.env[k] = ""; 24 | }); 25 | } 26 | 27 | describe("getConfig", () => { 28 | const SECRETS = ["FOO.*", "^BAR$"]; 29 | const REPOSITORIES = ["google/baz.*", "^google/foo$"]; 30 | const REPOSITORIES_LIST_REGEX = true; 31 | const GITHUB_API_URL = "https://api.github.com"; 32 | const GITHUB_API_URL_OVERRIDE = "overridden_api_url"; 33 | const GITHUB_TOKEN = "token"; 34 | const DRY_RUN = false; 35 | const RETRIES = 3; 36 | const CONCURRENCY = 50; 37 | const RUN_DELETE = false; 38 | const ENVIRONMENT = "production"; 39 | const TARGET = "actions"; 40 | 41 | // Must implement because operands for delete must be optional in typescript >= 4.0 42 | interface Inputs { 43 | INPUT_GITHUB_API_URL?: string; 44 | INPUT_GITHUB_TOKEN: string; 45 | INPUT_SECRETS: string; 46 | INPUT_REPOSITORIES: string; 47 | INPUT_REPOSITORIES_LIST_REGEX: string; 48 | INPUT_DRY_RUN: string; 49 | INPUT_RETRIES: string; 50 | INPUT_CONCURRENCY: string; 51 | INPUT_RUN_DELETE: string; 52 | INPUT_ENVIRONMENT: string; 53 | INPUT_TARGET: string; 54 | } 55 | const inputs: Inputs = { 56 | INPUT_GITHUB_API_URL: String(GITHUB_API_URL), 57 | INPUT_GITHUB_TOKEN: GITHUB_TOKEN, 58 | INPUT_SECRETS: SECRETS.join("\n"), 59 | INPUT_REPOSITORIES: REPOSITORIES.join("\n"), 60 | INPUT_REPOSITORIES_LIST_REGEX: String(REPOSITORIES_LIST_REGEX), 61 | INPUT_DRY_RUN: String(DRY_RUN), 62 | INPUT_RETRIES: String(RETRIES), 63 | INPUT_CONCURRENCY: String(CONCURRENCY), 64 | INPUT_RUN_DELETE: String(RUN_DELETE), 65 | INPUT_ENVIRONMENT: String(ENVIRONMENT), 66 | INPUT_TARGET: String(TARGET), 67 | }; 68 | 69 | beforeEach(() => { 70 | clearInputs(); 71 | }); 72 | 73 | afterAll(() => { 74 | clearInputs(); 75 | }); 76 | 77 | test("getConfig throws error on missing inputs", async () => { 78 | expect(() => getConfig()).toThrowError(); 79 | }); 80 | 81 | test("getConfig returns arrays for secrets and repositories", async () => { 82 | process.env = { ...process.env, ...inputs }; 83 | 84 | expect(getConfig()).toEqual({ 85 | GITHUB_API_URL, 86 | GITHUB_TOKEN, 87 | SECRETS, 88 | REPOSITORIES, 89 | REPOSITORIES_LIST_REGEX, 90 | DRY_RUN, 91 | RETRIES, 92 | CONCURRENCY, 93 | RUN_DELETE, 94 | ENVIRONMENT, 95 | TARGET, 96 | }); 97 | }); 98 | 99 | test("getConfig GITHUB_API_URL has fallback value", async () => { 100 | const inputsWithoutApiUrl = inputs; 101 | delete inputsWithoutApiUrl.INPUT_GITHUB_API_URL; 102 | delete process.env.GITHUB_API_URL; 103 | 104 | process.env = { ...process.env, ...inputsWithoutApiUrl }; 105 | expect(getConfig().GITHUB_API_URL).toEqual(GITHUB_API_URL); 106 | }); 107 | 108 | test("getConfig GITHUB_API_URL uses process.env.GITHUB_API_URL when present", async () => { 109 | process.env = { ...process.env, ...inputs }; 110 | process.env.GITHUB_API_URL = GITHUB_API_URL_OVERRIDE; 111 | expect(getConfig().GITHUB_API_URL).toEqual(GITHUB_API_URL_OVERRIDE); 112 | }); 113 | 114 | test("getConfig dry run should work with multiple values of true", async () => { 115 | process.env = { ...process.env, ...inputs }; 116 | 117 | const cases: [string, boolean][] = [ 118 | ["0", false], 119 | ["1", true], 120 | ["true", true], 121 | ["True", true], 122 | ["TRUE", true], 123 | ["false", false], 124 | ["False", false], 125 | ["FALSE", false], 126 | ["foo", false], 127 | ["", false], 128 | ]; 129 | 130 | for (const [value, expected] of cases) { 131 | process.env["INPUT_DRY_RUN"] = value; 132 | const actual = getConfig().DRY_RUN; 133 | expect(`${value}=${actual}`).toEqual(`${value}=${expected}`); 134 | } 135 | }); 136 | }); 137 | -------------------------------------------------------------------------------- /__tests__/github.test.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as config from "../src/config"; 18 | 19 | import { 20 | DefaultOctokit, 21 | filterReposByPatterns, 22 | listAllMatchingRepos, 23 | getRepos, 24 | publicKeyCache, 25 | setSecretForRepo, 26 | deleteSecretForRepo, 27 | } from "../src/github"; 28 | 29 | // @ts-ignore-next-line 30 | import fixture from "@octokit/fixtures/scenarios/api.github.com/get-repository/normalized-fixture.json"; 31 | import nock from "nock"; 32 | 33 | let octokit: any; 34 | 35 | beforeAll(() => { 36 | nock.disableNetConnect(); 37 | (config.getConfig as jest.Mock) = jest.fn().mockReturnValue({ 38 | GITHUB_TOKEN: "token", 39 | SECRETS: ["BAZ"], 40 | REPOSITORIES: [".*"], 41 | REPOSITORIES_LIST_REGEX: true, 42 | DRY_RUN: false, 43 | RETRIES: 3, 44 | }); 45 | 46 | octokit = DefaultOctokit({ 47 | auth: "", 48 | }); 49 | }); 50 | 51 | afterAll(() => { 52 | nock.enableNetConnect(); 53 | }); 54 | 55 | describe("listing repos from github", () => { 56 | const per_page = 3; 57 | beforeEach(() => { 58 | nock("https://api.github.com") 59 | .get(/\/user\/repos?.*page=1.*/) 60 | .reply(200, [ 61 | fixture[0].response, 62 | fixture[0].response, 63 | { archived: true, full_name: "foo/bar" }, 64 | ]); 65 | 66 | nock("https://api.github.com") 67 | .get(/\/user\/repos?.*page=2.*/) 68 | .reply(200, [fixture[0].response]); 69 | }); 70 | 71 | test("listAllReposForAuthenticatedUser returns from multiple pages", async () => { 72 | const repos = await listAllMatchingRepos({ 73 | patterns: [".*"], 74 | octokit, 75 | per_page, 76 | }); 77 | 78 | expect(repos.length).toEqual(3); 79 | }); 80 | 81 | test("listAllReposForAuthenticatedUser matches patterns", async () => { 82 | const repos = await listAllMatchingRepos({ 83 | patterns: ["octokit.*"], 84 | octokit, 85 | per_page, 86 | }); 87 | 88 | expect(repos.length).toEqual(3); 89 | }); 90 | 91 | test("listAllReposAccessibleToInstallation matches patterns", async () => { 92 | // Shadow original octokit with install token based one 93 | const origConfig = config.getConfig(); 94 | (config.getConfig as jest.Mock).mockImplementation(() => ({ 95 | ...origConfig, 96 | GITHUB_TOKEN: "ghs_installation_token", 97 | })); 98 | const octokit = DefaultOctokit({ 99 | auth: "", 100 | }); 101 | 102 | // Setup app install endpoint 103 | nock("https://api.github.com") 104 | .get(/\/installation\/repositories?.*page=1.*/) 105 | .reply(200, { 106 | repositories: [ 107 | fixture[0].response, 108 | fixture[0].response, 109 | { archived: true, full_name: "foo/bar" }, 110 | ], 111 | }); 112 | 113 | nock("https://api.github.com") 114 | .get(/\/installation\/repositories?.*page=2.*/) 115 | .reply(200, { 116 | repositories: [ 117 | fixture[0].response, 118 | fixture[0].response, // One more repo to distinguish installation endpoint from user endpoint 119 | ], 120 | }); 121 | 122 | // Query installation endpoint 123 | const repos = await listAllMatchingRepos({ 124 | patterns: ["octokit.*"], 125 | octokit, 126 | per_page, 127 | }); 128 | 129 | expect(repos.length).toEqual(4); 130 | }); 131 | }); 132 | 133 | describe("getting single repos from github", () => { 134 | nock.cleanAll(); 135 | 136 | const repo = fixture[0].response; 137 | 138 | beforeEach(() => { 139 | nock("https://api.github.com") 140 | .persist() 141 | .get(`/repos/${repo.full_name}`) 142 | .reply(fixture[0].status, fixture[0].response); 143 | }); 144 | 145 | test("getRepos returns from multiple pages", async () => { 146 | const repos = await getRepos({ 147 | patterns: [ 148 | fixture[0].response.full_name, 149 | fixture[0].response.full_name, 150 | fixture[0].response.full_name, 151 | ], 152 | octokit, 153 | }); 154 | 155 | expect(repos.length).toEqual(3); 156 | }); 157 | }); 158 | 159 | test("filterReposByPatterns matches patterns", async () => { 160 | expect(filterReposByPatterns([fixture[0].response], [".*"]).length).toBe(1); 161 | expect(filterReposByPatterns([fixture[0].response], ["nope"]).length).toBe(0); 162 | }); 163 | 164 | describe("setSecretForRepo", () => { 165 | const repo = fixture[0].response; 166 | const publicKey = { 167 | key_id: "1234", 168 | key: "HRkzRZD1+duhfvNvY8eiCPb+ihIjbvkvRyiehJCs8Vc=", 169 | }; 170 | 171 | jest.setTimeout(30000); 172 | 173 | const secrets = { FOO: "BAR" }; 174 | 175 | const repoEnvironment = "production"; 176 | 177 | let actionsPublicKeyMock: nock.Scope; 178 | let dependabotPublicKeyMock: nock.Scope; 179 | let codespacesPublicKeyMock: nock.Scope; 180 | let setActionsSecretMock: nock.Scope; 181 | let setDependabotSecretMock: nock.Scope; 182 | let setCodespacesSecretMock: nock.Scope; 183 | 184 | beforeEach(() => { 185 | nock.cleanAll(); 186 | 187 | publicKeyCache.clear(); 188 | 189 | actionsPublicKeyMock = nock("https://api.github.com") 190 | .get(`/repos/${repo.full_name}/actions/secrets/public-key`) 191 | .reply(200, publicKey); 192 | 193 | dependabotPublicKeyMock = nock("https://api.github.com") 194 | .get(`/repos/${repo.full_name}/dependabot/secrets/public-key`) 195 | .reply(200, publicKey); 196 | 197 | codespacesPublicKeyMock = nock("https://api.github.com") 198 | .get(`/repos/${repo.full_name}/codespaces/secrets/public-key`) 199 | .reply(200, publicKey); 200 | 201 | setActionsSecretMock = nock("https://api.github.com") 202 | .put(`/repos/${repo.full_name}/actions/secrets/FOO`, (body) => { 203 | expect(body.encrypted_value).toBeTruthy(); 204 | expect(body.key_id).toEqual(publicKey.key_id); 205 | return body; 206 | }) 207 | .reply(200); 208 | 209 | setDependabotSecretMock = nock("https://api.github.com") 210 | .put(`/repos/${repo.full_name}/dependabot/secrets/FOO`, (body) => { 211 | expect(body.encrypted_value).toBeTruthy(); 212 | expect(body.key_id).toEqual(publicKey.key_id); 213 | return body; 214 | }) 215 | .reply(200); 216 | 217 | setCodespacesSecretMock = nock("https://api.github.com") 218 | .put(`/repos/${repo.full_name}/codespaces/secrets/FOO`, (body) => { 219 | expect(body.encrypted_value).toBeTruthy(); 220 | expect(body.key_id).toEqual(publicKey.key_id); 221 | return body; 222 | }) 223 | .reply(200); 224 | }); 225 | 226 | test("setSecretForRepo with Actions target should retrieve public key for Actions", async () => { 227 | await setSecretForRepo( 228 | octokit, 229 | "FOO", 230 | secrets.FOO, 231 | repo, 232 | "", 233 | true, 234 | "actions" 235 | ); 236 | expect(actionsPublicKeyMock.isDone()).toBeTruthy(); 237 | }); 238 | 239 | test("setSecretForRepo with Dependabot target should retrieve public key for Dependabot", async () => { 240 | await setSecretForRepo( 241 | octokit, 242 | "FOO", 243 | secrets.FOO, 244 | repo, 245 | "", 246 | true, 247 | "dependabot" 248 | ); 249 | expect(dependabotPublicKeyMock.isDone()).toBeTruthy(); 250 | }); 251 | 252 | test("setSecretForRepo with Codespaces target should retrieve public key for Codespaces", async () => { 253 | await setSecretForRepo( 254 | octokit, 255 | "FOO", 256 | secrets.FOO, 257 | repo, 258 | "", 259 | true, 260 | "codespaces" 261 | ); 262 | expect(codespacesPublicKeyMock.isDone()).toBeTruthy(); 263 | }); 264 | 265 | test("setSecretForRepo should not set secret with dry run", async () => { 266 | await setSecretForRepo( 267 | octokit, 268 | "FOO", 269 | secrets.FOO, 270 | repo, 271 | "", 272 | true, 273 | "actions" 274 | ); 275 | expect(actionsPublicKeyMock.isDone()).toBeTruthy(); 276 | expect(setActionsSecretMock.isDone()).toBeFalsy(); 277 | }); 278 | 279 | test("setSecretForRepo with Actions target should call set secret endpoint for Actions", async () => { 280 | await setSecretForRepo( 281 | octokit, 282 | "FOO", 283 | secrets.FOO, 284 | repo, 285 | "", 286 | false, 287 | "actions" 288 | ); 289 | expect(setActionsSecretMock.isDone()).toBeTruthy(); 290 | }); 291 | 292 | test("setSecretForRepo with Dependabot target should call set secret endpoint for Dependabot", async () => { 293 | await setSecretForRepo( 294 | octokit, 295 | "FOO", 296 | secrets.FOO, 297 | repo, 298 | "", 299 | false, 300 | "dependabot" 301 | ); 302 | expect(setDependabotSecretMock.isDone()).toBeTruthy(); 303 | }); 304 | 305 | test("setSecretForRepo with Codespaces target should call set secret endpoint for Codespaces", async () => { 306 | await setSecretForRepo( 307 | octokit, 308 | "FOO", 309 | secrets.FOO, 310 | repo, 311 | "", 312 | false, 313 | "codespaces" 314 | ); 315 | expect(setCodespacesSecretMock.isDone()).toBeTruthy(); 316 | }); 317 | }); 318 | 319 | describe("setSecretForRepo with environment", () => { 320 | const repo = fixture[0].response; 321 | const publicKey = { 322 | key_id: "1234", 323 | key: "HRkzRZD1+duhfvNvY8eiCPb+ihIjbvkvRyiehJCs8Vc=", 324 | }; 325 | 326 | jest.setTimeout(30000); 327 | 328 | const secrets = { FOO: "BAR" }; 329 | 330 | const repoEnvironment = "production"; 331 | 332 | let environmentPublicKeyMock: nock.Scope; 333 | let setEnvironmentSecretMock: nock.Scope; 334 | 335 | beforeEach(() => { 336 | nock.cleanAll(); 337 | publicKeyCache.clear(); 338 | 339 | environmentPublicKeyMock = nock("https://api.github.com") 340 | .get( 341 | `/repositories/${repo.id}/environments/${repoEnvironment}/secrets/public-key` 342 | ) 343 | .reply(200, publicKey); 344 | 345 | setEnvironmentSecretMock = nock("https://api.github.com") 346 | .put( 347 | `/repositories/${repo.id}/environments/${repoEnvironment}/secrets/FOO`, 348 | (body) => { 349 | expect(body.encrypted_value).toBeTruthy(); 350 | expect(body.key_id).toEqual(publicKey.key_id); 351 | return body; 352 | } 353 | ) 354 | .reply(200); 355 | }); 356 | 357 | test("setSecretForRepo should retrieve public key", async () => { 358 | await setSecretForRepo( 359 | octokit, 360 | "FOO", 361 | secrets.FOO, 362 | repo, 363 | repoEnvironment, 364 | true, 365 | "actions" 366 | ); 367 | expect(environmentPublicKeyMock.isDone()).toBeTruthy(); 368 | }); 369 | 370 | test("setSecretForRepo should not set secret with dry run", async () => { 371 | await setSecretForRepo( 372 | octokit, 373 | "FOO", 374 | secrets.FOO, 375 | repo, 376 | repoEnvironment, 377 | true, 378 | "actions" 379 | ); 380 | expect(environmentPublicKeyMock.isDone()).toBeTruthy(); 381 | expect(setEnvironmentSecretMock.isDone()).toBeFalsy(); 382 | }); 383 | 384 | test("setSecretForRepo should not set secret with Dependabot target", async () => { 385 | await setSecretForRepo( 386 | octokit, 387 | "FOO", 388 | secrets.FOO, 389 | repo, 390 | repoEnvironment, 391 | true, 392 | "dependabot" 393 | ); 394 | expect(environmentPublicKeyMock.isDone()).toBeTruthy(); 395 | expect(setEnvironmentSecretMock.isDone()).toBeFalsy(); 396 | }); 397 | 398 | test("setSecretForRepo should call set secret endpoint", async () => { 399 | await setSecretForRepo( 400 | octokit, 401 | "FOO", 402 | secrets.FOO, 403 | repo, 404 | repoEnvironment, 405 | false, 406 | "actions" 407 | ); 408 | expect(nock.isDone()).toBeTruthy(); 409 | }); 410 | }); 411 | 412 | describe("deleteSecretForRepo", () => { 413 | const repo = fixture[0].response; 414 | 415 | jest.setTimeout(30000); 416 | 417 | const secrets = { FOO: "BAR" }; 418 | let deleteActionsSecretMock: nock.Scope; 419 | let deleteDependabotSecretMock: nock.Scope; 420 | let deleteCodespacesSecretMock: nock.Scope; 421 | 422 | beforeEach(() => { 423 | nock.cleanAll(); 424 | 425 | deleteActionsSecretMock = nock("https://api.github.com") 426 | .delete(`/repos/${repo.full_name}/actions/secrets/FOO`) 427 | .reply(200); 428 | 429 | deleteDependabotSecretMock = nock("https://api.github.com") 430 | .delete(`/repos/${repo.full_name}/dependabot/secrets/FOO`) 431 | .reply(200); 432 | 433 | deleteCodespacesSecretMock = nock("https://api.github.com") 434 | .delete(`/repos/${repo.full_name}/codespaces/secrets/FOO`) 435 | .reply(200); 436 | }); 437 | 438 | test("deleteSecretForRepo should not delete secret with dry run", async () => { 439 | await deleteSecretForRepo( 440 | octokit, 441 | "FOO", 442 | secrets.FOO, 443 | repo, 444 | "", 445 | true, 446 | "actions" 447 | ); 448 | expect(deleteActionsSecretMock.isDone()).toBeFalsy(); 449 | }); 450 | 451 | test("deleteSecretForRepo with Actions target should call set secret endpoint for Actions", async () => { 452 | await deleteSecretForRepo( 453 | octokit, 454 | "FOO", 455 | secrets.FOO, 456 | repo, 457 | "", 458 | false, 459 | "actions" 460 | ); 461 | expect(deleteActionsSecretMock.isDone()).toBeTruthy(); 462 | }); 463 | 464 | test("deleteSecretForRepo with Dependabot target should call set secret endpoint for Dependabot", async () => { 465 | await deleteSecretForRepo( 466 | octokit, 467 | "FOO", 468 | secrets.FOO, 469 | repo, 470 | "", 471 | false, 472 | "dependabot" 473 | ); 474 | expect(deleteDependabotSecretMock.isDone()).toBeTruthy(); 475 | }); 476 | 477 | test("deleteSecretForRepo with Codespaces target should call set secret endpoint for Codespaces", async () => { 478 | await deleteSecretForRepo( 479 | octokit, 480 | "FOO", 481 | secrets.FOO, 482 | repo, 483 | "", 484 | false, 485 | "codespaces" 486 | ); 487 | expect(deleteCodespacesSecretMock.isDone()).toBeTruthy(); 488 | }); 489 | }); 490 | 491 | describe("deleteSecretForRepo with environment", () => { 492 | const repo = fixture[0].response; 493 | 494 | const repoEnvironment = "production"; 495 | 496 | jest.setTimeout(30000); 497 | 498 | const secrets = { FOO: "BAR" }; 499 | let deleteSecretMock: nock.Scope; 500 | 501 | beforeEach(() => { 502 | nock.cleanAll(); 503 | deleteSecretMock = nock("https://api.github.com") 504 | .delete( 505 | `/repositories/${repo.id}/environments/${repoEnvironment}/secrets/FOO` 506 | ) 507 | .reply(200); 508 | }); 509 | 510 | test("deleteSecretForRepo should not delete secret with dry run", async () => { 511 | await deleteSecretForRepo( 512 | octokit, 513 | "FOO", 514 | secrets.FOO, 515 | repo, 516 | repoEnvironment, 517 | true, 518 | "actions" 519 | ); 520 | expect(deleteSecretMock.isDone()).toBeFalsy(); 521 | }); 522 | 523 | test("deleteSecretForRepo should not delete secret with Dependabot target", async () => { 524 | await deleteSecretForRepo( 525 | octokit, 526 | "FOO", 527 | secrets.FOO, 528 | repo, 529 | repoEnvironment, 530 | true, 531 | "dependabot" 532 | ); 533 | expect(deleteSecretMock.isDone()).toBeFalsy(); 534 | }); 535 | 536 | test("deleteSecretForRepo with Actions target should call set secret endpoint for Actions", async () => { 537 | await deleteSecretForRepo( 538 | octokit, 539 | "FOO", 540 | secrets.FOO, 541 | repo, 542 | repoEnvironment, 543 | false, 544 | "actions" 545 | ); 546 | expect(nock.isDone()).toBeTruthy(); 547 | }); 548 | }); 549 | -------------------------------------------------------------------------------- /__tests__/main.test.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as config from "../src/config"; 18 | import * as github from "../src/github"; 19 | import * as secrets from "../src/secrets"; 20 | 21 | // @ts-ignore-next-line 22 | import fixture from "@octokit/fixtures/scenarios/api.github.com/get-repository/normalized-fixture.json"; 23 | import nock from "nock"; 24 | import { run } from "../src/main"; 25 | 26 | nock.disableNetConnect(); 27 | 28 | beforeEach(() => {}); 29 | 30 | test("run should succeed with a repo and secret", async () => { 31 | (github.listAllMatchingRepos as jest.Mock) = jest 32 | .fn() 33 | .mockImplementation(async () => [fixture[0].response]); 34 | 35 | (github.setSecretForRepo as jest.Mock) = jest 36 | .fn() 37 | .mockImplementation(async () => null); 38 | 39 | (secrets.getSecrets as jest.Mock) = jest.fn().mockReturnValue({ 40 | BAZ: "bar", 41 | }); 42 | 43 | (config.getConfig as jest.Mock) = jest.fn().mockReturnValue({ 44 | GITHUB_TOKEN: "token", 45 | SECRETS: ["BAZ"], 46 | REPOSITORIES: [".*"], 47 | REPOSITORIES_LIST_REGEX: true, 48 | DRY_RUN: false, 49 | RETRIES: 3, 50 | CONCURRENCY: 1, 51 | TARGET: "actions", 52 | }); 53 | await run(); 54 | 55 | expect(github.listAllMatchingRepos as jest.Mock).toBeCalledTimes(1); 56 | expect((github.setSecretForRepo as jest.Mock).mock.calls[0][3]).toEqual( 57 | fixture[0].response 58 | ); 59 | 60 | expect(process.exitCode).toBe(undefined); 61 | }); 62 | 63 | test("run should succeed with a repo and secret with repository_list_regex as false", async () => { 64 | (github.getRepos as jest.Mock) = jest 65 | .fn() 66 | .mockImplementation(async () => [fixture[0].response]); 67 | 68 | (github.setSecretForRepo as jest.Mock) = jest 69 | .fn() 70 | .mockImplementation(async () => null); 71 | 72 | (secrets.getSecrets as jest.Mock) = jest.fn().mockReturnValue({ 73 | BAZ: "bar", 74 | }); 75 | 76 | (config.getConfig as jest.Mock) = jest.fn().mockReturnValue({ 77 | GITHUB_TOKEN: "token", 78 | SECRETS: ["BAZ"], 79 | REPOSITORIES: [fixture[0].response.full_name], 80 | REPOSITORIES_LIST_REGEX: false, 81 | DRY_RUN: false, 82 | CONCURRENCY: 1, 83 | TARGET: "actions", 84 | }); 85 | await run(); 86 | 87 | expect(github.getRepos as jest.Mock).toBeCalledTimes(1); 88 | expect((github.setSecretForRepo as jest.Mock).mock.calls[0][3]).toEqual( 89 | fixture[0].response 90 | ); 91 | 92 | expect(process.exitCode).toBe(undefined); 93 | }); 94 | 95 | test("run should succeed with delete enabled, a repo and secret with repository_list_regex as false", async () => { 96 | (github.deleteSecretForRepo as jest.Mock) = jest 97 | .fn() 98 | .mockImplementation(async () => null); 99 | 100 | (config.getConfig as jest.Mock) = jest.fn().mockReturnValue({ 101 | GITHUB_TOKEN: "token", 102 | SECRETS: ["BAZ"], 103 | REPOSITORIES: [fixture[0].response.full_name], 104 | REPOSITORIES_LIST_REGEX: false, 105 | DRY_RUN: false, 106 | RUN_DELETE: true, 107 | CONCURRENCY: 1, 108 | TARGET: "actions", 109 | }); 110 | await run(); 111 | 112 | expect(github.deleteSecretForRepo as jest.Mock).toBeCalledTimes(1); 113 | expect(process.exitCode).toBe(undefined); 114 | }); 115 | 116 | test("run should fail if target is not supported", async () => { 117 | (github.getRepos as jest.Mock) = jest 118 | .fn() 119 | .mockImplementation(async () => [fixture[0].response]); 120 | 121 | (github.setSecretForRepo as jest.Mock) = jest 122 | .fn() 123 | .mockImplementation(async () => null); 124 | 125 | (secrets.getSecrets as jest.Mock) = jest.fn().mockReturnValue({ 126 | BAZ: "bar", 127 | }); 128 | 129 | (config.getConfig as jest.Mock) = jest.fn().mockReturnValue({ 130 | GITHUB_TOKEN: "token", 131 | SECRETS: ["BAZ"], 132 | REPOSITORIES: [fixture[0].response.full_name], 133 | REPOSITORIES_LIST_REGEX: false, 134 | DRY_RUN: false, 135 | CONCURRENCY: 1, 136 | TARGET: "invalid", 137 | }); 138 | await run(); 139 | 140 | expect(process.exitCode).toBe(1); 141 | }); 142 | -------------------------------------------------------------------------------- /__tests__/secrets.test.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as core from "@actions/core"; 18 | 19 | import { getSecrets } from "../src/secrets"; 20 | 21 | const setSecretMock: jest.Mock = jest.fn(); 22 | 23 | beforeAll(() => { 24 | // @ts-ignore-next-line 25 | core.setSecret = setSecretMock; 26 | }); 27 | 28 | test("getSecrets matches with regex", async () => { 29 | const env = { FOO: "BAR" }; 30 | expect(getSecrets(["FO*"], env)).toEqual(env); 31 | }); 32 | 33 | test("getSecrets matches multiple keys with regex", async () => { 34 | const env = { FOO: "BAR", FOOO: "BAR" }; 35 | expect(getSecrets(["FO*"], env)).toEqual(env); 36 | }); 37 | 38 | test("getSecrets matches multiple keys with multiple regexs", async () => { 39 | const env = { FOO: "BAR", QUZ: "BAR" }; 40 | expect(getSecrets(["FOO", "Q.*"], env)).toEqual(env); 41 | }); 42 | 43 | test("getSecrets regex does not use case insensitive flag", async () => { 44 | const env = { FOO: "BAR" }; 45 | expect(getSecrets(["fo+"], env)).toEqual({}); 46 | }); 47 | 48 | test("getSecrets empty pattern returns no keys", async () => { 49 | const env = { FOO: "BAR" }; 50 | expect(getSecrets([], env)).toEqual({}); 51 | }); 52 | 53 | test("getSecrets using process.env", async () => { 54 | process.env.FOO = "bar"; 55 | expect(getSecrets([".*"]).FOO).toEqual(process.env.FOO); 56 | delete process.env.FOO; 57 | }); 58 | 59 | test("getSecrets does not add mask to GITHUB_", async () => { 60 | const env = { FOO: "BAR", GITHUB_FOO: "GITHUB_BAR" }; 61 | 62 | setSecretMock.mockClear(); 63 | getSecrets([".*"], env); 64 | 65 | expect((core.setSecret as jest.Mock).mock.calls.length).toBe(1); 66 | expect((core.setSecret as jest.Mock).mock.calls[0][0]).toBe(env.FOO); 67 | }); 68 | -------------------------------------------------------------------------------- /__tests__/utils.test.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { encrypt } from "../src/utils"; 18 | 19 | const key = "HRkzRZD1+duhfvNvY8eiCPb+ihIjbvkvRyiehJCs8Vc="; 20 | 21 | test("encrypt should return a value", () => { 22 | expect(encrypt("baz", key)).toBeTruthy(); 23 | }); 24 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | # action.yml 2 | name: "Secrets Sync Action" 3 | author: Justin Poehnelt 4 | branding: 5 | icon: 'copy' 6 | color: 'red' 7 | description: "Copies secrets from the action's environment to many other repos." 8 | inputs: 9 | github_token: 10 | description: "Token to use to get repos and write secrets" 11 | required: true 12 | github_api_url: 13 | description: | 14 | Override default GitHub API URL. When not provided, the action will attempt 15 | to use an environment variable provided by the GitHub Action runner environment 16 | defaults. 17 | required: false 18 | repositories: 19 | description: | 20 | New line deliminated regex expressions to select repositories. Repositories 21 | are limited to those in which the token user is an owner or collaborator. 22 | Set `REPOSITORIES_LIST_REGEX` to `False` to use a hardcoded list of 23 | repositories. Archived repositories will be ignored. 24 | required: true 25 | repositories_list_regex: 26 | default: "true" 27 | description: | 28 | If this value is `true`(default), the action will find all repositories 29 | available to the token user and filter based upon the regex provided. If 30 | it is false, it is expected that `REPOSITORIES` will be an a new line 31 | deliminated list in the form of org/name. 32 | required: false 33 | secrets: 34 | description: | 35 | New line deliminated regex expressions to select values from `process.env`. 36 | Use the action env to pass secrets from the repository in which this action 37 | runs with the `env` attribute of the step. 38 | required: true 39 | dry_run: 40 | description: | 41 | Run everything except for secret create and update functionality. 42 | required: false 43 | retries: 44 | description: | 45 | The number of retries to attempt when making Github calls. 46 | default: "3" 47 | required: false 48 | concurrency: 49 | description: | 50 | The number of allowed concurrent calls to the set secret endpoint. Lower this 51 | number to avoid abuse limits. 52 | default: "10" 53 | required: false 54 | delete: 55 | description: | 56 | When set to `true`, the action will find and delete the selected secrets from repositories. Defaults to `false`. 57 | default: false 58 | required: false 59 | environment: 60 | default: "" 61 | description: | 62 | If this value is set, the action will set the secrets to the repositories environment with the name of this value. 63 | Only works if `target` is set to `actions` (default). 64 | required: false 65 | target: 66 | description: | 67 | Target where secrets should be stored: `actions` (default), `codespaces` or `dependabot`. 68 | default: "actions" 69 | required: false 70 | runs: 71 | using: 'node20' 72 | main: 'dist/index.js' 73 | -------------------------------------------------------------------------------- /dist/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jpoehnelt/secrets-sync-action/7840777f242539d96b60477b66aa1c179e7644ea/dist/.gitkeep -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | module.exports = { 18 | clearMocks: true, 19 | moduleFileExtensions: ["js", "ts"], 20 | testEnvironment: "jest-environment-uint8array", // includes fix for https://github.com/facebook/jest/issues/4422 and Buffers 21 | testMatch: ["**/*.test.ts"], 22 | testRunner: "jest-circus/runner", 23 | transform: { 24 | "^.+\\.ts$": "ts-jest" 25 | }, 26 | verbose: true, 27 | collectCoverage: true, 28 | collectCoverageFrom: ["src/**/([a-zA-Z_]*).{js,ts}", "!**/*.test.{js,ts}"] 29 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "secrets-sync-action", 3 | "version": "0.0.0", 4 | "description": "Secrets sync action for Github", 5 | "keywords": [ 6 | "actions", 7 | "node", 8 | "setup" 9 | ], 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/jpoehnelt/secrets-sync-action.git" 13 | }, 14 | "license": "Apache 2.0", 15 | "author": "Justin Poehnelt", 16 | "main": "lib/index.js", 17 | "scripts": { 18 | "all": "npm run build && npm run format-check && npm run lint && npm test && npm run pack", 19 | "build": "tsc", 20 | "format": "prettier --write **/*.ts", 21 | "format-check": "prettier --check **/*.ts", 22 | "lint": "eslint src/**/*.ts", 23 | "lint-fix": "eslint --fix src/**/*.ts", 24 | "pack": "ncc build", 25 | "test": "jest" 26 | }, 27 | "dependencies": { 28 | "@actions/core": "^1.9.1", 29 | "@octokit/plugin-retry": "^3.0.1", 30 | "@octokit/plugin-throttling": "^3.2.0", 31 | "@octokit/rest": "^18.12.0", 32 | "p-limit": "^2.3.0", 33 | "tweetsodium": "0.0.4" 34 | }, 35 | "devDependencies": { 36 | "@octokit/fixtures": "^21.0.2", 37 | "@octokit/types": "^6.31.1", 38 | "@semantic-release/commit-analyzer": "^10.0.1", 39 | "@semantic-release/git": "^10.0.1", 40 | "@semantic-release/github": "^9.0.3", 41 | "@semantic-release/release-notes-generator": "^11.0.4", 42 | "@types/jest": "^24.0.23", 43 | "@types/node": "^12.12.30", 44 | "@types/tmp": "^0.1.0", 45 | "@typescript-eslint/parser": "^2.24.0", 46 | "@vercel/ncc": "^0.36.1", 47 | "eslint": "^5.16.0", 48 | "eslint-plugin-github": "^2.0.0", 49 | "eslint-plugin-jest": "^22.21.0", 50 | "flow-bin": "^0.211.1", 51 | "jest": "^24.9.0", 52 | "jest-circus": "^24.9.0", 53 | "jest-environment-uint8array": "^1.0.0", 54 | "js-yaml": "^3.13.1", 55 | "nock": "^12.0.3", 56 | "prettier": "^2.4.1", 57 | "semantic-release": "^21.0.7", 58 | "ts-jest": "^24.2.0", 59 | "typescript": "^4.0.0" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as core from "@actions/core"; 18 | 19 | export interface Config { 20 | GITHUB_API_URL: string; 21 | GITHUB_TOKEN: string; 22 | SECRETS: string[]; 23 | REPOSITORIES: string[]; 24 | REPOSITORIES_LIST_REGEX: boolean; 25 | DRY_RUN: boolean; 26 | RETRIES: number; 27 | CONCURRENCY: number; 28 | RUN_DELETE: boolean; 29 | ENVIRONMENT: string; 30 | TARGET: string; 31 | } 32 | 33 | export function getConfig(): Config { 34 | const config = { 35 | GITHUB_API_URL: 36 | core.getInput("GITHUB_API_URL") || 37 | process.env.GITHUB_API_URL || 38 | "https://api.github.com", 39 | GITHUB_TOKEN: core.getInput("GITHUB_TOKEN", { required: true }), 40 | CONCURRENCY: Number(core.getInput("CONCURRENCY")), 41 | RETRIES: Number(core.getInput("RETRIES")), 42 | SECRETS: core.getInput("SECRETS", { required: true }).split("\n"), 43 | REPOSITORIES: core.getInput("REPOSITORIES", { required: true }).split("\n"), 44 | REPOSITORIES_LIST_REGEX: ["1", "true"].includes( 45 | core 46 | .getInput("REPOSITORIES_LIST_REGEX", { required: false }) 47 | .toLowerCase() 48 | ), 49 | DRY_RUN: ["1", "true"].includes( 50 | core.getInput("DRY_RUN", { required: false }).toLowerCase() 51 | ), 52 | RUN_DELETE: ["1", "true"].includes( 53 | core.getInput("DELETE", { required: false }).toLowerCase() 54 | ), 55 | ENVIRONMENT: core.getInput("ENVIRONMENT", { required: false }), 56 | TARGET: core.getInput("TARGET", { required: false }), 57 | }; 58 | 59 | if (config.DRY_RUN) { 60 | core.info("[DRY_RUN='true'] No changes will be written to secrets"); 61 | } 62 | 63 | return config; 64 | } 65 | -------------------------------------------------------------------------------- /src/github.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as core from "@actions/core"; 18 | 19 | import { Octokit } from "@octokit/rest"; 20 | import { encrypt } from "./utils"; 21 | import { getConfig } from "./config"; 22 | import { retry } from "@octokit/plugin-retry"; 23 | 24 | export interface Repository { 25 | full_name: string; 26 | archived?: boolean; 27 | id: number; 28 | } 29 | 30 | export interface PublicKey { 31 | key: string; 32 | key_id: string; 33 | } 34 | 35 | export const publicKeyCache = new Map(); 36 | 37 | const RetryOctokit = Octokit.plugin(retry); 38 | 39 | export function DefaultOctokit({ ...octokitOptions }): any { 40 | const retries = getConfig().RETRIES; 41 | 42 | /* istanbul ignore next */ 43 | function onRateLimit(retryAfter: any, options: any): boolean { 44 | core.warning( 45 | `Request quota exhausted for request ${options.method} ${options.url}` 46 | ); 47 | 48 | if (options.request.retryCount < retries) { 49 | core.warning( 50 | `Retrying request ${options.method} ${options.url} after ${retryAfter} seconds!` 51 | ); 52 | return true; 53 | } 54 | core.warning(`Did not retry request ${options.method} ${options.url}`); 55 | return false; 56 | } 57 | 58 | /* istanbul ignore next */ 59 | function onAbuseLimit(retryAfter: any, options: any): boolean { 60 | core.warning(`Abuse detected for request ${options.method} ${options.url}`); 61 | 62 | if (options.request.retryCount < retries) { 63 | core.warning( 64 | `Retrying request ${options.method} ${options.url} after ${retryAfter} seconds!` 65 | ); 66 | return true; 67 | } 68 | core.warning(`Did not retry request ${options.method} ${options.url}`); 69 | return false; 70 | } 71 | 72 | const defaultOptions = { 73 | throttle: { 74 | onRateLimit, 75 | onAbuseLimit, 76 | }, 77 | }; 78 | 79 | return new RetryOctokit({ ...defaultOptions, ...octokitOptions }); 80 | } 81 | 82 | export async function getRepos({ 83 | patterns, 84 | octokit, 85 | }: { 86 | patterns: string[]; 87 | octokit: any; 88 | }): Promise { 89 | const repos: Repository[] = []; 90 | 91 | for (const pattern of patterns) { 92 | const [repo_owner, repo_name] = pattern.split("/"); 93 | const response = await octokit.repos.get({ 94 | owner: repo_owner, 95 | repo: repo_name, 96 | }); 97 | repos.push(response.data); 98 | } 99 | return repos.filter((r) => !r.archived); 100 | } 101 | 102 | export async function listAllMatchingRepos({ 103 | patterns, 104 | octokit, 105 | affiliation = "owner,collaborator,organization_member", 106 | per_page = 30, 107 | }: { 108 | patterns: string[]; 109 | octokit: any; 110 | affiliation?: string; 111 | per_page?: number; 112 | }): Promise { 113 | const usingInstallToken = getConfig().GITHUB_TOKEN.startsWith("ghs_"); 114 | const repos = await (usingInstallToken 115 | ? listAllReposAccessibleToInstallation({ 116 | octokit, 117 | per_page, 118 | }) 119 | : listAllReposForAuthenticatedUser({ 120 | octokit, 121 | affiliation, 122 | per_page, 123 | })); 124 | 125 | core.info( 126 | `Available repositories: ${JSON.stringify(repos.map((r) => r.full_name))}` 127 | ); 128 | 129 | return filterReposByPatterns(repos, patterns); 130 | } 131 | 132 | export async function listAllReposForAuthenticatedUser({ 133 | octokit, 134 | affiliation, 135 | per_page, 136 | }: { 137 | octokit: any; 138 | affiliation: string; 139 | per_page: number; 140 | }): Promise { 141 | const repos: Repository[] = []; 142 | 143 | for (let page = 1; ; page++) { 144 | const response = await octokit.repos.listForAuthenticatedUser({ 145 | affiliation, 146 | page, 147 | per_page, 148 | }); 149 | repos.push(...response.data); 150 | 151 | if (response.data.length < per_page) { 152 | break; 153 | } 154 | } 155 | return repos.filter((r) => !r.archived); 156 | } 157 | 158 | export async function listAllReposAccessibleToInstallation({ 159 | octokit, 160 | per_page, 161 | }: { 162 | octokit: any; 163 | per_page: number; 164 | }): Promise { 165 | const repos: Repository[] = []; 166 | 167 | for (let page = 1; ; page++) { 168 | const response = await octokit.apps.listReposAccessibleToInstallation({ 169 | page, 170 | per_page, 171 | }); 172 | repos.push(...response.data.repositories); 173 | 174 | if (response.data.repositories.length < per_page) { 175 | break; 176 | } 177 | } 178 | return repos.filter((r) => !r.archived); 179 | } 180 | 181 | export function filterReposByPatterns( 182 | repos: Repository[], 183 | patterns: string[] 184 | ): Repository[] { 185 | const regexPatterns = patterns.map((s) => new RegExp(s)); 186 | 187 | return repos.filter( 188 | (repo) => regexPatterns.filter((r) => r.test(repo.full_name)).length 189 | ); 190 | } 191 | 192 | export async function getPublicKey( 193 | octokit: any, 194 | repo: Repository, 195 | environment: string, 196 | target: string 197 | ): Promise { 198 | let publicKey = publicKeyCache.get(repo); 199 | 200 | if (!publicKey) { 201 | if (environment) { 202 | publicKey = ( 203 | await octokit.actions.getEnvironmentPublicKey({ 204 | repository_id: repo.id, 205 | environment_name: environment, 206 | }) 207 | ).data as PublicKey; 208 | 209 | publicKeyCache.set(repo, publicKey); 210 | 211 | return publicKey; 212 | } else { 213 | const [owner, name] = repo.full_name.split("/"); 214 | 215 | switch (target) { 216 | case "codespaces": 217 | publicKey = ( 218 | await octokit.codespaces.getRepoPublicKey({ 219 | owner, 220 | repo: name, 221 | }) 222 | ).data as PublicKey; 223 | 224 | publicKeyCache.set(repo, publicKey); 225 | 226 | return publicKey; 227 | case "dependabot": 228 | publicKey = ( 229 | await octokit.dependabot.getRepoPublicKey({ 230 | owner, 231 | repo: name, 232 | }) 233 | ).data as PublicKey; 234 | 235 | publicKeyCache.set(repo, publicKey); 236 | 237 | return publicKey; 238 | case "actions": 239 | default: 240 | publicKey = ( 241 | await octokit.actions.getRepoPublicKey({ 242 | owner, 243 | repo: name, 244 | }) 245 | ).data as PublicKey; 246 | 247 | publicKeyCache.set(repo, publicKey); 248 | 249 | return publicKey; 250 | } 251 | } 252 | } 253 | 254 | return publicKey; 255 | } 256 | 257 | export async function setSecretForRepo( 258 | octokit: any, 259 | name: string, 260 | secret: string, 261 | repo: Repository, 262 | environment: string, 263 | dry_run: boolean, 264 | target: string 265 | ): Promise { 266 | const [repo_owner, repo_name] = repo.full_name.split("/"); 267 | 268 | const publicKey = await getPublicKey(octokit, repo, environment, target); 269 | const encrypted_value = encrypt(secret, publicKey.key); 270 | 271 | core.info(`Set \`${name} = ***\` on ${repo.full_name}`); 272 | 273 | if (!dry_run) { 274 | switch (target) { 275 | case "codespaces": 276 | return octokit.codespaces.createOrUpdateRepoSecret({ 277 | owner: repo_owner, 278 | repo: repo_name, 279 | secret_name: name, 280 | key_id: publicKey.key_id, 281 | encrypted_value, 282 | }); 283 | case "dependabot": 284 | return octokit.dependabot.createOrUpdateRepoSecret({ 285 | owner: repo_owner, 286 | repo: repo_name, 287 | secret_name: name, 288 | key_id: publicKey.key_id, 289 | encrypted_value, 290 | }); 291 | case "actions": 292 | default: 293 | if (environment) { 294 | return octokit.actions.createOrUpdateEnvironmentSecret({ 295 | repository_id: repo.id, 296 | environment_name: environment, 297 | secret_name: name, 298 | key_id: publicKey.key_id, 299 | encrypted_value, 300 | }); 301 | } else { 302 | return octokit.actions.createOrUpdateRepoSecret({ 303 | owner: repo_owner, 304 | repo: repo_name, 305 | secret_name: name, 306 | key_id: publicKey.key_id, 307 | encrypted_value, 308 | }); 309 | } 310 | } 311 | } 312 | } 313 | 314 | export async function deleteSecretForRepo( 315 | octokit: any, 316 | name: string, 317 | secret: string, 318 | repo: Repository, 319 | environment: string, 320 | dry_run: boolean, 321 | target: string 322 | ): Promise { 323 | core.info(`Remove ${name} from ${repo.full_name}`); 324 | 325 | try { 326 | if (!dry_run) { 327 | const action = "DELETE"; 328 | switch (target) { 329 | case "codespaces": 330 | return octokit.request( 331 | `${action} /repos/${repo.full_name}/codespaces/secrets/${name}` 332 | ); 333 | case "dependabot": 334 | return octokit.request( 335 | `${action} /repos/${repo.full_name}/dependabot/secrets/${name}` 336 | ); 337 | case "actions": 338 | default: 339 | if (environment) { 340 | return octokit.request( 341 | `${action} /repositories/${repo.id}/environments/${environment}/secrets/${name}` 342 | ); 343 | } else { 344 | return octokit.request( 345 | `${action} /repos/${repo.full_name}/actions/secrets/${name}` 346 | ); 347 | } 348 | } 349 | } 350 | } catch (HttpError) { 351 | //If secret is not found in target repo, silently continue 352 | } 353 | } 354 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { run } from "./main"; 2 | 3 | /* istanbul ignore next */ 4 | run(); 5 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as core from "@actions/core"; 18 | 19 | import { 20 | DefaultOctokit, 21 | Repository, 22 | listAllMatchingRepos, 23 | setSecretForRepo, 24 | deleteSecretForRepo, 25 | getRepos, 26 | } from "./github"; 27 | 28 | import { getConfig } from "./config"; 29 | import { getSecrets } from "./secrets"; 30 | import pLimit from "p-limit"; 31 | 32 | export async function run(): Promise { 33 | try { 34 | const config = getConfig(); 35 | const secrets = getSecrets(config.SECRETS); 36 | 37 | /* istanbul ignore next */ 38 | if (!secrets) { 39 | core.setFailed(`Secrets: no matches with "${config.SECRETS.join(", ")}"`); 40 | return; 41 | } 42 | 43 | const allowedTargets = ["dependabot", "actions", "codespaces"]; 44 | if (!allowedTargets.some((x) => x === config.TARGET)) { 45 | core.setFailed( 46 | `Target: Value not in supported targets: ${allowedTargets}` 47 | ); 48 | return; 49 | } 50 | 51 | const octokit = DefaultOctokit({ 52 | auth: config.GITHUB_TOKEN, 53 | baseUrl: config.GITHUB_API_URL, 54 | }); 55 | 56 | let repos: Repository[]; 57 | if (config.REPOSITORIES_LIST_REGEX) { 58 | repos = await listAllMatchingRepos({ 59 | patterns: config.REPOSITORIES, 60 | octokit, 61 | }); 62 | } else { 63 | repos = await getRepos({ 64 | patterns: config.REPOSITORIES, 65 | octokit, 66 | }); 67 | } 68 | 69 | /* istanbul ignore next */ 70 | if (repos.length === 0) { 71 | const repoPatternString = config.REPOSITORIES.join(", "); 72 | core.setFailed( 73 | `Repos: No matches with "${repoPatternString}". Check your token and regex.` 74 | ); 75 | return; 76 | } 77 | 78 | const repoNames = repos.map((r) => r.full_name); 79 | 80 | core.info( 81 | JSON.stringify( 82 | { 83 | REPOSITORIES: config.REPOSITORIES, 84 | REPOSITORIES_LIST_REGEX: config.REPOSITORIES_LIST_REGEX, 85 | SECRETS: config.SECRETS, 86 | DRY_RUN: config.DRY_RUN, 87 | FOUND_REPOS: repoNames, 88 | FOUND_SECRETS: Object.keys(secrets), 89 | ENVIRONMENT: config.ENVIRONMENT, 90 | TARGET: config.TARGET, 91 | }, 92 | null, 93 | 2 94 | ) 95 | ); 96 | 97 | const limit = pLimit(config.CONCURRENCY); 98 | const calls: Promise[] = []; 99 | for (const repo of repos) { 100 | for (const k of Object.keys(secrets)) { 101 | const action = config.RUN_DELETE 102 | ? deleteSecretForRepo 103 | : setSecretForRepo; 104 | 105 | calls.push( 106 | limit(() => 107 | action( 108 | octokit, 109 | k, 110 | secrets[k], 111 | repo, 112 | config.ENVIRONMENT, 113 | config.DRY_RUN, 114 | config.TARGET 115 | ) 116 | ) 117 | ); 118 | } 119 | } 120 | await Promise.all(calls); 121 | } catch (error: any) { 122 | /* istanbul ignore next */ 123 | core.error(error); 124 | /* istanbul ignore next */ 125 | core.setFailed(error.message); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/secrets.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as core from "@actions/core"; 18 | 19 | /** 20 | * Get Secrets from the current environment using patterns to match keys. 21 | * @param patterns 22 | * @param env 23 | */ 24 | export function getSecrets( 25 | patterns: string[], 26 | env: NodeJS.ProcessEnv = process.env 27 | ): { [key: string]: string } { 28 | const regexPatterns = patterns.map((s) => new RegExp(s)); 29 | const keys = Object.keys(env); 30 | 31 | core.info(`Available env keys: ${JSON.stringify(keys)}`); 32 | 33 | return keys 34 | .filter((k: string) => { 35 | return env[k] && regexPatterns.filter((r) => r.test(k)).length; 36 | }) 37 | .reduce((o: { [key: string]: string }, k: string) => { 38 | // tell Github to mask this from logs 39 | if (!k.match(/GITHUB_.*/)) { 40 | core.setSecret(env[k] as string); 41 | } 42 | 43 | o[k] = env[k] as string; 44 | 45 | return o; 46 | }, {}); 47 | } 48 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as core from "@actions/core"; 18 | 19 | // @ts-ignore-next-line 20 | import { seal } from "tweetsodium"; 21 | 22 | export function encrypt(value: string, key: string): string { 23 | // Convert the message and key to Uint8Array's (Buffer implements that interface) 24 | const messageBytes = Buffer.from(value, "utf8"); 25 | const keyBytes = Buffer.from(key, "base64"); 26 | 27 | // Encrypt using LibSodium 28 | const encryptedBytes = seal(messageBytes, keyBytes); 29 | 30 | // Base64 the encrypted secret 31 | const encrypted = Buffer.from(encryptedBytes).toString("base64"); 32 | 33 | // tell Github to mask this from logs 34 | core.setSecret(encrypted); 35 | 36 | return encrypted; 37 | } 38 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ 4 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 5 | "outDir": "./lib", /* Redirect output structure to the directory. */ 6 | "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 7 | "strict": true, /* Enable all strict type-checking options. */ 8 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 9 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 10 | "resolveJsonModule": true 11 | 12 | }, 13 | "exclude": ["node_modules", "**/*.test.ts"] 14 | } --------------------------------------------------------------------------------