Compare commits

..

3 Commits

Author SHA1 Message Date
github-actions[bot] e1be5e75ed v3 new release (#72)
* Bump ansi-regex from 5.0.0 to 5.0.1 (#56)

Bumps [ansi-regex](https://github.com/chalk/ansi-regex) from 5.0.0 to 5.0.1.
- [Release notes](https://github.com/chalk/ansi-regex/releases)
- [Commits](https://github.com/chalk/ansi-regex/compare/v5.0.0...v5.0.1)

---
updated-dependencies:
- dependency-name: ansi-regex
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Vidya reddy prettier (#58)

* upgraded to Node16

* Enforce Prettier

* code fix

* jest version change and prettify code

Co-authored-by: Vidya Reddy <vidyareddy@microsoft.com>

* Upgraded the ncc version (#61)

Co-authored-by: Vidya Reddy <vidyareddy@microsoft.com>

* Update README example to v3 (#60)

* Bump @actions/core from 1.9.0 to 1.9.1 (#63)

Bumps [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) from 1.9.0 to 1.9.1.
- [Release notes](https://github.com/actions/toolkit/releases)
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/core/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/core)

---
updated-dependencies:
- dependency-name: "@actions/core"
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Add the issue report and feature request form (#64)

* syntax error fixes (#66)

* added support message (#67)

* Bump @actions/core (#68)

to address https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/

* Add node modules and compiled JavaScript from main

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Vidya Reddy <59590642+Vidya2606@users.noreply.github.com>
Co-authored-by: Vidya Reddy <vidyareddy@microsoft.com>
Co-authored-by: Oliver King <olivermerkleyking@gmail.com>
Co-authored-by: Asa Gayle <azmatch.gayle@gmail.com>
Co-authored-by: Sumner Warren <sumner.warren@gmail.com>
Co-authored-by: Oliver King <oking3@uncc.edu>
2022-12-05 13:21:32 -05:00
Oliver King b196533533 Delete node_modules directory (#71) 2022-12-05 12:02:40 -05:00
github-actions[bot] 7f7e5ba5ea Add node modules and compiled JavaScript from main (#57)
Co-authored-by: Oliver King <oking3@uncc.edu>
2022-06-21 12:18:30 -04:00
26 changed files with 18362 additions and 26368 deletions
+1 -1
View File
@@ -1 +1 @@
* @Azure/cloud-native-github-action-owners
* @Azure/aks-atlanta
-18
View File
@@ -1,18 +0,0 @@
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
groups:
actions:
patterns:
- '*'
- package-ecosystem: github-actions
directory: .github/workflows
schedule:
interval: weekly
groups:
actions:
patterns:
- '*'
-91
View File
@@ -1,91 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: 'CodeQL Advanced'
on:
push:
branches: ['main']
pull_request:
branches: ['main']
schedule:
- cron: '15 9 * * 0'
jobs:
analyze:
name: Analyze (${{ matrix.language }})
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
permissions:
# required for all workflows
security-events: write
# required to fetch internal or private CodeQL packs
packages: read
# only required for workflows in private repositories
actions: read
contents: read
strategy:
fail-fast: false
matrix:
include:
- language: javascript-typescript
build-mode: none
# CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- if: matrix.build-mode == 'manual'
shell: bash
run: |
echo 'If you are using a "manual" build mode for one or more of the' \
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
category: '/language:${{matrix.language}}'
+2 -2
View File
@@ -8,7 +8,7 @@ jobs:
label-issues:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
- uses: actions/stale@v3
name: Setting issue as idle
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
@@ -19,7 +19,7 @@ jobs:
operations-per-run: 100
exempt-issue-labels: 'backlog'
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
- uses: actions/stale@v3
name: Setting PR as idle
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
+4 -40
View File
@@ -17,7 +17,7 @@ jobs:
KUBECONFIG: /home/runner/.kube/config
PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@v2
name: Checkout from PR branch
- id: action-npm-build
@@ -27,11 +27,9 @@ jobs:
if [[ $PR_BASE_REF != releases/* ]]; then
npm install
npm run build
# remove node_modules to match production environment where only index.js is present
rm -rf node_modules
fi
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
- uses: actions/setup-python@v2
name: Install Python
with:
python-version: '3.x'
@@ -39,47 +37,13 @@ jobs:
- name: Install requests library
run: pip install requests
- name: Setup kubectl latest
uses: ./
with:
version: 'latest'
- name: Validate kubectl setup
run: python test/validate-kubectl.py latest
- name: Setup kubectl old version
- name: Setup kubectl
uses: ./
with:
version: 'v1.15.1'
- name: Validate kubectl setup old version
- name: Validate kubectl setup
run: python test/validate-kubectl.py 'v1.15.1'
- name: Fetch known SHA256 for v1.30.0 linux/amd64
id: sha
run: |
value=$(curl -fsSL https://dl.k8s.io/release/v1.30.0/bin/linux/amd64/kubectl.sha256)
echo "value=$value" >> "$GITHUB_OUTPUT"
- name: Setup kubectl with valid checksum
uses: ./
with:
version: 'v1.30.0'
checksum: ${{ steps.sha.outputs.value }}
- name: Validate kubectl setup with checksum
run: python test/validate-kubectl.py 'v1.30.0'
- name: Setup kubectl with bad checksum (expect failure)
id: badsum
continue-on-error: true
uses: ./
with:
version: 'v1.29.0'
checksum: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef'
- name: Assert bad-checksum step failed
if: steps.badsum.outcome != 'failure'
run: |
echo "Expected bad-checksum step to fail, but outcome was: ${{ steps.badsum.outcome }}"
exit 1
+4 -11
View File
@@ -10,16 +10,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- name: Enforce Prettier
uses: actionsx/prettier@v2
with:
node-version: 'lts/*'
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Run Prettier Check
run: npx prettier --check .
args: --check .
+8 -12
View File
@@ -1,18 +1,14 @@
name: Release Project
name: Create release PR
on:
push:
branches:
- main
paths:
- CHANGELOG.md
workflow_dispatch:
inputs:
release:
description: 'Define release version (ex: v1, v2, v3)'
required: true
jobs:
release:
permissions:
actions: read
contents: write
uses: Azure/action-release-workflows/.github/workflows/release_js_project.yaml@a391b701462581f586d0e8a68e60b04aa47dc4a9 # v1.2.0
release-pr:
uses: OliverMKing/javascript-release-workflow/.github/workflows/release-pr.yml@main
with:
changelogPath: ./CHANGELOG.md
release: ${{ github.event.inputs.release }}
+10
View File
@@ -0,0 +1,10 @@
name: Tag and create release draft
on:
push:
branches:
- releases/*
jobs:
tag-and-release:
uses: OliverMKing/javascript-release-workflow/.github/workflows/tag-and-release.yml@main
+1 -2
View File
@@ -13,10 +13,9 @@ jobs:
build: # make sure build/ci works properly
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@v1
- name: Build and run L0 tests.
run: |
npm install
npm run build
npm test
-32
View File
@@ -1,32 +0,0 @@
set +e
npm test
npm run format-check || {
echo ""
echo "❌ Formatting check failed."
echo "💡 Run 'npm run format' or 'prettier --write .' to fix formatting issues."
exit 1
}
STAGED=$(git diff --cached --name-only)
if echo "$STAGED" | grep -qE '^(package\.json|package-lock\.json|CHANGELOG\.md)$'; then
PKG_VERSION=$(node -p "require('./package.json').version")
LOCK_VERSION=$(node -p "require('./package-lock.json').version")
CHANGELOG_VERSION=$(sed -n 's/^## \[\([^]]*\)\].*/\1/p' CHANGELOG.md | head -1)
MISMATCH=""
if [ "$PKG_VERSION" != "$LOCK_VERSION" ]; then
MISMATCH="${MISMATCH}\n package.json: ${PKG_VERSION}\n package-lock.json: ${LOCK_VERSION}"
fi
if [ "$PKG_VERSION" != "$CHANGELOG_VERSION" ]; then
MISMATCH="${MISMATCH}\n package.json: ${PKG_VERSION}\n CHANGELOG.md: ${CHANGELOG_VERSION}"
fi
if [ -n "$MISMATCH" ]; then
echo ""
echo "❌ Version mismatch detected:"
echo -e "$MISMATCH"
echo ""
echo "💡 Ensure package.json, package-lock.json, and CHANGELOG.md all have the same version."
exit 1
fi
fi
-94
View File
@@ -1,94 +0,0 @@
# Changelog
## [5.2.0] - 2026-10-05
### Added
- #268 [Add custom download URL, checksum verification, and download authentication inputs](https://github.com/Azure/setup-kubectl/pull/268)
### Fixed
- #251 [Add Node.js types for TypeScript 6 compatibility](https://github.com/Azure/setup-kubectl/pull/251)
### Changed
- #267 [Pin the release workflow to a commit SHA](https://github.com/Azure/setup-kubectl/pull/267)
- #252 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/252)
- #253 [Update CI action dependencies](https://github.com/Azure/setup-kubectl/pull/253)
- #254 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/254)
- #255 [Update CodeQL action](https://github.com/Azure/setup-kubectl/pull/255)
- #257 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/257)
- #258 [Update CodeQL action](https://github.com/Azure/setup-kubectl/pull/258)
- #262 [Update Node.js type definitions](https://github.com/Azure/setup-kubectl/pull/262)
- #263 [Update CodeQL action](https://github.com/Azure/setup-kubectl/pull/263)
- #265 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/265)
- #266 [Update CI action dependencies](https://github.com/Azure/setup-kubectl/pull/266)
- #269 [Update Vitest](https://github.com/Azure/setup-kubectl/pull/269)
- #270 [Update Node.js type definitions](https://github.com/Azure/setup-kubectl/pull/270)
- #271 [Update CI action dependencies](https://github.com/Azure/setup-kubectl/pull/271)
- #272 [Update esbuild](https://github.com/Azure/setup-kubectl/pull/272)
- #273 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/273)
- #274 [Update Node.js type definitions](https://github.com/Azure/setup-kubectl/pull/274)
- #275 [Update checkout action](https://github.com/Azure/setup-kubectl/pull/275)
- #281 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/281)
- #282 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/282)
- #284 [Update Prettier](https://github.com/Azure/setup-kubectl/pull/284)
- #285 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/285)
- #287 [Update CI action dependencies](https://github.com/Azure/setup-kubectl/pull/287)
- #293 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/293)
- #294 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/294)
- #295 [Update CI action dependencies](https://github.com/Azure/setup-kubectl/pull/295)
- #299 [Update action dependencies](https://github.com/Azure/setup-kubectl/pull/299)
### Security
- #256 [Update postcss](https://github.com/Azure/setup-kubectl/pull/256)
- #276 [Update undici](https://github.com/Azure/setup-kubectl/pull/276)
- #289 [Update undici](https://github.com/Azure/setup-kubectl/pull/289)
- #290 [Update postcss](https://github.com/Azure/setup-kubectl/pull/290)
## [5.1.0] - 2026-04-11
### Changed
- #243 [Migrate to ESM with esbuild and vitest](https://github.com/Azure/setup-kubectl/pull/243)
- Replaced `@vercel/ncc` with `esbuild` for ESM bundling
- Replaced `jest`/`ts-jest` with `vitest` for testing
- Upgraded `@actions/core` to `^3.0.0`, `@actions/exec` to `^3.0.0`, `@actions/tool-cache` to `^4.0.0`
- Updated `tsconfig.json` to `NodeNext` module resolution
- Add `npm run build` step to CI unit-tests workflow
### Security
- #242 [Bump picomatch](https://github.com/Azure/setup-kubectl/pull/242)
- #244 [Bump handlebars from 4.7.8 to 4.7.9](https://github.com/Azure/setup-kubectl/pull/244)
- #247 [Bump vite from 8.0.3 to 8.0.5](https://github.com/Azure/setup-kubectl/pull/247)
- #245 [Bump github/codeql-action in CI workflows](https://github.com/Azure/setup-kubectl/pull/245)
## [5.0.0] - 2026-03-25
### Changed
- #233 [Update Node.js runtime from node20 to node24](https://github.com/Azure/setup-kubectl/pull/233)
- #228 [Replace cdn.dl.k8s.io with dl.k8s.io](https://github.com/Azure/setup-kubectl/pull/228)
- #219 [Remove download redirects, use cdn.dl.k8s.io domain](https://github.com/Azure/setup-kubectl/pull/219)
- #190 [Update stableVersionUrl to dl.k8s.io](https://github.com/Azure/setup-kubectl/pull/190)
- #235 [Bump undici from 6.23.0 to 6.24.1](https://github.com/Azure/setup-kubectl/pull/235)
- #226 [Bump undici and @actions/http-client](https://github.com/Azure/setup-kubectl/pull/226)
- #230 [Bump minimatch](https://github.com/Azure/setup-kubectl/pull/230)
### Added
- #172 [Enhance version handling: auto-resolve kubectl major.minor to latest patch](https://github.com/Azure/setup-kubectl/pull/172)
- #171 [Add husky precommit check](https://github.com/Azure/setup-kubectl/pull/171)
## [4.0.1] - 2025-06-17
- Remove erronious 'v' prefix on previous changelog for v4.0.0 that led to "vv4.0.0" tag issue
- Dependabot fixes
## [4.0.0] - 2024-01-30
### Changed
- #90 Migrate to node 20 as node 16 is deprecated
+3 -3
View File
@@ -4,6 +4,6 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope
Resources:
- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
+1 -1
View File
@@ -5,7 +5,7 @@
Acceptable values are latest or any semantic version string like `v1.15.0`. Use this action in workflow to define which version of kubectl will be used.
```yaml
- uses: azure/setup-kubectl@v4
- uses: azure/setup-kubectl@v3
with:
version: '<version>' # default is latest stable
id: install
+7 -7
View File
@@ -14,13 +14,13 @@ You should receive a response within 24 hours. If for some reason you do not, pl
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
- Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
- Full paths of source file(s) related to the manifestation of the issue
- The location of the affected source code (tag/branch/commit or direct URL)
- Any special configuration required to reproduce the issue
- Step-by-step instructions to reproduce the issue
- Proof-of-concept or exploit code (if possible)
- Impact of the issue, including how an attacker might exploit the issue
- Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
- Full paths of source file(s) related to the manifestation of the issue
- The location of the affected source code (tag/branch/commit or direct URL)
- Any special configuration required to reproduce the issue
- Step-by-step instructions to reproduce the issue
- Proof-of-concept or exploit code (if possible)
- Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
+2 -14
View File
@@ -1,27 +1,15 @@
name: 'Kubectl tool installer'
description: 'Install a specific version of kubectl binary. Acceptable values are latest or any semantic version string like "v1.15.0"'
description: 'Install a specific version of kubectl binary. Acceptable values are latest or any semantic version string like 1.15.0'
inputs:
version:
description: 'Version of kubectl'
required: true
default: 'latest'
downloadBaseURL:
description: 'Base URL to download kubectl from (https only). Use for private mirrors.'
required: false
default: 'https://dl.k8s.io'
checksum:
description: 'Expected SHA256 of the kubectl binary (lowercase 64-char hex). Required when overriding downloadBaseURL; the action fails closed without it to prevent unverified binaries from poisoning the tool cache.'
required: false
default: ''
downloadAuthToken:
description: 'Optional bearer token sent as the Authorization header when fetching from downloadBaseURL. Stripped on cross-origin redirects.'
required: false
default: ''
outputs:
kubectl-path:
description: 'Path to the cached kubectl binary'
branding:
color: 'blue'
runs:
using: 'node24'
using: 'node16'
main: 'lib/index.js'
+18
View File
@@ -0,0 +1,18 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.ts$': 'ts-jest'
},
verbose: true,
coverageThreshold: {
global: {
branches: 0,
functions: 14,
lines: 27,
statements: 27
}
}
}
+7386 -22775
View File
File diff suppressed because one or more lines are too long
+10686 -1868
View File
File diff suppressed because it is too large Load Diff
+15 -18
View File
@@ -1,17 +1,14 @@
{
"name": "setup-kubectl-action",
"version": "5.2.0",
"version": "0.0.0",
"private": true,
"main": "lib/index.js",
"type": "module",
"scripts": {
"build": "tsc --noEmit && esbuild src/index.ts --bundle --platform=node --target=node20 --format=esm --outfile=lib/index.js --banner:js=\"import { createRequire } from 'module';const require = createRequire(import.meta.url);\"",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test-coverage": "vitest run --coverage",
"build": "ncc build src/run.ts -o lib",
"test": "jest",
"test-coverage": "jest --coverage",
"format": "prettier --write .",
"format-check": "prettier --check .",
"prepare": "husky"
"format-check": "prettier --check ."
},
"keywords": [
"actions",
@@ -21,17 +18,17 @@
"author": "GitHub",
"license": "MIT",
"dependencies": {
"@actions/core": "^3.0.1",
"@actions/exec": "^3.0.0",
"@actions/http-client": "^4.0.1",
"@actions/tool-cache": "^4.0.0"
"@actions/core": "^1.10.0",
"@actions/exec": "^1.0.0",
"@actions/tool-cache": "^1.0.0"
},
"devDependencies": {
"@types/node": "^26.4.1",
"esbuild": "^0.28.2",
"husky": "^9.1.7",
"prettier": "3.9.6",
"typescript": "7.0.2",
"vitest": "^5.0.0"
"@types/jest": "^26.0.0",
"@types/node": "^12.0.4",
"@vercel/ncc": "^0.34.0",
"jest": "^26.0.1",
"prettier": "2.7.1",
"ts-jest": "^26.0.0",
"typescript": "3.9.2"
}
}
+19 -282
View File
@@ -1,223 +1,5 @@
import * as os from 'os'
import * as fs from 'fs'
import * as net from 'net'
import * as dns from 'dns'
import * as path from 'path'
import * as crypto from 'crypto'
import * as core from '@actions/core'
import * as toolCache from '@actions/tool-cache'
import {HttpClient} from '@actions/http-client'
export const DEFAULT_KUBECTL_BASE_URL = 'https://dl.k8s.io'
export function normalizeBaseURL(input: string): string {
const u = new URL(input)
return `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/, '')}`
}
export function isDefaultBaseURL(input: string): boolean {
try {
return (
normalizeBaseURL(input) === normalizeBaseURL(DEFAULT_KUBECTL_BASE_URL)
)
} catch {
return false
}
}
const SECURE_DOWNLOAD_MAX_BYTES = 256 * 1024 * 1024
const SECURE_DOWNLOAD_MAX_REDIRECTS = 5
export async function secureDownload(
downloadURL: string,
authToken: string = ''
): Promise<string> {
const client = new HttpClient('setup-kubectl', [], {
allowRedirects: false
})
const initialOrigin = new URL(downloadURL).origin
let currentURL = downloadURL
let response!: Awaited<ReturnType<HttpClient['get']>>
let status: number | undefined
for (let hop = 0; hop <= SECURE_DOWNLOAD_MAX_REDIRECTS; hop++) {
await assertHostResolvesSafely(new URL(currentURL).hostname)
const sameOrigin = new URL(currentURL).origin === initialOrigin
const headers =
authToken && sameOrigin
? {Authorization: `Bearer ${authToken}`}
: undefined
response = await client.get(currentURL, headers)
status = response.message.statusCode
if (!status || status < 300 || status >= 400) break
const locationHeader = response.message.headers['location']
const location = Array.isArray(locationHeader)
? locationHeader[0]
: locationHeader
response.message.resume()
if (!location) {
throw new Error(
`Redirect from custom downloadBaseURL had no Location header (status ${status}).`
)
}
if (hop === SECURE_DOWNLOAD_MAX_REDIRECTS) {
throw new Error(
`Refusing download: exceeded ${SECURE_DOWNLOAD_MAX_REDIRECTS} redirects from custom downloadBaseURL.`
)
}
// Re-validate the redirect target so a mirror can't bounce us to a literal internal IP.
const next = new URL(location, currentURL)
validateBaseURL(next.toString())
currentURL = next.toString()
}
if (status !== 200) {
response.message.resume()
throw typeof status === 'number'
? new toolCache.HTTPError(status)
: new Error(
`Refusing download: no HTTP status returned for ${currentURL} (network or TLS error).`
)
}
const contentLengthHeader = response.message.headers['content-length']
const contentLength = Array.isArray(contentLengthHeader)
? contentLengthHeader[0]
: contentLengthHeader
if (contentLength) {
const declared = Number.parseInt(contentLength, 10)
if (Number.isFinite(declared) && declared > SECURE_DOWNLOAD_MAX_BYTES) {
response.message.resume()
throw new Error(
`Refusing download: Content-Length ${declared} exceeds cap ${SECURE_DOWNLOAD_MAX_BYTES} bytes.`
)
}
}
const tmpDir = process.env['RUNNER_TEMP'] || os.tmpdir()
const tmpFile = path.join(tmpDir, `kubectl-${crypto.randomUUID()}`)
// 'wx' = create exclusive, so we never silently overwrite an existing file.
const fd = fs.openSync(tmpFile, 'wx')
let received = 0
let success = false
try {
for await (const chunk of response.message as AsyncIterable<Buffer>) {
received += chunk.length
if (received > SECURE_DOWNLOAD_MAX_BYTES) {
response.message.destroy()
throw new Error(
`Refusing download: response body exceeded cap ${SECURE_DOWNLOAD_MAX_BYTES} bytes.`
)
}
fs.writeSync(fd, chunk)
}
success = true
} finally {
try {
fs.closeSync(fd)
} catch {
/* empty */
}
if (!success) {
try {
fs.unlinkSync(tmpFile)
} catch {
/* empty */
}
}
}
return tmpFile
}
export function validateBaseURL(input: string): URL {
let url: URL
try {
url = new URL(input)
} catch {
throw new Error(`Invalid downloadBaseURL: "${input}" is not a valid URL.`)
}
if (url.protocol !== 'https:') {
throw new Error(
`downloadBaseURL must use https://, got "${url.protocol}" in "${input}".`
)
}
if (url.username || url.password) {
throw new Error(
'downloadBaseURL must not contain userinfo (user:pass@host).'
)
}
// Strip IPv6 brackets so net.isIP recognises the address.
const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, '')
const family = net.isIP(host)
if (family !== 0 && isBlockedIP(host, family)) {
throw new Error(
`downloadBaseURL host "${host}" is a literal loopback/link-local/private IP and is blocked.`
)
}
return url
}
// Loopback, link-local (incl. IMDS 169.254.169.254), RFC1918, IPv6 ULA, v4-mapped IPv6.
export function isBlockedIP(host: string, family: number): boolean {
return (
host === '::1' ||
host === '::' ||
host === '0.0.0.0' ||
/^127\./.test(host) ||
/^169\.254\./.test(host) ||
/^10\./.test(host) ||
/^192\.168\./.test(host) ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(host) ||
(family === 6 && /^f[cd]/.test(host)) || // ULA fc00::/7
(family === 6 && /^fe[89ab]/.test(host)) || // link-local fe80::/10
(family === 6 && host.startsWith('::ffff:')) // v4-mapped IPv6
)
}
// Reject hostnames whose DNS resolves to any blocked range. Closes the SSRF hole
// where an attacker controls DNS for a public-looking name pointed at internal IPs.
export async function assertHostResolvesSafely(
hostname: string
): Promise<void> {
const bare = hostname.replace(/^\[|\]$/g, '')
if (net.isIP(bare) !== 0) return
let addresses: dns.LookupAddress[]
try {
addresses = await dns.promises.lookup(bare, {all: true, verbatim: true})
} catch (err) {
throw new Error(
`Failed to resolve downloadBaseURL host "${bare}": ${
err instanceof Error ? err.message : String(err)
}`
)
}
for (const {address, family} of addresses) {
if (isBlockedIP(address.toLowerCase(), family)) {
throw new Error(
`downloadBaseURL host "${bare}" resolved to a blocked address (${address}); refusing to fetch.`
)
}
}
}
export function validateVersion(version: string): void {
if (!/^v?\d+\.\d+\.\d+$/.test(version)) {
throw new Error(
`Invalid kubectl version: "${version}". Expected a value like "v1.30.0".`
)
}
}
import * as util from 'util'
export function getKubectlArch(): string {
const arch = os.arch()
@@ -227,74 +9,29 @@ export function getKubectlArch(): string {
return arch
}
export function getkubectlDownloadURL(
version: string,
arch: string,
baseURL: string = DEFAULT_KUBECTL_BASE_URL
): string {
validateVersion(version)
const url = validateBaseURL(baseURL)
let osDir: string
let file: string
export function getkubectlDownloadURL(version: string, arch: string): string {
switch (os.type()) {
case 'Linux':
osDir = 'linux'
file = 'kubectl'
break
return util.format(
'https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubectl',
version,
arch
)
case 'Darwin':
osDir = 'darwin'
file = 'kubectl'
break
return util.format(
'https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/%s/kubectl',
version,
arch
)
case 'Windows_NT':
default:
osDir = 'windows'
file = 'kubectl.exe'
break
}
const basePath = url.pathname.replace(/\/+$/, '')
url.pathname = `${basePath}/release/${version}/bin/${osDir}/${arch}/${file}`
return url.toString()
}
export async function getLatestPatchVersion(
major: string,
minor: string,
baseURL: string = DEFAULT_KUBECTL_BASE_URL,
authToken: string = ''
): Promise<string> {
const version = `${major}.${minor}`
const url = validateBaseURL(baseURL)
const basePath = url.pathname.replace(/\/+$/, '')
url.pathname = `${basePath}/release/stable-${version}.txt`
const sourceURL = url.toString()
const useSecure = !isDefaultBaseURL(baseURL)
let downloadPath = ''
try {
downloadPath = useSecure
? await secureDownload(sourceURL, authToken)
: await toolCache.downloadTool(sourceURL)
const latestPatch = fs
.readFileSync(downloadPath, 'utf8')
.toString()
.trim()
if (!latestPatch) {
throw new Error(`No patch version found for ${version}`)
}
return latestPatch
} catch (error) {
core.debug(String(error))
core.warning('GetLatestPatchVersionFailed')
throw new Error(`Failed to get latest patch version for ${version}`)
} finally {
if (useSecure && downloadPath) {
try {
fs.unlinkSync(downloadPath)
} catch {
/* best-effort cleanup of secureDownload temp file */
}
}
return util.format(
'https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/%s/kubectl.exe',
version,
arch
)
}
}
-4
View File
@@ -1,4 +0,0 @@
import {run} from './run.js'
import * as core from '@actions/core'
run().catch(core.setFailed)
+155 -880
View File
File diff suppressed because it is too large Load Diff
+36 -192
View File
@@ -1,77 +1,27 @@
import * as path from 'path'
import * as util from 'util'
import * as fs from 'fs'
import * as crypto from 'crypto'
import * as toolCache from '@actions/tool-cache'
import * as core from '@actions/core'
import {
DEFAULT_KUBECTL_BASE_URL,
getkubectlDownloadURL,
getKubectlArch,
getExecutableExtension,
getLatestPatchVersion,
isDefaultBaseURL,
normalizeBaseURL,
secureDownload,
validateBaseURL
} from './helpers.js'
getExecutableExtension
} from './helpers'
const kubectlToolName = 'kubectl'
const stableKubectlVersion = 'v1.15.0'
const stableVersionUrl =
'https://storage.googleapis.com/kubernetes-release/release/stable.txt'
export async function run() {
let version = core.getInput('version', {required: true})
const rawBaseURL = core.getInput('downloadBaseURL', {required: false}).trim()
const downloadBaseURL = rawBaseURL || DEFAULT_KUBECTL_BASE_URL
validateBaseURL(downloadBaseURL)
const expectedChecksum = core
.getInput('checksum', {required: false})
.trim()
.toLowerCase()
const downloadAuthToken = core
.getInput('downloadAuthToken', {required: false})
.trim()
if (downloadAuthToken) {
core.setSecret(downloadAuthToken)
if (isDefaultBaseURL(downloadBaseURL)) {
throw new Error(
'`downloadAuthToken` was set but `downloadBaseURL` is the default (https://dl.k8s.io). Refusing to send a bearer token to the public Kubernetes mirror.'
)
}
if (version.toLocaleLowerCase() === 'latest') {
version = await getStableKubectlVersion()
}
if (!isDefaultBaseURL(downloadBaseURL)) {
if (!expectedChecksum) {
throw new Error(
'Refusing to download from a custom `downloadBaseURL` without a `checksum`. On self-hosted runners an unverified binary would poison the tool cache and be reused across jobs. Set the `checksum` input to a 64-char SHA-256 to enable integrity verification.'
)
}
core.notice(
`kubectl will be downloaded from a custom mirror: ${downloadBaseURL}`
)
}
if (version.trim().toLowerCase() === 'latest') {
version = await getStableKubectlVersion(
downloadBaseURL,
downloadAuthToken
)
} else {
version = await resolveKubectlVersion(
version,
downloadBaseURL,
downloadAuthToken
)
}
const cachedPath = await downloadKubectl(
version,
downloadBaseURL,
expectedChecksum,
downloadAuthToken
)
const cachedPath = await downloadKubectl(version)
core.addPath(path.dirname(cachedPath))
@@ -81,79 +31,32 @@ export async function run() {
core.setOutput('kubectl-path', cachedPath)
}
export async function getStableKubectlVersion(
baseURL: string = DEFAULT_KUBECTL_BASE_URL,
authToken: string = ''
): Promise<string> {
const url = validateBaseURL(baseURL)
const basePath = url.pathname.replace(/\/+$/, '')
url.pathname = `${basePath}/release/stable.txt`
const stableVersionUrl = url.toString()
const useSecure = !isDefaultBaseURL(baseURL)
let downloadPath = ''
try {
downloadPath = useSecure
? await secureDownload(stableVersionUrl, authToken)
: await toolCache.downloadTool(stableVersionUrl)
let version = fs.readFileSync(downloadPath, 'utf8').toString().trim()
if (!version) {
version = stableKubectlVersion
}
return version
} catch (error) {
core.debug(String(error))
if (useSecure) {
throw new Error(
`Failed to fetch stable.txt from custom downloadBaseURL "${baseURL}".`
)
}
core.warning('GetStableVersionFailed')
return stableKubectlVersion
} finally {
if (useSecure && downloadPath) {
try {
fs.unlinkSync(downloadPath)
} catch {
/* empty */
export async function getStableKubectlVersion(): Promise<string> {
return toolCache.downloadTool(stableVersionUrl).then(
(downloadPath) => {
let version = fs.readFileSync(downloadPath, 'utf8').toString().trim()
if (!version) {
version = stableKubectlVersion
}
return version
},
(error) => {
core.debug(error)
core.warning('GetStableVersionFailed')
return stableKubectlVersion
}
}
)
}
export async function downloadKubectl(
version: string,
baseURL: string = DEFAULT_KUBECTL_BASE_URL,
expectedChecksum: string = '',
authToken: string = ''
): Promise<string> {
validateBaseURL(baseURL)
if (!isDefaultBaseURL(baseURL) && !expectedChecksum) {
throw new Error(
'Refusing to download from a custom `baseURL` without a `checksum`. Pass a 64-char SHA-256 to enable integrity verification.'
)
}
const cacheKey = isDefaultBaseURL(baseURL)
? version
: `${version}-${crypto
.createHash('sha256')
.update(normalizeBaseURL(baseURL))
.digest('hex')
.slice(0, 12)}`
let cachedToolpath = toolCache.find(kubectlToolName, cacheKey)
export async function downloadKubectl(version: string): Promise<string> {
let cachedToolpath = toolCache.find(kubectlToolName, version)
let kubectlDownloadPath = ''
const arch = getKubectlArch()
if (!cachedToolpath) {
const downloadURL = getkubectlDownloadURL(version, arch, baseURL)
try {
if (isDefaultBaseURL(baseURL)) {
kubectlDownloadPath = await toolCache.downloadTool(downloadURL)
} else {
kubectlDownloadPath = await secureDownload(downloadURL, authToken)
}
kubectlDownloadPath = await toolCache.downloadTool(
getkubectlDownloadURL(version, arch)
)
} catch (exception) {
if (
exception instanceof toolCache.HTTPError &&
@@ -166,84 +69,25 @@ export async function downloadKubectl(
arch
)
)
} else {
throw new Error('DownloadKubectlFailed')
}
throw exception instanceof Error
? exception
: new Error(`DownloadKubectlFailed: ${String(exception)}`)
}
try {
cachedToolpath = await toolCache.cacheFile(
kubectlDownloadPath,
kubectlToolName + getExecutableExtension(),
kubectlToolName,
cacheKey
)
} finally {
if (!isDefaultBaseURL(baseURL) && kubectlDownloadPath) {
try {
fs.unlinkSync(kubectlDownloadPath)
} catch {
/* empty */
}
}
}
cachedToolpath = await toolCache.cacheFile(
kubectlDownloadPath,
kubectlToolName + getExecutableExtension(),
kubectlToolName,
version
)
}
const kubectlPath = path.join(
cachedToolpath,
kubectlToolName + getExecutableExtension()
)
// Re-verify on every run so cached binaries are also checked.
if (expectedChecksum) {
verifyChecksum(kubectlPath, expectedChecksum)
}
fs.chmodSync(kubectlPath, '775')
return kubectlPath
}
function verifyChecksum(filePath: string, expected: string): void {
if (!/^[a-f0-9]{64}$/.test(expected)) {
throw new Error(
`Invalid checksum input: expected a 64-character hex SHA256 string.`
)
}
const actual = crypto
.createHash('sha256')
.update(fs.readFileSync(filePath))
.digest('hex')
if (actual !== expected) {
throw new Error(
`Checksum mismatch for downloaded kubectl. Expected ${expected}, got ${actual}.`
)
}
}
export async function resolveKubectlVersion(
version: string,
baseURL: string = DEFAULT_KUBECTL_BASE_URL,
authToken: string = ''
): Promise<string> {
const cleanedVersion = version.trim()
const versionMatch = cleanedVersion.match(
/^v?(?<major>\d+)\.(?<minor>\d+)(?:\.(?<patch>\d+))?$/
)
if (!versionMatch?.groups) {
throw new Error(
`Invalid version format: "${version}". Version must be in "major.minor" or "major.minor.patch" format (e.g., "1.27" or "v1.27.15").`
)
}
const {major, minor, patch} = versionMatch.groups
if (patch) {
return cleanedVersion.startsWith('v')
? cleanedVersion
: `v${cleanedVersion}`
}
return await getLatestPatchVersion(major, minor, baseURL, authToken)
}
run().catch(core.setFailed)
+1 -1
View File
@@ -10,7 +10,7 @@ def get_latest_version():
time_to_sleep = 2
for _ in range(10):
response = requests.get(
'https://dl.k8s.io/release/stable.txt')
'https://storage.googleapis.com/kubernetes-release/release/stable.txt')
if response.status_code == 200:
break
print('Failed to obtain latest version info, retrying.')
+3 -10
View File
@@ -1,14 +1,7 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "./src",
"outDir": "./lib",
"types": ["node"],
"skipLibCheck": true,
"noEmit": true
"target": "ES6",
"module": "commonjs"
},
"include": ["src"],
"exclude": ["node_modules", "**/*.test.ts", "vitest.config.ts"]
"exclude": ["node_modules", "test"]
}
-10
View File
@@ -1,10 +0,0 @@
import {defineConfig} from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['**/*.test.ts'],
clearMocks: true
}
})