From 7803d8cbf3b6d84f5c72a50f50383038724c2b0d Mon Sep 17 00:00:00 2001 From: Hironori Takahashi Date: Wed, 2 Dec 2026 19:28:58 +0900 Subject: [PATCH 1/3] feat: add configure-environments.sh for environment protection --- .templatesyncignore | 1 + scripts/configure-environments.sh | 281 ++++++++++++++++++++++++++++++ 2 files changed, 282 insertions(+) create mode 100755 scripts/configure-environments.sh diff --git a/.templatesyncignore b/.templatesyncignore index 38afdaf..e3de019 100644 --- a/.templatesyncignore +++ b/.templatesyncignore @@ -37,6 +37,7 @@ :!scripts/init-sandbox.sh :!scripts/sandbox-push.sh :!scripts/check-webapp-policy.sh +:!scripts/configure-environments.sh :!scripts/set-properties.sh :!scripts/gcp-get-secret.sh :!scripts/fetch-clasp-credentials.sh diff --git a/scripts/configure-environments.sh b/scripts/configure-environments.sh new file mode 100755 index 0000000..39d4eb8 --- /dev/null +++ b/scripts/configure-environments.sh @@ -0,0 +1,281 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Apps Script Fleet — Deployment Environment Protection +# +# Configures protection for the 'development' and 'production' deployment +# environments. Environment protection is a per-repo setting (org rulesets +# cannot apply it), so this script makes it repeatable: run it from init.sh +# at project creation, or standalone on an existing repo. +# +# Idempotent: PUT replaces the environment's protection settings. +# Without options it only ensures the two environments exist (current init.sh +# behavior). +# +# Prerequisites: +# - GitHub: gh CLI authenticated with repo admin rights +# - GitLab: glab CLI authenticated (Premium+ for protected environments) +# +# Usage: +# ./scripts/configure-environments.sh [options] +# +# Options: +# --production-reviewers [,...] +# Required reviewers for the production environment. +# --development-reviewers [,...] +# Required reviewers for the development environment. +# --prevent-self-review +# The user who triggered the deployment cannot approve it +# (applies to environments that have reviewers). +# --branch-policy +# Restrict both environments' deployment branch policy to 'main' only. +# Matches the fleet's cd.yml: workflow_run executes on the default +# branch, so BOTH environments evaluate against 'main' (GitHub). +# +# Notes: +# - Requires private/internal repos to be on a plan that supports protected +# environments (GitHub Team/Enterprise, GitLab Premium). On GitLab, +# unsupported plans produce a warning and the step is skipped. + +PRODUCTION_REVIEWERS="" +DEVELOPMENT_REVIEWERS="" +PREVENT_SELF_REVIEW="false" +BRANCH_POLICY="false" + +while [[ $# -gt 0 ]]; do + case $1 in + --production-reviewers) + PRODUCTION_REVIEWERS="$2" + shift 2 + ;; + --development-reviewers) + DEVELOPMENT_REVIEWERS="$2" + shift 2 + ;; + --prevent-self-review) + PREVENT_SELF_REVIEW="true" + shift + ;; + --branch-policy) + BRANCH_POLICY="true" + shift + ;; + *) + echo "Unknown option: $1" >&2 + exit 1 + ;; + esac +done + +die() { + echo "Error: $*" >&2 + exit 1 +} + +require_cmd() { + command -v "$1" >/dev/null 2>&1 || die "$1 is required but not installed." +} + +extract_host() { + local url="$1" + if [[ "$url" == git@* ]]; then + local without_prefix="${url#git@}" + echo "${without_prefix%%:*}" + else + local without_scheme="${url#*://}" + echo "${without_scheme%%/*}" + fi +} + +extract_path() { + local url="$1" + local path + if [[ "$url" == git@* ]]; then + path="${url#*:}" + else + local without_scheme="${url#*://}" + path="${without_scheme#*/}" + fi + echo "${path%.git}" +} + +REMOTE_URL=$(git remote get-url origin 2>/dev/null) || die "No git remote 'origin' found." +REMOTE_HOST=$(extract_host "$REMOTE_URL") + +detect_platform() { + local host="$REMOTE_HOST" + if command -v gh >/dev/null 2>&1 && gh auth status --hostname "$host" >/dev/null 2>&1; then + echo "github" + elif command -v glab >/dev/null 2>&1 && glab auth status --hostname "$host" >/dev/null 2>&1; then + echo "gitlab" + else + die "No authenticated CLI found for ${host}. Run 'gh auth login' or 'glab auth login --hostname ${host}'." + fi +} + +# --------------------------------------------------------------------------- +# GitHub +# --------------------------------------------------------------------------- + +# Resolve a reviewer entry (org team slug, or username) to "Type:id". +gh_resolve_reviewer() { + local owner="$1" entry="$2" + local id + if id=$(gh api "orgs/${owner}/teams/${entry}" --jq .id 2>/dev/null); then + echo "Team:${id}" + elif id=$(gh api "users/${entry}" --jq .id 2>/dev/null); then + echo "User:${id}" + else + die "Could not resolve reviewer '${entry}' as team '${owner}/${entry}' or as a user." + fi +} + +# Build the PUT body for an environment from "Type:id,Type:id" + flags. +gh_env_body() { + local reviewers="$1" prevent="$2" branch_policy="$3" + node -e " + const [reviewers, prevent, branchPolicy] = process.argv.slice(1); + const body = {}; + if (reviewers) { + body.reviewers = reviewers.split(',').map((r) => { + const [type, id] = r.split(':'); + return { type, id: Number(id) }; + }); + if (prevent === 'true') body.prevent_self_review = true; + } + if (branchPolicy === 'true') { + body.deployment_branch_policy = { protected_branches: false, custom_branch_policies: true }; + } + process.stdout.write(JSON.stringify(body)); + " "$reviewers" "$prevent" "$branch_policy" +} + +gh_configure_environment() { + local repo="$1" env="$2" reviewers_csv="$3" + local owner="${repo%%/*}" + + local resolved="" + if [[ -n "$reviewers_csv" ]]; then + local entry + IFS=',' read -ra entries <<< "$reviewers_csv" + for entry in "${entries[@]}"; do + local r + r=$(gh_resolve_reviewer "$owner" "$entry") + resolved="${resolved:+${resolved},}${r}" + echo " ${env}: reviewer ${entry} -> ${r}" + done + fi + + local body + body=$(gh_env_body "$resolved" "$PREVENT_SELF_REVIEW" "$BRANCH_POLICY") + printf '%s' "$body" | gh api -X PUT "repos/${repo}/environments/${env}" --input - --silent + echo " ${env}: environment configured" + + if [[ "$BRANCH_POLICY" == "true" ]]; then + local existing + existing=$(gh api "repos/${repo}/environments/${env}/deployment-branch-policies" \ + --jq '[.branch_policies[].name] | join(" ")' 2>/dev/null || echo "") + if [[ " ${existing} " == *" main "* ]]; then + echo " ${env}: branch policy 'main' already present" + else + gh api -X POST "repos/${repo}/environments/${env}/deployment-branch-policies" \ + -f name=main --silent + echo " ${env}: deployments restricted to 'main'" + fi + fi +} + +setup_github() { + require_cmd gh + require_cmd node + local repo + repo=$(gh repo view --json nameWithOwner -q '.nameWithOwner') + + echo "Configuring GitHub environments for ${repo}..." + gh_configure_environment "$repo" "development" "$DEVELOPMENT_REVIEWERS" + gh_configure_environment "$repo" "production" "$PRODUCTION_REVIEWERS" +} + +# --------------------------------------------------------------------------- +# GitLab +# --------------------------------------------------------------------------- + +gl_encoded_path() { + local path + path=$(extract_path "$REMOTE_URL") + echo "${path//\//%2F}" +} + +gl_resolve_user_id() { + local username="$1" + local id + id=$(glab api "users?username=${username}" --hostname "$REMOTE_HOST" 2>/dev/null \ + | node -e " + const chunks=[]; process.stdin.on('data',c=>chunks.push(c)).on('end',()=>{ + try { + const users=JSON.parse(Buffer.concat(chunks).toString()); + process.stdout.write(users.length ? String(users[0].id) : ''); + } catch { process.stdout.write(''); } + }); + ") + [[ -n "$id" ]] || die "Could not resolve GitLab user '${username}'." + echo "$id" +} + +gl_protect_environment() { + local encoded_path="$1" env="$2" reviewers_csv="$3" + [[ -n "$reviewers_csv" ]] || return 0 + + local args=(--hostname "$REMOTE_HOST" --method POST + --raw-field "name=${env}" + --raw-field "deploy_access_levels[][access_level]=40" + --raw-field "required_approval_count=1") + local entry + IFS=',' read -ra entries <<< "$reviewers_csv" + for entry in "${entries[@]}"; do + local uid + uid=$(gl_resolve_user_id "$entry") + args+=(--raw-field "approval_rules[][user_id]=${uid}") + echo " ${env}: approver ${entry} -> user ${uid}" + done + + if glab api "projects/${encoded_path}/protected_environments" "${args[@]}" >/dev/null 2>&1; then + echo " ${env}: protected environment configured" + else + echo " Warning: could not configure protected environment '${env}'." >&2 + echo " Protected environments with approval rules require GitLab Premium;" >&2 + echo " if it already exists, update it in Settings > CI/CD > Protected environments." >&2 + fi +} + +setup_gitlab() { + require_cmd glab + require_cmd node + local encoded_path + encoded_path=$(gl_encoded_path) + + echo "Configuring GitLab protected environments..." + if [[ "$PREVENT_SELF_REVIEW" == "true" ]]; then + echo " Warning: --prevent-self-review has no GitLab equivalent for deployment approvals; skipping." >&2 + fi + if [[ "$BRANCH_POLICY" == "true" ]]; then + echo " Note: --branch-policy is GitHub-only. On GitLab, restrict deployments via protected branches (dev/main)." >&2 + fi + gl_protect_environment "$encoded_path" "development" "$DEVELOPMENT_REVIEWERS" + gl_protect_environment "$encoded_path" "production" "$PRODUCTION_REVIEWERS" +} + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +PLATFORM=$(detect_platform) +echo "Platform: ${PLATFORM}" + +if [[ "$PLATFORM" == "github" ]]; then + setup_github +else + setup_gitlab +fi + +echo "Done." From 98131ebbb0fe768f4b8135f3c8685cbdd3584dae Mon Sep 17 00:00:00 2001 From: Hironori Takahashi Date: Wed, 2 Dec 2026 19:28:58 +0900 Subject: [PATCH 2/3] feat: forward environment protection options from init.sh --- scripts/init.sh | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/scripts/init.sh b/scripts/init.sh index 47f3bad..db4725e 100755 --- a/scripts/init.sh +++ b/scripts/init.sh @@ -11,11 +11,18 @@ set -euo pipefail # # Usage: # ./scripts/init.sh [--title "Project Name"] [--type standalone|sheets|docs|slides|forms] [--gcp-project ] +# [--production-reviewers [,...]] [--development-reviewers [,...]] +# [--prevent-self-review] [--branch-policy] +# +# Environment protection options are forwarded to +# ./scripts/configure-environments.sh (also runnable standalone on existing +# repos). Without them, environments are created unprotected as before. TITLE="" SCRIPT_TYPE="standalone" GCP_PROJECT="" VALID_TYPES="standalone sheets docs slides forms" +ENV_PROTECT_ARGS=() while [[ $# -gt 0 ]]; do case $1 in @@ -31,6 +38,14 @@ while [[ $# -gt 0 ]]; do GCP_PROJECT="$2" shift 2 ;; + --production-reviewers|--development-reviewers) + ENV_PROTECT_ARGS+=("$1" "$2") + shift 2 + ;; + --prevent-self-review|--branch-policy) + ENV_PROTECT_ARGS+=("$1") + shift + ;; *) echo "Unknown option: $1" >&2 exit 1 @@ -328,6 +343,12 @@ elif [[ "$PLATFORM" == "gitlab" ]]; then setup_gitlab "$DEV_SCRIPT_ID" "$DEV_DEPLOYMENT_ID" "$PROD_SCRIPT_ID" "$PROD_DEPLOYMENT_ID" fi +# Environment protection (optional; see scripts/configure-environments.sh) +if [[ ${#ENV_PROTECT_ARGS[@]} -gt 0 ]]; then + echo "" + "$(dirname "$0")/configure-environments.sh" "${ENV_PROTECT_ARGS[@]}" +fi + # Cleanup rm -f .clasp.json From 50dbff7503931c0af3d809f97d22e9a9f49a19fe Mon Sep 17 00:00:00 2001 From: Hironori Takahashi Date: Wed, 2 Dec 2026 19:28:59 +0900 Subject: [PATCH 3/3] docs: document environment protection options in README --- README.ja.md | 9 +++++++++ README.md | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/README.ja.md b/README.ja.md index 624eb8c..b114f33 100644 --- a/README.ja.md +++ b/README.ja.md @@ -135,9 +135,18 @@ Apps Script Fleet は各 Apps Script 機能を独立したリポジトリとし - `--title "名前"` — Apps Script プロジェクト名(デフォルト: ディレクトリ名) - `--type standalone|sheets|docs|slides|forms` — Apps Script プロジェクトタイプ(デフォルト: `standalone`) - `--gcp-project <番号>` — 紐付ける GCP プロジェクト番号(Cloud Logging + `clasp run` が有効に) +- `--production-reviewers [,...]` / `--development-reviewers …` — デプロイ environment の required reviewers +- `--prevent-self-review` — デプロイを起こした本人は承認できないようにする +- `--branch-policy` — 両 environment のデプロイを `main` のみに制限(`workflow_run` 起動の cd.yml に合わせた設定) スクリプトは dev/prod の Apps Script プロジェクトを作成し、初回デプロイを行い、`CLASP_JSON` + `DEPLOYMENT_ID` を CI/CD プラットフォームに設定します。`--gcp-project` を指定した場合、Apps Script プロジェクトが GCP プロジェクトに紐付けられ、`GCP_PROJECT_NUMBER` が CI/CD 変数として設定されます。 +environment の保護設定はリポ単位の設定(org ルールセットでは一括適用不可)のため、保護オプションは既存リポ向けに単体でも実行できます: + +```bash +./scripts/configure-environments.sh --production-reviewers script-admins --prevent-self-review --branch-policy +``` + ### CI/CD 経由の Script Properties 注入 GCP プロジェクト統合が設定されている場合、デプロイ時に Script Properties を自動注入できます: diff --git a/README.md b/README.md index 70b4881..77785ab 100644 --- a/README.md +++ b/README.md @@ -135,9 +135,18 @@ Options: - `--title "Name"` — Apps Script project title (default: directory name) - `--type standalone|sheets|docs|slides|forms` — Apps Script project type (default: `standalone`) - `--gcp-project ` — GCP project number to bind (enables Cloud Logging + `clasp run`) +- `--production-reviewers [,...]` / `--development-reviewers …` — required reviewers for the deployment environment +- `--prevent-self-review` — the user who triggered a deployment cannot approve it +- `--branch-policy` — restrict both environments' deployments to `main` (matches the `workflow_run`-based cd.yml) The script creates dev/prod Apps Script projects, deploys initial versions, and sets `CLASP_JSON` + `DEPLOYMENT_ID` on your CI/CD platform. When `--gcp-project` is specified, the projects are bound to the GCP project and `GCP_PROJECT_NUMBER` is set as a CI/CD variable. +Environment protection is per-repo (org rulesets cannot apply it), so the protection options are also available standalone for existing repos: + +```bash +./scripts/configure-environments.sh --production-reviewers script-admins --prevent-self-review --branch-policy +``` + ### Script Properties via CI/CD When GCP project integration is configured, you can automatically inject Script Properties during deployment: