From 260fb8c6e9fb298aef06a29e3008c8174c6192e9 Mon Sep 17 00:00:00 2001 From: Brian Ojeda <9335829+sgtoj@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:15:26 -0500 Subject: [PATCH 1/2] build(deps): bump go to 1.27, go modules, and github actions - go from 1.25 to 1.27 (go.mod, CI, example image golang:1.27-alpine) - example runtime image alpine from 3.21 to 3.24 - github.com/aws/aws-sdk-go-v2 from 1.41.1 to 1.47.5 - github.com/aws/aws-sdk-go-v2/config from 1.32.7 to 1.33.13 - github.com/aws/aws-sdk-go-v2/service/ssm from 1.67.8 to 1.81.2 - github.com/chainguard-dev/clog from 1.8.0 to 1.8.1 - actions/checkout from 6.0.2 to 7.0.1 - actions/setup-go from 6.2.0 to 7.0.0 - mathieudutour/github-tag-action from 6.2.0 to 7.0.0 - ncipollo/release-action from 1.20.0 to 1.21.0 - release: skip creating a release when github-tag-action v7 produces no tag, and serialize release runs with a concurrency group Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yaml | 24 +++++----- .github/workflows/release.yaml | 11 +++-- .github/workflows/semantic-check.yaml | 2 +- examples/simple/Dockerfile | 4 +- go.mod | 34 +++++++------- go.sum | 64 +++++++++++++-------------- 6 files changed, 72 insertions(+), 67 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 967a3db..6a16851 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -16,12 +16,12 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Go - uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: '1.25' + go-version: '1.27' - name: Run go vet run: go vet ./... @@ -39,12 +39,12 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Go - uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: '1.25' + go-version: '1.27' - name: Run unit tests run: make test-unit @@ -53,12 +53,12 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Go - uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: '1.25' + go-version: '1.27' - name: Run integration tests run: make test-integration @@ -67,12 +67,12 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Go - uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: '1.25' + go-version: '1.27' - name: Build run: make build diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 96f1def..4534ea0 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -8,21 +8,26 @@ on: permissions: contents: write +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + jobs: release: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Bump Version id: tag_version - uses: mathieudutour/github-tag-action@a22cf08638b34d5badda920f9daf6e72c477b07b # v6.2.0 + uses: mathieudutour/github-tag-action@af99e60ce8132224b8e6ebab5023449fe256ed46 # v7.0.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} default_bump: minor custom_release_rules: bug:patch:Fixes,chore:patch:Chores,docs:patch:Documentation,feat:minor:Features,refactor:minor:Refactors,test:patch:Tests,ci:patch:Development,dev:patch:Development - name: Create Release - uses: ncipollo/release-action@b7eabc95ff50cbeeedec83973935c8f306dfcd0b # v1.20.0 + if: steps.tag_version.outputs.new_tag != '' + uses: ncipollo/release-action@339a81892b84b4eeb0f6e744e4574d79d0d9b8dd # v1.21.0 with: tag: ${{ steps.tag_version.outputs.new_tag }} name: ${{ steps.tag_version.outputs.new_tag }} diff --git a/.github/workflows/semantic-check.yaml b/.github/workflows/semantic-check.yaml index 4ab18b6..8a52998 100644 --- a/.github/workflows/semantic-check.yaml +++ b/.github/workflows/semantic-check.yaml @@ -16,7 +16,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6.1.1 name: Check PR for Semantic Commit Message env: diff --git a/examples/simple/Dockerfile b/examples/simple/Dockerfile index 0898fc9..f5fe24e 100644 --- a/examples/simple/Dockerfile +++ b/examples/simple/Dockerfile @@ -1,7 +1,7 @@ # syntax=docker/dockerfile:1 # ------------------------------------------------------------------ builder --- -FROM golang:1.25-alpine AS builder +FROM golang:1.27-alpine AS builder RUN apk add --no-cache git ca-certificates @@ -19,7 +19,7 @@ WORKDIR /build/examples/simple RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/app . # ------------------------------------------------------------------ runtime --- -FROM alpine:3.21 +FROM alpine:3.24 RUN apk add --no-cache ca-certificates diff --git a/go.mod b/go.mod index 6c3a35d..fc63241 100644 --- a/go.mod +++ b/go.mod @@ -1,26 +1,26 @@ module github.com/cruxstack/github-app-setup-go -go 1.25 +go 1.27 require ( - github.com/aws/aws-sdk-go-v2 v1.41.1 - github.com/aws/aws-sdk-go-v2/config v1.32.7 - github.com/aws/aws-sdk-go-v2/service/ssm v1.67.8 - github.com/chainguard-dev/clog v1.8.0 + github.com/aws/aws-sdk-go-v2 v1.47.5 + github.com/aws/aws-sdk-go-v2/config v1.33.13 + github.com/aws/aws-sdk-go-v2/service/ssm v1.81.2 + github.com/chainguard-dev/clog v1.8.1 gopkg.in/yaml.v3 v3.0.1 ) require ( - github.com/aws/aws-sdk-go-v2/credentials v1.19.7 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect - github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 // indirect - github.com/aws/smithy-go v1.24.0 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.20.13 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect + github.com/aws/smithy-go v1.28.8 // indirect ) diff --git a/go.sum b/go.sum index 17fc545..2ac7366 100644 --- a/go.sum +++ b/go.sum @@ -1,35 +1,35 @@ -github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU= -github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= -github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY= -github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY= -github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8= -github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU= -github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y= -github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M= -github.com/aws/aws-sdk-go-v2/service/ssm v1.67.8 h1:31Llf5VfrZ78YvYs7sWcS7L2m3waikzRc6q1nYenVS4= -github.com/aws/aws-sdk-go-v2/service/ssm v1.67.8/go.mod h1:/jgaDlU1UImoxTxhRNxXHvBAPqPZQ8oCjcPbbkR6kac= -github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk= -github.com/aws/aws-sdk-go-v2/service/sso v1.30.9/go.mod h1:yifAsgBxgJWn3ggx70A3urX2AN49Y5sJTD1UQFlfqBw= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLzVR3XtmC4ZDPcAI6Ftvds= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo= -github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ= -github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ= -github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= -github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= -github.com/chainguard-dev/clog v1.8.0 h1:frlTMEdg3XQR+ioQ6O9i92uigY8GTUcWKpuCFkhcCHA= -github.com/chainguard-dev/clog v1.8.0/go.mod h1:5MQOZi+Iu7fV7GcJG8ag8rCB5elEOpqRMKEASgnGVdo= +github.com/aws/aws-sdk-go-v2 v1.47.5 h1:5yA+A+BiXbDq1ZLbYwPViwhEGDMdR0MEhL8Jh2LnLS4= +github.com/aws/aws-sdk-go-v2 v1.47.5/go.mod h1:iNIkogrRvFwm+1OQIUOP2lPBtlXZboOIUWiCa+pHEMw= +github.com/aws/aws-sdk-go-v2/config v1.33.13 h1:u52x6ISQOx172tpwM0VRxhJzEsTJYpMcEYUGM2A1wrw= +github.com/aws/aws-sdk-go-v2/config v1.33.13/go.mod h1:/ixtz6XPHb42zekjQ0LqD9XjTpTysNWhIGwufY1OzI4= +github.com/aws/aws-sdk-go-v2/credentials v1.20.13 h1:j4z41OtspmQ3ftQycaDunJ26b69a9SHfaSVUPqgRv8k= +github.com/aws/aws-sdk-go-v2/credentials v1.20.13/go.mod h1:SgPA1oS3b+dlMxZb618jDmGNscpXSCaxz15igS52OlE= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 h1:iXjy2SFhGYNB1jWZBhQqq8HbhsbPF23w+/zbMvPXsTg= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5/go.mod h1:k0RUiBnyXU0AXRJ9tJmY2jQke6XUIX2PNVnWtvgaPtc= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 h1:gzIWc3DTPfPbWKrQnmL6BV6WD7NPD1htxzgdk/bQ/Z4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8/go.mod h1:vvUA5cDAZWGo4R14FZPZfXfJCmgsafOWEq78Kg0D+ug= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 h1:PWv+vG8aCLS8qd+HPdYhK7Vees90aKHWFFQ1AGYD/8E= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8/go.mod h1:xxPZEpflYHJA12366ZGyq66z9dHPCoeCIu99Jck+MPw= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 h1:WOp5De9iWdEHDPh2Kb0tBP3vGBm/dVAuRGh4a4tqduo= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8/go.mod h1:z8W8YgfhbWl62XqcTtK+CxPrE+iHGRVUOtrrbIOp7ZY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 h1:MCIR6iZaCKO4UE0hUvoWWLI6JVjppopV64JfAJaMjng= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23/go.mod h1:pphWFS+z0MmIPivj8c/6bATd1Z+Av7Ust75DPdEFsPA= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 h1:+PMpWlJYOn2tm7sm6OZ/ZLd4jStl17T7wjNapd1Rczs= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8/go.mod h1:cnG3xZLGQL4c/bt8pjdzlFtZsW7epBBuNS04a5xMjdo= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 h1:WZLC+k/CZx11kZGQDqu9mpA8yhiXGX2I//jhuJE1FDo= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.1/go.mod h1:wxAk0D2oVBSjuXEIzvcKxTZfM90zticdAbh/VD42L0Y= +github.com/aws/aws-sdk-go-v2/service/ssm v1.81.2 h1:GnK/9Xino71FUigioVvDxwa7dhXSsonIsugTSCinZD0= +github.com/aws/aws-sdk-go-v2/service/ssm v1.81.2/go.mod h1:z5Gm1inYUfvFTAz82OARi7T4iROwp0VzWpYh9a7P5+s= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 h1:4VB/dnDo7pmXSLQMszSoBzWndENuc7mzwTpD6lQn77A= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.1/go.mod h1:UGsEYgWz4Gi+46vDQ5zkFLqUgJziyOE2SXjZjgmfmHc= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 h1:w8yui2ZqdHmGwVBDGvazoIvKw/DnLENBLkYnN8q8iqo= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1/go.mod h1:gJSdIY6YUzDvqQLcMtPVZgBRHrFwzHryvpE8Igzbxps= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw= +github.com/aws/smithy-go v1.28.8 h1:aEmdAq7gVCoGCnvf1NnELlu3I6D/nhqrC321FyFiQkQ= +github.com/aws/smithy-go v1.28.8/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/chainguard-dev/clog v1.8.1 h1:Lab3GEDsVm1J9XGlpWEBuzXX7eETRmd0vN5PYoNyT+Y= +github.com/chainguard-dev/clog v1.8.1/go.mod h1:5MQOZi+Iu7fV7GcJG8ag8rCB5elEOpqRMKEASgnGVdo= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= From d584ccff67ede5b26fc8dfc8cb1af7a0569a6b57 Mon Sep 17 00:00:00 2001 From: Brian Ojeda <9335829+sgtoj@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:15:26 -0500 Subject: [PATCH 2/2] fix: harden installer, readiness gate, and credential stores - installer: reject /callback once the installer is disabled so saved credentials cannot be replaced by exchanging another app's code - installer: invoke OnCredentialsSaved only after a successful save - installer: escape org and app slug in generated URLs and trim a trailing slash from GITHUB_URL - configwait: match allowed paths on segment boundaries and never let non-canonical paths (dot segments, repeated slashes) bypass the gate; ignore empty allowed-path entries - configstore/files: reject custom field keys that escape the store directory or collide with reserved credential files - configstore/aws-ssm: create tagged parameters without overwrite and fall back to an untagged overwrite, since SSM rejects tags+overwrite - configstore/envfile: rewrite only updated keys and preserve all other lines verbatim instead of re-quoting the whole file on every save - ghappsetup/configwait: mark the runtime ready after a successful reload and log reload failures - configwait/ghappsetup/ssmresolver: always attempt at least once when MaxRetries is zero or negative instead of reporting success - ssmresolver: recognize SSM ARNs in all AWS partitions - ghappsetup: correct EnsureLoaded and Reload documentation Co-Authored-By: Claude Opus 5.5 --- configstore/aws_ssm_store.go | 43 ++++++---- configstore/aws_ssm_store_test.go | 25 +++++- configstore/local_env_store.go | 49 +++++------ configstore/local_env_store_test.go | 46 ++++++++++ configstore/local_file_store.go | 33 ++++++- configstore/local_file_store_test.go | 75 ++++++++++++++++ configwait/configwait.go | 65 +++++++++++--- configwait/configwait_test.go | 80 +++++++++++++++++ configwait/reloader.go | 4 + ghappsetup/runtime.go | 18 +++- ghappsetup/runtime_http.go | 10 ++- ghappsetup/runtime_http_test.go | 50 +++++++++++ ghappsetup/runtime_lambda.go | 22 +++-- ghappsetup/runtime_lambda_test.go | 80 +++++++++++++++++ installer/installer.go | 39 ++++++--- installer/installer_test.go | 124 +++++++++++++++++++++++++++ integration/testdata/scenarios.yaml | 38 ++++++++ ssmresolver/resolver.go | 14 +-- ssmresolver/resolver_test.go | 20 +++++ 19 files changed, 748 insertions(+), 87 deletions(-) diff --git a/configstore/aws_ssm_store.go b/configstore/aws_ssm_store.go index 127e7f3..216ee76 100644 --- a/configstore/aws_ssm_store.go +++ b/configstore/aws_ssm_store.go @@ -119,36 +119,47 @@ func (s *AWSSSMStore) Save(ctx context.Context, creds *AppCredentials) error { } // putParameter creates or updates a single SSM parameter. +// +// SSM rejects PutParameter requests that set both Tags and Overwrite, so when +// tags are configured the parameter is first created with tags (no overwrite) +// and, if it already exists, updated in place without tags. func (s *AWSSSMStore) putParameter(ctx context.Context, name, value string) error { input := &ssm.PutParameterInput{ - Name: aws.String(s.ParameterPrefix + name), - Value: aws.String(value), - Type: types.ParameterTypeSecureString, - Overwrite: aws.Bool(true), - DataType: aws.String("text"), + Name: aws.String(s.ParameterPrefix + name), + Value: aws.String(value), + Type: types.ParameterTypeSecureString, + DataType: aws.String("text"), } if s.KMSKeyID != "" { input.KeyId = aws.String(s.KMSKeyID) } - if len(s.Tags) > 0 { - var tags []types.Tag - for key, value := range s.Tags { - tags = append(tags, types.Tag{ - Key: aws.String(key), - Value: aws.String(value), - }) - } - input.Tags = tags + if len(s.Tags) == 0 { + input.Overwrite = aws.Bool(true) + _, err := s.ssmClient.PutParameter(ctx, input) + return err + } + + tags := make([]types.Tag, 0, len(s.Tags)) + for key, value := range s.Tags { + tags = append(tags, types.Tag{ + Key: aws.String(key), + Value: aws.String(value), + }) } + input.Tags = tags _, err := s.ssmClient.PutParameter(ctx, input) - if err != nil { + var alreadyExists *types.ParameterAlreadyExists + if !errors.As(err, &alreadyExists) { return err } - return nil + input.Tags = nil + input.Overwrite = aws.Bool(true) + _, err = s.ssmClient.PutParameter(ctx, input) + return err } // Status returns the current registration state by checking required SSM parameters. diff --git a/configstore/aws_ssm_store_test.go b/configstore/aws_ssm_store_test.go index 4211ed9..619130d 100644 --- a/configstore/aws_ssm_store_test.go +++ b/configstore/aws_ssm_store_test.go @@ -33,6 +33,15 @@ func (m *mockSSMClient) PutParameter(ctx context.Context, params *ssm.PutParamet if m.putErr != nil { return nil, m.putErr } + // Mirror SSM validation: tags and overwrite are mutually exclusive, and + // existing parameters are only replaced when overwrite is set. + overwrite := aws.ToBool(params.Overwrite) + if overwrite && len(params.Tags) > 0 { + return nil, fmt.Errorf("ValidationException: tags and overwrite can't be used together") + } + if _, exists := m.parameters[*params.Name]; exists && !overwrite { + return nil, &types.ParameterAlreadyExists{} + } m.parameters[*params.Name] = *params.Value return &ssm.PutParameterOutput{}, nil } @@ -221,12 +230,26 @@ func TestAWSSSMStore_Save_WithTags(t *testing.T) { t.Fatalf("Save() error = %v", err) } - // Verify tags were applied to all parameters + // Verify tags were applied to all newly created parameters for _, call := range mock.putCalls { if len(call.Tags) != 2 { t.Errorf("Parameter %q has %d tags, want 2", *call.Name, len(call.Tags)) } } + + // Saving again must update existing parameters even though tags are set. + creds.ClientSecret = "rotated" + mock.putCalls = nil + if err := store.Save(context.Background(), creds); err != nil { + t.Fatalf("second Save() error = %v", err) + } + if got := mock.parameters["/prefix/"+EnvGitHubClientSecret]; got != "rotated" { + t.Errorf("client secret = %q, want %q", got, "rotated") + } + + if err := store.DisableInstaller(context.Background()); err != nil { + t.Fatalf("DisableInstaller() error = %v", err) + } } func TestAWSSSMStore_Save_OmitsEmptyOptionalFields(t *testing.T) { diff --git a/configstore/local_env_store.go b/configstore/local_env_store.go index b94af76..a29c0b5 100644 --- a/configstore/local_env_store.go +++ b/configstore/local_env_store.go @@ -7,8 +7,10 @@ import ( "bufio" "context" "fmt" + "maps" "os" "path/filepath" + "slices" "strconv" "strings" ) @@ -32,35 +34,33 @@ func (s *LocalEnvFileStore) Save(ctx context.Context, creds *AppCredentials) err return fmt.Errorf("failed to create directory %s: %w", dir, err) } - existingValues, originalLines, err := parseEnvFile(s.FilePath) + _, originalLines, err := parseEnvFile(s.FilePath) if err != nil && !os.IsNotExist(err) { return fmt.Errorf("failed to read existing .env file: %w", err) } - if existingValues == nil { - existingValues = make(map[string]string) - } + updates := make(map[string]string) for key, value := range creds.CustomFields { if value != "" { - existingValues[key] = value + updates[key] = value } } singleLinePEM := strings.ReplaceAll(creds.PrivateKey, "\n", "\\n") - existingValues[EnvGitHubAppID] = fmt.Sprintf("%d", creds.AppID) - existingValues[EnvGitHubWebhookSecret] = creds.WebhookSecret - existingValues[EnvGitHubClientID] = creds.ClientID - existingValues[EnvGitHubClientSecret] = creds.ClientSecret - existingValues[EnvGitHubAppPrivateKey] = singleLinePEM + updates[EnvGitHubAppID] = fmt.Sprintf("%d", creds.AppID) + updates[EnvGitHubWebhookSecret] = creds.WebhookSecret + updates[EnvGitHubClientID] = creds.ClientID + updates[EnvGitHubClientSecret] = creds.ClientSecret + updates[EnvGitHubAppPrivateKey] = singleLinePEM if creds.AppSlug != "" { - existingValues[EnvGitHubAppSlug] = creds.AppSlug + updates[EnvGitHubAppSlug] = creds.AppSlug } if creds.HTMLURL != "" { - existingValues[EnvGitHubAppHTMLURL] = creds.HTMLURL + updates[EnvGitHubAppHTMLURL] = creds.HTMLURL } - if err := writeEnvFile(s.FilePath, existingValues, originalLines); err != nil { + if err := writeEnvFile(s.FilePath, updates, originalLines); err != nil { return fmt.Errorf("failed to write .env file: %w", err) } @@ -131,6 +131,9 @@ func parseEnvFile(path string) (map[string]string, []string, error) { return values, lines, nil } +// writeEnvFile rewrites only the lines whose keys appear in values and appends +// any keys not already present. All other lines are preserved verbatim so that +// quoting, inline comments, and formatting of unrelated entries are untouched. func writeEnvFile(path string, values map[string]string, originalLines []string) error { var outputLines []string writtenKeys := make(map[string]bool) @@ -159,9 +162,9 @@ func writeEnvFile(path string, values map[string]string, originalLines []string) } } - for key, value := range values { + for _, key := range slices.Sorted(maps.Keys(values)) { if !writtenKeys[key] { - outputLines = append(outputLines, formatEnvLine(key, value)) + outputLines = append(outputLines, formatEnvLine(key, values[key])) } } @@ -225,19 +228,13 @@ func (s *LocalEnvFileStore) DisableInstaller(ctx context.Context) error { return fmt.Errorf("failed to create directory %s: %w", dir, err) } - values, originalLines, err := parseEnvFile(s.FilePath) - if err != nil { - if !os.IsNotExist(err) { - return err - } - } - if values == nil { - values = make(map[string]string) + _, originalLines, err := parseEnvFile(s.FilePath) + if err != nil && !os.IsNotExist(err) { + return err } - values[EnvGitHubAppInstallerEnabled] = "false" - - if err := writeEnvFile(s.FilePath, values, originalLines); err != nil { + updates := map[string]string{EnvGitHubAppInstallerEnabled: "false"} + if err := writeEnvFile(s.FilePath, updates, originalLines); err != nil { return fmt.Errorf("failed to persist installer flag: %w", err) } diff --git a/configstore/local_env_store_test.go b/configstore/local_env_store_test.go index fb652cd..5127c5c 100644 --- a/configstore/local_env_store_test.go +++ b/configstore/local_env_store_test.go @@ -588,3 +588,49 @@ MIIEowIBAAKCAQEA0Z3VS5JJcds3xfn/ygWyF8PbnGy0AHB7MhgHW1FZ t.Error("Custom field ANOTHER_FIELD was not saved") } } + +func TestLocalEnvFileStore_PreservesUnrelatedLines(t *testing.T) { + tmpDir := t.TempDir() + envPath := filepath.Join(tmpDir, ".env") + + unrelated := []string{ + `GREETING="hello \"world\""`, + `PORT=8080 # http port`, + `HOME_REF='$HOME'`, + } + initial := strings.Join(unrelated, "\n") + "\n" + if err := os.WriteFile(envPath, []byte(initial), 0600); err != nil { + t.Fatalf("failed to write initial .env: %v", err) + } + + store := NewLocalEnvFileStore(envPath) + creds := &AppCredentials{ + AppID: 1, + ClientID: "client", + ClientSecret: "secret", + WebhookSecret: "webhook", + PrivateKey: "key", + } + + // Save repeatedly and disable the installer; unrelated lines must survive + // byte-for-byte rather than being re-quoted on every write. + for i := 0; i < 2; i++ { + if err := store.Save(context.Background(), creds); err != nil { + t.Fatalf("Save() error = %v", err) + } + } + if err := store.DisableInstaller(context.Background()); err != nil { + t.Fatalf("DisableInstaller() error = %v", err) + } + + content, err := os.ReadFile(envPath) + if err != nil { + t.Fatalf("failed to read .env: %v", err) + } + lines := strings.Split(string(content), "\n") + for i, want := range unrelated { + if lines[i] != want { + t.Errorf("line %d = %q, want %q", i+1, lines[i], want) + } + } +} diff --git a/configstore/local_file_store.go b/configstore/local_file_store.go index ca5cc8a..4d4d801 100644 --- a/configstore/local_file_store.go +++ b/configstore/local_file_store.go @@ -54,7 +54,10 @@ func (s *LocalFileStore) Save(ctx context.Context, creds *AppCredentials) error for key, value := range creds.CustomFields { if value != "" { - filename := strings.ToLower(strings.ReplaceAll(key, "_", "-")) + filename, err := customFieldFileName(key) + if err != nil { + return err + } files[filename] = struct { content string mode os.FileMode @@ -134,6 +137,34 @@ func (s *LocalFileStore) DisableInstaller(ctx context.Context) error { return nil } +// reservedFileNames are the files LocalFileStore manages itself. Custom fields +// must not overwrite them (e.g., replacing the private key or creating the +// installer-disabled marker). +var reservedFileNames = map[string]bool{ + "app-id": true, + "app-slug": true, + "app-html-url": true, + "client-id": true, + "client-secret": true, + "webhook-secret": true, + "private-key.pem": true, + "installer-disabled": true, +} + +// customFieldFileName maps a custom field key to its file name (lowercase, +// underscores replaced with dashes) and rejects keys that would escape the +// store directory or collide with a file the store manages. +func customFieldFileName(key string) (string, error) { + name := strings.ToLower(strings.ReplaceAll(key, "_", "-")) + if name == "." || !filepath.IsLocal(name) || strings.ContainsAny(name, `/\`) { + return "", fmt.Errorf("invalid custom field key %q: must map to a plain file name", key) + } + if reservedFileNames[name] { + return "", fmt.Errorf("invalid custom field key %q: conflicts with reserved file %q", key, name) + } + return name, nil +} + func readTrimmedFile(path string) (string, error) { data, err := os.ReadFile(path) if err != nil { diff --git a/configstore/local_file_store_test.go b/configstore/local_file_store_test.go index a56840a..6e52e13 100644 --- a/configstore/local_file_store_test.go +++ b/configstore/local_file_store_test.go @@ -443,3 +443,78 @@ func TestReadTrimmedFile_NotExists(t *testing.T) { t.Errorf("readTrimmedFile() error = %v, want os.IsNotExist", err) } } + +func TestLocalFileStore_Save_RejectsUnsafeCustomFieldKeys(t *testing.T) { + baseCreds := func(key string) *AppCredentials { + return &AppCredentials{ + AppID: 1, + ClientID: "client", + ClientSecret: "secret", + WebhookSecret: "webhook", + PrivateKey: "original-key", + CustomFields: map[string]string{key: "injected"}, + } + } + + tests := []struct { + name string + key string + }{ + {"parent traversal", "../../escaped"}, + {"nested traversal", "sub/../../escaped"}, + {"absolute path", "/tmp/escaped"}, + {"path separator", "sub/file"}, + {"backslash separator", `..\escaped`}, + {"dot dot", ".."}, + {"dot", "."}, + {"overwrites private key", "PRIVATE_KEY.PEM"}, + {"creates installer disabled marker", "INSTALLER_DISABLED"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + root := t.TempDir() + storeDir := filepath.Join(root, "store") + store := NewLocalFileStore(storeDir) + + if err := store.Save(context.Background(), baseCreds(tt.key)); err == nil { + t.Fatalf("Save() with custom field key %q error = nil, want error", tt.key) + } + + if _, err := os.Stat(filepath.Join(root, "escaped")); !os.IsNotExist(err) { + t.Errorf("file written outside store directory (stat err = %v)", err) + } + if _, err := os.Stat(filepath.Join(storeDir, "installer-disabled")); !os.IsNotExist(err) { + t.Errorf("installer-disabled marker created (stat err = %v)", err) + } + if _, err := os.Stat(filepath.Join(storeDir, "private-key.pem")); !os.IsNotExist(err) { + t.Errorf("credentials partially written before validation failed (stat err = %v)", err) + } + }) + } +} + +func TestLocalFileStore_Save_AllowsPlainCustomFieldKeys(t *testing.T) { + dir := t.TempDir() + store := NewLocalFileStore(dir) + creds := &AppCredentials{ + AppID: 1, + ClientID: "client", + ClientSecret: "secret", + WebhookSecret: "webhook", + PrivateKey: "key", + CustomFields: map[string]string{"CUSTOM_DOMAIN": "example.com", "build.version": "1.2.3"}, + } + if err := store.Save(context.Background(), creds); err != nil { + t.Fatalf("Save() error = %v", err) + } + for name, want := range map[string]string{"custom-domain": "example.com", "build.version": "1.2.3"} { + got, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + if string(got) != want { + t.Errorf("%s = %q, want %q", name, got, want) + } + } +} diff --git a/configwait/configwait.go b/configwait/configwait.go index cb5e6ab..ccbbcf4 100644 --- a/configwait/configwait.go +++ b/configwait/configwait.go @@ -10,6 +10,7 @@ import ( "encoding/json" "net/http" "os" + "path" "strconv" "strings" "sync" @@ -60,17 +61,19 @@ func NewConfigFromEnv() Config { // LoadFunc attempts to load configuration; returns nil on success. type LoadFunc func(ctx context.Context) error -// Wait blocks until load succeeds or max retries is reached. +// Wait blocks until load succeeds or max retries is reached. Load is always +// attempted at least once, even if MaxRetries is zero or negative. func Wait(ctx context.Context, cfg Config, load LoadFunc) error { log := clog.FromContext(ctx) var lastErr error + maxAttempts := max(cfg.MaxRetries, 1) - for attempt := 1; attempt <= cfg.MaxRetries; attempt++ { + for attempt := 1; attempt <= maxAttempts; attempt++ { if err := load(ctx); err != nil { lastErr = err - log.Warnf("[configwait] attempt %d/%d failed: %v", attempt, cfg.MaxRetries, err) + log.Warnf("[configwait] attempt %d/%d failed: %v", attempt, maxAttempts, err) - if attempt < cfg.MaxRetries { + if attempt < maxAttempts { select { case <-ctx.Done(): return ctx.Err() @@ -101,12 +104,33 @@ type ReadyGate struct { } // NewReadyGate creates a ReadyGate wrapping the given handler. -// The allowedPaths are path prefixes always allowed through (e.g., "/setup"). +// +// The allowedPaths are always allowed through, even before the gate is ready. +// Each entry matches the path itself and anything beneath it on a path-segment +// boundary: "/setup" allows "/setup", "/setup/", and "/setup/disable", but not +// "/setupadmin". The entry "/" matches only the root path. Requests whose path +// is not canonical (dot segments, repeated slashes) never bypass the gate, so +// a path such as "/setup/../webhook" cannot reach a gated handler early. +// // The inner handler can be nil initially; call SetHandler() once ready. func NewReadyGate(inner http.Handler, allowedPaths []string) *ReadyGate { + normalized := make([]string, 0, len(allowedPaths)) + for _, p := range allowedPaths { + if p == "" { + continue + } + if p != "/" { + p = strings.TrimRight(p, "/") + if p == "" { + p = "/" + } + } + normalized = append(normalized, p) + } + rg := &ReadyGate{ inner: inner, - allowedPaths: allowedPaths, + allowedPaths: normalized, handlerReady: make(chan struct{}), } if inner != nil { @@ -162,22 +186,43 @@ func (rg *ReadyGate) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(w, r) } -// isAllowedPath checks if the path matches any allowed path prefix. -func (rg *ReadyGate) isAllowedPath(path string) bool { +// isAllowedPath reports whether a request path may bypass the gate. Only +// canonical paths qualify: otherwise the inner router could resolve the path +// differently than this check does (e.g., "/setup/../webhook"). +func (rg *ReadyGate) isAllowedPath(p string) bool { + if p == "" || p != cleanPath(p) { + return false + } for _, allowed := range rg.allowedPaths { if allowed == "/" { - if path == "/" { + if p == "/" { return true } continue } - if strings.HasPrefix(path, allowed) { + if p == allowed || strings.HasPrefix(p, allowed+"/") { return true } } return false } +// cleanPath returns the canonical form of p, mirroring net/http.ServeMux: +// it resolves dot segments and repeated slashes and keeps a trailing slash. +func cleanPath(p string) string { + if p == "" { + return "/" + } + if p[0] != '/' { + p = "/" + p + } + np := path.Clean(p) + if p[len(p)-1] == '/' && np != "/" { + np += "/" + } + return np +} + // getHandler returns the current handler. func (rg *ReadyGate) getHandler() http.Handler { h := rg.handler.Load() diff --git a/configwait/configwait_test.go b/configwait/configwait_test.go index af39bb0..c8bf742 100644 --- a/configwait/configwait_test.go +++ b/configwait/configwait_test.go @@ -164,10 +164,24 @@ func TestReadyGate_AllowedPathsPassThrough(t *testing.T) { wantBody string }{ {"/setup", http.StatusOK, "setup page"}, + {"/setup/", http.StatusOK, "setup page"}, {"/setup/callback", http.StatusOK, "setup page"}, {"/healthz", http.StatusOK, "setup page"}, {"/other", http.StatusServiceUnavailable, ""}, {"/webhook", http.StatusServiceUnavailable, ""}, + + // Allowed paths match on segment boundaries, not raw string prefixes. + {"/setupadmin", http.StatusServiceUnavailable, ""}, + {"/healthzz", http.StatusServiceUnavailable, ""}, + + // Non-canonical paths never bypass the gate, in either direction. + {"/setup/../webhook", http.StatusServiceUnavailable, ""}, + {"/setup/%2e%2e/webhook", http.StatusServiceUnavailable, ""}, + {"/setup/%2E%2E%2Fwebhook", http.StatusServiceUnavailable, ""}, + {"/webhook/../setup", http.StatusServiceUnavailable, ""}, + {"/setup/./callback", http.StatusServiceUnavailable, ""}, + {"//setup", http.StatusServiceUnavailable, ""}, + {"/setup//callback", http.StatusServiceUnavailable, ""}, } for _, tt := range tests { @@ -189,6 +203,37 @@ func TestReadyGate_AllowedPathsPassThrough(t *testing.T) { } } +func TestReadyGate_AllowedPathNormalization(t *testing.T) { + inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + tests := []struct { + name string + allowed []string + path string + want int + }{ + {"trailing slash entry allows bare path", []string{"/setup/"}, "/setup", http.StatusOK}, + {"trailing slash entry allows subtree", []string{"/setup/"}, "/setup/disable", http.StatusOK}, + {"trailing slash entry rejects sibling", []string{"/setup/"}, "/setupadmin", http.StatusServiceUnavailable}, + {"root entry allows only root", []string{"/"}, "/", http.StatusOK}, + {"root entry does not allow subpaths", []string{"/"}, "/webhook", http.StatusServiceUnavailable}, + {"empty entry is ignored", []string{""}, "/webhook", http.StatusServiceUnavailable}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gate := NewReadyGate(inner, tt.allowed) + rec := httptest.NewRecorder() + gate.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, tt.path, nil)) + if rec.Code != tt.want { + t.Errorf("path %q with allowed %q: status = %d, want %d", tt.path, tt.allowed, rec.Code, tt.want) + } + }) + } +} + func TestReadyGate_IsReady(t *testing.T) { gate := NewReadyGate(nil, nil) @@ -358,3 +403,38 @@ func TestReloader_ContextCancellation(t *testing.T) { t.Error("Reloader did not stop after context cancellation") } } + +func TestWait_NonPositiveMaxRetriesStillLoads(t *testing.T) { + for _, maxRetries := range []int{0, -1} { + var calls atomic.Int32 + wantErr := errors.New("not configured") + err := Wait(context.Background(), Config{MaxRetries: maxRetries}, func(ctx context.Context) error { + calls.Add(1) + return wantErr + }) + if !errors.Is(err, wantErr) { + t.Errorf("MaxRetries=%d: Wait() error = %v, want %v", maxRetries, err, wantErr) + } + if got := calls.Load(); got != 1 { + t.Errorf("MaxRetries=%d: load called %d times, want 1", maxRetries, got) + } + } +} + +func TestReloader_SuccessMarksGateReady(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + gate := NewReadyGate(nil, nil) + reloader := NewReloader(ctx, gate, func(ctx context.Context) error { return nil }) + reloader.Start() + reloader.Trigger() + + deadline := time.Now().Add(time.Second) + for !gate.IsReady() && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if !gate.IsReady() { + t.Error("gate.IsReady() = false after successful reload, want true") + } +} diff --git a/configwait/reloader.go b/configwait/reloader.go index 68f86b8..a71c5f4 100644 --- a/configwait/reloader.go +++ b/configwait/reloader.go @@ -104,5 +104,9 @@ func (r *Reloader) doReload() { return } + if r.gate != nil { + r.gate.SetReady() + } + log.Infof("[reloader] configuration reloaded successfully") } diff --git a/ghappsetup/runtime.go b/ghappsetup/runtime.go index 79e8bdb..562394d 100644 --- a/ghappsetup/runtime.go +++ b/ghappsetup/runtime.go @@ -58,6 +58,11 @@ type Config struct { // AllowedPaths specifies HTTP paths that should be served even before // configuration is loaded. This is typically used for health checks and // installer endpoints. Only applicable in HTTP environments. + // + // Each entry matches the path itself and anything beneath it on a + // path-segment boundary ("/setup" allows "/setup/disable" but not + // "/setupadmin"); "/" matches only the root path. Non-canonical request + // paths (dot segments, repeated slashes) are never allowed early. AllowedPaths []string // MaxRetries is the maximum number of times to retry loading configuration. @@ -166,11 +171,16 @@ func (r *Runtime) setReady(ready bool) { } } -// Reload triggers a configuration reload by calling LoadFunc. -// This is safe to call from multiple goroutines; concurrent reload -// requests are coalesced. +// Reload triggers a configuration reload by calling LoadFunc. On success the +// runtime is marked ready, so a reload after a failed or still-pending Start +// (e.g., once the installer has saved credentials) opens the ReadyGate. +// Use ReloadCallback for asynchronous, coalesced reload requests. func (r *Runtime) Reload(ctx context.Context) error { - return r.config.LoadFunc(ctx) + if err := r.config.LoadFunc(ctx); err != nil { + return err + } + r.setReady(true) + return nil } // ReloadCallback returns a function suitable for use as installer.Config.OnReloadNeeded. diff --git a/ghappsetup/runtime_http.go b/ghappsetup/runtime_http.go index e0a4609..04f751c 100644 --- a/ghappsetup/runtime_http.go +++ b/ghappsetup/runtime_http.go @@ -10,6 +10,8 @@ import ( "os/signal" "syscall" + "github.com/chainguard-dev/clog" + "github.com/cruxstack/github-app-setup-go/configwait" ) @@ -93,10 +95,10 @@ func (r *Runtime) ListenForReloads(ctx context.Context) <-chan struct{} { // doReload performs the actual reload operation. func (r *Runtime) doReload(ctx context.Context) { - if err := r.config.LoadFunc(ctx); err != nil { - // Log error but don't crash - reload failures are non-fatal - // The application continues running with the previous configuration - return + if err := r.Reload(ctx); err != nil { + // Reload failures are non-fatal; the application continues running + // with the previous configuration. + clog.FromContext(ctx).Errorf("[ghappsetup] reload failed: %v", err) } } diff --git a/ghappsetup/runtime_http_test.go b/ghappsetup/runtime_http_test.go index 65f36b6..44eada6 100644 --- a/ghappsetup/runtime_http_test.go +++ b/ghappsetup/runtime_http_test.go @@ -281,3 +281,53 @@ func (m *httpMockStore) Status(ctx context.Context) (*configstore.InstallerStatu func (m *httpMockStore) DisableInstaller(ctx context.Context) error { return nil } + +func TestRuntime_ListenForReloads_MarksReadyAfterFailedStart(t *testing.T) { + os.Unsetenv("AWS_LAMBDA_FUNCTION_NAME") + + var configured atomic.Bool + runtime, err := NewRuntime(Config{ + Store: &mockStore{}, + LoadFunc: func(ctx context.Context) error { + if !configured.Load() { + return errors.New("not configured") + } + return nil + }, + MaxRetries: 1, + RetryInterval: time.Millisecond, + }) + if err != nil { + t.Fatalf("NewRuntime() error = %v", err) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + if err := runtime.Start(ctx); err == nil { + t.Fatal("Start() error = nil, want error") + } + handler := runtime.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + + runtime.ListenForReloads(ctx) + + // Simulate the installer saving credentials and requesting a reload. + configured.Store(true) + runtime.ReloadCallback()() + + deadline := time.Now().Add(time.Second) + for !runtime.IsReady() && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if !runtime.IsReady() { + t.Fatal("IsReady() = false after successful reload, want true") + } + + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/webhook", nil)) + if rec.Code != http.StatusOK { + t.Errorf("gated request status = %d, want %d", rec.Code, http.StatusOK) + } +} diff --git a/ghappsetup/runtime_lambda.go b/ghappsetup/runtime_lambda.go index b9af7c1..ea7ca9e 100644 --- a/ghappsetup/runtime_lambda.go +++ b/ghappsetup/runtime_lambda.go @@ -39,12 +39,14 @@ func (r *Runtime) getLambdaState() *lambdaState { } // EnsureLoaded ensures that configuration has been loaded, performing -// lazy initialization if needed. This method is idempotent and safe to -// call from multiple goroutines. +// lazy initialization if needed. It is safe to call from multiple goroutines. // -// On first call, it attempts to load configuration with retry logic. -// Subsequent calls return immediately if already loaded, or return the -// last error if loading failed. +// The first call loads configuration using the configured retry policy. +// Once a load succeeds, subsequent calls return nil immediately. While a load +// is in progress, concurrent callers wait for it and receive its result. If a +// load fails, its error is returned and the next call starts a fresh load +// (again with the full retry policy), so a later invocation can succeed once +// configuration becomes available, e.g. after the installer saves credentials. // // This method is intended for Lambda environments where configuration // loading happens lazily on first request. For HTTP servers, use Start instead. @@ -119,17 +121,19 @@ func (r *Runtime) waitForLoad(ctx context.Context, state *lambdaState) error { } } -// loadWithRetry attempts to load configuration with retry logic. +// loadWithRetry attempts to load configuration with retry logic. LoadFunc is +// always attempted at least once. func (r *Runtime) loadWithRetry(ctx context.Context) error { log := clog.FromContext(ctx) var lastErr error + maxAttempts := max(r.config.MaxRetries, 1) - for attempt := 1; attempt <= r.config.MaxRetries; attempt++ { + for attempt := 1; attempt <= maxAttempts; attempt++ { if err := r.config.LoadFunc(ctx); err != nil { lastErr = err - log.Warnf("[ghappsetup] attempt %d/%d failed: %v", attempt, r.config.MaxRetries, err) + log.Warnf("[ghappsetup] attempt %d/%d failed: %v", attempt, maxAttempts, err) - if attempt < r.config.MaxRetries { + if attempt < maxAttempts { select { case <-ctx.Done(): return ctx.Err() diff --git a/ghappsetup/runtime_lambda_test.go b/ghappsetup/runtime_lambda_test.go index 7b1e51c..b6a3128 100644 --- a/ghappsetup/runtime_lambda_test.go +++ b/ghappsetup/runtime_lambda_test.go @@ -277,3 +277,83 @@ func (m *lambdaMockStore) Status(ctx context.Context) (*configstore.InstallerSta func (m *lambdaMockStore) DisableInstaller(ctx context.Context) error { return nil } + +func TestRuntime_EnsureLoaded_NegativeMaxRetriesStillLoads(t *testing.T) { + os.Setenv("AWS_LAMBDA_FUNCTION_NAME", "test-function") + defer os.Unsetenv("AWS_LAMBDA_FUNCTION_NAME") + + var calls atomic.Int32 + wantErr := errors.New("not configured") + runtime, err := NewRuntime(Config{ + Store: &lambdaMockStore{}, + LoadFunc: func(ctx context.Context) error { + calls.Add(1) + return wantErr + }, + MaxRetries: -1, + }) + if err != nil { + t.Fatalf("NewRuntime() error = %v", err) + } + + if err := runtime.EnsureLoaded(context.Background()); !errors.Is(err, wantErr) { + t.Errorf("EnsureLoaded() error = %v, want %v", err, wantErr) + } + if got := calls.Load(); got != 1 { + t.Errorf("LoadFunc called %d times, want 1", got) + } + if runtime.IsReady() { + t.Error("IsReady() = true without a successful load") + } +} + +func TestRuntime_EnsureLoaded_RetriesAfterFailure(t *testing.T) { + os.Setenv("AWS_LAMBDA_FUNCTION_NAME", "test-function") + defer os.Unsetenv("AWS_LAMBDA_FUNCTION_NAME") + + var calls atomic.Int32 + var configured atomic.Bool + runtime, err := NewRuntime(Config{ + Store: &lambdaMockStore{}, + LoadFunc: func(ctx context.Context) error { + calls.Add(1) + if !configured.Load() { + return errors.New("not configured") + } + return nil + }, + MaxRetries: 2, + RetryInterval: time.Millisecond, + }) + if err != nil { + t.Fatalf("NewRuntime() error = %v", err) + } + + ctx := context.Background() + if err := runtime.EnsureLoaded(ctx); err == nil { + t.Fatal("first EnsureLoaded() error = nil, want error") + } + if got := calls.Load(); got != 2 { + t.Fatalf("LoadFunc called %d times after first failure, want 2", got) + } + + // A failed load is not cached: the next call runs the full retry policy again. + configured.Store(true) + if err := runtime.EnsureLoaded(ctx); err != nil { + t.Fatalf("second EnsureLoaded() error = %v, want nil", err) + } + if got := calls.Load(); got != 3 { + t.Errorf("LoadFunc called %d times total, want 3", got) + } + if !runtime.IsReady() { + t.Error("IsReady() = false after successful reload") + } + + // Once loaded, further calls return immediately without loading again. + if err := runtime.EnsureLoaded(ctx); err != nil { + t.Fatalf("third EnsureLoaded() error = %v", err) + } + if got := calls.Load(); got != 3 { + t.Errorf("LoadFunc called %d times after success, want 3", got) + } +} diff --git a/installer/installer.go b/installer/installer.go index 923d5f4..021524a 100644 --- a/installer/installer.go +++ b/installer/installer.go @@ -14,6 +14,7 @@ import ( "html/template" "io" "net/http" + "net/url" "os" "strings" "time" @@ -95,6 +96,7 @@ func New(cfg Config) (*Handler, error) { if cfg.Store == nil { return nil, fmt.Errorf("store is required") } + cfg.GitHubURL = strings.TrimRight(cfg.GitHubURL, "/") if cfg.GitHubURL == "" { cfg.GitHubURL = "https://github.com" } @@ -195,7 +197,7 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) { var formActionURL string if h.config.GitHubOrg != "" { formActionURL = fmt.Sprintf("%s/organizations/%s/settings/apps/new", - h.config.GitHubURL, h.config.GitHubOrg) + h.config.GitHubURL, url.PathEscape(h.config.GitHubOrg)) } else { formActionURL = fmt.Sprintf("%s/settings/apps/new", h.config.GitHubURL) } @@ -245,6 +247,19 @@ func (h *Handler) handleCallback(w http.ResponseWriter, r *http.Request) { return } + // Once the installer is disabled, refuse to exchange new codes so the + // saved credentials cannot be replaced by anyone who can reach /callback. + status, err := h.config.Store.Status(ctx) + if err != nil { + log.Errorf("[installer] failed to read installer status: %v", err) + http.Error(w, "Failed to load installer status", http.StatusInternalServerError) + return + } + if status != nil && status.InstallerDisabled { + http.NotFound(w, r) + return + } + var customDomain string if cookie, err := r.Cookie("custom_domain"); err == nil { customDomain = cookie.Value @@ -271,12 +286,6 @@ func (h *Handler) handleCallback(w http.ResponseWriter, r *http.Request) { creds.CustomFields["CUSTOM_DOMAIN"] = customDomain } - if h.config.OnCredentialsSaved != nil { - if err := h.config.OnCredentialsSaved(ctx, creds); err != nil { - log.Errorf("[installer] OnCredentialsSaved callback failed: %v", err) - } - } - if err := h.config.Store.Save(ctx, creds); err != nil { log.Errorf("[installer] failed to save credentials: %v", err) http.Error(w, "Failed to save credentials", http.StatusInternalServerError) @@ -285,6 +294,12 @@ func (h *Handler) handleCallback(w http.ResponseWriter, r *http.Request) { log.Infof("[installer] successfully created github app: slug=%s app_id=%d", creds.AppSlug, creds.AppID) + if h.config.OnCredentialsSaved != nil { + if err := h.config.OnCredentialsSaved(ctx, creds); err != nil { + log.Errorf("[installer] OnCredentialsSaved callback failed: %v", err) + } + } + if h.config.OnReloadNeeded != nil { log.Infof("[installer] triggering configuration reload") h.config.OnReloadNeeded() @@ -296,13 +311,15 @@ func (h *Handler) handleCallback(w http.ResponseWriter, r *http.Request) { // exchangeCode exchanges the temporary code for app credentials. func (h *Handler) exchangeCode(ctx context.Context, code string) (*configstore.AppCredentials, error) { - url := fmt.Sprintf("%s/api/v3/app-manifests/%s/conversions", h.config.GitHubURL, code) + // code is validated by isValidOAuthCode (alphanumeric only), so it cannot + // inject path segments; escape anyway as defense in depth. + endpoint := fmt.Sprintf("%s/api/v3/app-manifests/%s/conversions", h.config.GitHubURL, url.PathEscape(code)) if h.config.GitHubURL == "https://github.com" { - url = fmt.Sprintf("https://api.github.com/app-manifests/%s/conversions", code) + endpoint = fmt.Sprintf("https://api.github.com/app-manifests/%s/conversions", url.PathEscape(code)) } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } @@ -393,7 +410,7 @@ func (h *Handler) installURLFor(slug, htmlURL string) string { if githubURL == "" { githubURL = "https://github.com" } - return fmt.Sprintf("%s/apps/%s/installations/new", githubURL, slug) + return fmt.Sprintf("%s/apps/%s/installations/new", githubURL, url.PathEscape(slug)) } if htmlURL != "" { trimmed := strings.TrimRight(htmlURL, "/") diff --git a/installer/installer_test.go b/installer/installer_test.go index c2c7d43..beb75ba 100644 --- a/installer/installer_test.go +++ b/installer/installer_test.go @@ -5,8 +5,10 @@ package installer import ( "context" + "errors" "net/http" "net/http/httptest" + "strings" "testing" "github.com/cruxstack/github-app-setup-go/configstore" @@ -180,6 +182,33 @@ func TestInstallURLFor(t *testing.T) { } } +func TestInstallURLFor_EscapesSlug(t *testing.T) { + h := &Handler{config: Config{GitHubURL: "https://github.com"}} + got := h.installURLFor("../../evil", "") + want := "https://github.com/apps/..%2F..%2Fevil/installations/new" + if got != want { + t.Errorf("installURLFor() = %q, want %q", got, want) + } +} + +func TestHandler_handleIndex_EscapesOrgInFormAction(t *testing.T) { + h, _ := New(Config{Store: &mockStore{}, GitHubOrg: "../../evil"}) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/setup", nil)) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) + } + body := rec.Body.String() + if strings.Contains(body, "/organizations/../../evil/") { + t.Error("form action contains unescaped org path traversal") + } + if !strings.Contains(body, "/organizations/..%2f..%2fevil/settings/apps/new") && + !strings.Contains(body, "/organizations/..%2F..%2Fevil/settings/apps/new") { + t.Error("form action does not contain escaped org") + } +} + func TestManifestClone(t *testing.T) { t.Run("nil manifest returns nil", func(t *testing.T) { var m *Manifest = nil @@ -319,6 +348,14 @@ func TestNew_Validation(t *testing.T) { } }) + t.Run("trailing slash is trimmed from GitHubURL", func(t *testing.T) { + store := &mockStore{} + h, _ := New(Config{Store: store, GitHubURL: "https://ghe.example.com/"}) + if h.config.GitHubURL != "https://ghe.example.com" { + t.Errorf("GitHubURL = %q, want %q", h.config.GitHubURL, "https://ghe.example.com") + } + }) + t.Run("empty AppDisplayName defaults", func(t *testing.T) { store := &mockStore{} h, _ := New(Config{Store: store, AppDisplayName: ""}) @@ -474,6 +511,93 @@ func TestHandler_handleCallback_InvalidCode(t *testing.T) { } } +func TestHandler_handleCallback_OnCredentialsSaved(t *testing.T) { + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id": 1, "slug": "app", "pem": "key"}`)) + })) + defer github.Close() + + tests := []struct { + name string + saveErr error + wantStatus int + wantCallback bool + }{ + {"called after successful save", nil, http.StatusOK, true}, + {"not called when save fails", errors.New("boom"), http.StatusInternalServerError, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + saved := false + called := false + store := &mockStore{ + saveFunc: func(ctx context.Context, creds *configstore.AppCredentials) error { + if tt.saveErr == nil { + saved = true + } + return tt.saveErr + }, + } + h, _ := New(Config{ + Store: store, + GitHubURL: github.URL, + OnCredentialsSaved: func(ctx context.Context, creds *configstore.AppCredentials) error { + called = true + if !saved { + t.Error("OnCredentialsSaved called before credentials were saved") + } + return nil + }, + }) + + req := httptest.NewRequest(http.MethodGet, "/callback?code=validcode1234567890", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + if rec.Code != tt.wantStatus { + t.Errorf("status = %d, want %d", rec.Code, tt.wantStatus) + } + if called != tt.wantCallback { + t.Errorf("OnCredentialsSaved called = %v, want %v", called, tt.wantCallback) + } + }) + } +} + +func TestHandler_handleCallback_DisabledInstaller(t *testing.T) { + exchanged := false + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + exchanged = true + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id": 1}`)) + })) + defer github.Close() + + store := &mockStore{ + statusFunc: func(ctx context.Context) (*configstore.InstallerStatus, error) { + return &configstore.InstallerStatus{Registered: true, InstallerDisabled: true}, nil + }, + saveFunc: func(ctx context.Context, creds *configstore.AppCredentials) error { + t.Error("Save called while installer is disabled") + return nil + }, + } + h, _ := New(Config{Store: store, GitHubURL: github.URL}) + + req := httptest.NewRequest(http.MethodGet, "/callback?code=validcode1234567890", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + if rec.Code != http.StatusNotFound { + t.Errorf("status = %d, want %d", rec.Code, http.StatusNotFound) + } + if exchanged { + t.Error("code was exchanged with GitHub while installer is disabled") + } +} + // mockStore implements configstore.Store for testing type mockStore struct { saveFunc func(ctx context.Context, creds *configstore.AppCredentials) error diff --git a/integration/testdata/scenarios.yaml b/integration/testdata/scenarios.yaml index f34f51e..2061f9f 100644 --- a/integration/testdata/scenarios.yaml +++ b/integration/testdata/scenarios.yaml @@ -176,6 +176,44 @@ registered: true installer_disabled: true +- name: "disabled_installer_rejects_callback" + description: "GET /callback cannot replace credentials once the installer is disabled" + preset_credentials: + app_id: 12345 + app_slug: "my-app" + client_id: "Iv1.test" + client_secret: "test_secret" + webhook_secret: "test_webhook" + html_url: "https://github.com/apps/my-app" + mock_responses: + - method: POST + path: /api/v3/app-manifests/othercode1234567890/conversions + status: 201 + body: | + { + "id": 66666, + "slug": "other-app", + "client_id": "Iv1.other", + "client_secret": "other_secret", + "webhook_secret": "other_webhook", + "pem": "other-key", + "html_url": "https://github.com/apps/other-app" + } + steps: + - action: request + method: POST + path: /setup/disable + expect_status: 303 + - action: request + method: GET + path: /callback?code=othercode1234567890 + expect_status: 404 + expected_store: + registered: true + installer_disabled: true + app_id: 12345 + app_slug: "my-app" + - name: "disable_without_registration_fails" description: "POST /setup/disable fails when not registered" steps: diff --git a/ssmresolver/resolver.go b/ssmresolver/resolver.go index 461a592..ef2b9bf 100644 --- a/ssmresolver/resolver.go +++ b/ssmresolver/resolver.go @@ -28,7 +28,9 @@ const ( DefaultRetryInterval = 1 * time.Second ) -var ssmARNPattern = regexp.MustCompile(`^arn:aws:ssm:[^:]+:[^:]+:parameter/(.+)$`) +// ssmARNPattern matches SSM parameter ARNs in any AWS partition (aws, aws-cn, +// aws-us-gov, aws-iso, ...). +var ssmARNPattern = regexp.MustCompile(`^arn:aws(?:-[a-z]+)*:ssm:[^:]+:[^:]+:parameter/(.+)$`) // Client defines the interface for SSM operations. type Client interface { @@ -160,12 +162,14 @@ func NewRetryConfigFromEnv() RetryConfig { return cfg } -// ResolveEnvironmentWithRetry resolves all environment variables with retry logic. +// ResolveEnvironmentWithRetry resolves all environment variables with retry +// logic. Resolution is always attempted at least once. func ResolveEnvironmentWithRetry(ctx context.Context, cfg RetryConfig) error { log := clog.FromContext(ctx) var lastErr error + maxAttempts := max(cfg.MaxRetries, 1) - for attempt := 1; attempt <= cfg.MaxRetries; attempt++ { + for attempt := 1; attempt <= maxAttempts; attempt++ { err := ResolveEnvironmentWithDefaults(ctx) if err == nil { if attempt > 1 { @@ -175,9 +179,9 @@ func ResolveEnvironmentWithRetry(ctx context.Context, cfg RetryConfig) error { } lastErr = err - log.Warnf("[ssmresolver] attempt %d/%d failed: %v", attempt, cfg.MaxRetries, err) + log.Warnf("[ssmresolver] attempt %d/%d failed: %v", attempt, maxAttempts, err) - if attempt < cfg.MaxRetries { + if attempt < maxAttempts { select { case <-ctx.Done(): return ctx.Err() diff --git a/ssmresolver/resolver_test.go b/ssmresolver/resolver_test.go index 112ce34..e069207 100644 --- a/ssmresolver/resolver_test.go +++ b/ssmresolver/resolver_test.go @@ -34,8 +34,28 @@ func TestIsSSMARN(t *testing.T) { value: "arn:aws:ssm:eu-west-1:999888777666:parameter//app/secret", want: true, }, + { + name: "valid GovCloud partition ARN", + value: "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/my-param", + want: true, + }, + { + name: "valid China partition ARN", + value: "arn:aws-cn:ssm:cn-north-1:123456789012:parameter/my-param", + want: true, + }, + { + name: "valid ISO-B partition ARN", + value: "arn:aws-iso-b:ssm:us-isob-east-1:123456789012:parameter/my-param", + want: true, + }, // Invalid ARNs + { + name: "unknown partition prefix", + value: "arn:awsx:ssm:us-east-1:123456789012:parameter/my-param", + want: false, + }, { name: "empty string", value: "",