@tomgrv/devcontainer-features-gateway 0.0.0-stage → 11.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,226 @@
1
- # Temporary Holding Version
1
+ <!-- @format -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # Man In The Middle SSL Gateway Handling Feature
4
+
5
+ A [Dev Container](https://containers.dev/) helper for developing inside a corporate network protected by SSL inspection (Zscaler & similar).
6
+
7
+ ## Problem
8
+
9
+ SSL inspection tools act as a man-in-the-middle TLS proxy and replace server certificates with their own. This breaks tools like `curl`, `git`, `npm`, `pip`, and others that perform certificate validation, because the root CA is not trusted by default inside a container — and often not even on the host, which prevents Docker from pulling the base image and the devcontainer CLI from downloading features in the first place.
10
+
11
+ ## What this feature does
12
+
13
+ - Installs the SSL inspection root CA certificate(s) found in `.devcontainer/.gateway/certs/*.pem` into the container system trust store (at build time via the provided Dockerfile stub, and at create time via `postCreateCommand` — reached through the workspace's own standard mount, no dedicated bind mount required).
14
+ - Exposes the system CA bundle path via environment variables consumed by common runtimes and tools (Node.js, Python, Git, curl, Composer).
15
+ - Installs a `gateway-curl` wrapper that transparently handles gateway redirect forms and cookie management, and diverts the system `curl` to it — on by default inside a container, opt-in on a host (see [Options](#options)).
16
+ - Provisions VS Code extensions from VSIX packages fetched with `curl` — pre-fetched into the image at build time, then installed by a background flow running in parallel with VS Code attaching — because the VS Code server downloads extensions with Node's own `http` stack, which the curl wrapper cannot help (see [VS Code extensions](#vs-code-extensions-behind-the-gateway)).
17
+ - Optionally prepares the **host** as well, so the devcontainer can actually be created behind the gateway (see [Host installation](#host-installation--get-ready-for-devcontainer-creation)).
18
+
19
+ ## Quick Start — devcontainer.json
20
+
21
+ ```json
22
+ "features": {
23
+ "ghcr.io/tomgrv/devcontainer-features/gateway:11": {}
24
+ }
25
+ ```
26
+
27
+ Then create the certificate folder and drop your root CA into it:
28
+
29
+ ```sh
30
+ mkdir -p .devcontainer/.gateway/certs
31
+ cp /path/to/your-root-ca.pem .devcontainer/.gateway/certs/gateway.pem
32
+ ```
33
+
34
+ > The certificate itself is optional — everything degrades gracefully until you supply it. Certificates are picked up through the workspace's own standard mount, so the `certs` folder doesn't need to exist before the container is created; add it any time and re-run `feature-configure gateway` (or rebuild).
35
+ >
36
+ > The stub `devcontainer.json` deployed by [`add gateway`](#quick-install--console-recommended) additionally declares a dedicated bind mount to a fixed, workspace-layout-independent path — useful for non-standard workspaces, but opt-in and freely editable/removable in your own `devcontainer.json`. If you're running in a nested/docker-outside-of-docker setup and see `bind source path does not exist`, that dedicated mount is the one thing to remove — its `${localWorkspaceFolder}` source needs to be a path the Docker daemon itself can see, which a mounted `docker.sock` doesn't guarantee.
37
+
38
+ ## Quick Install — console (recommended)
39
+
40
+ `add gateway` self-detects whether it's running on the **host** or **inside an already-running container** and installs `gateway-curl` accordingly either way (diverting the system `curl` by default in a container, opt-in on a host — see [Options](#options)):
41
+
42
+ ```sh
43
+ npx tomgrv/devcontainer-features -- add gateway
44
+ # or, without node/npm:
45
+ curl -fsSL https://raw.githubusercontent.com/tomgrv/devcontainer-features/develop/setup.sh | sh -s -- add gateway
46
+ ```
47
+
48
+ Run it **on the host**, from the root of your project, before creating the container: this deploys the `.devcontainer` stubs (including a Dockerfile that bakes the certificate into the image at build time), installs `gateway-curl` on the host, and on Debian-based Linux/WSL installs the certificate into the host trust store when present. For other hosts, use the manual steps below.
49
+
50
+ ## Quick Install — npm
51
+
52
+ ```sh
53
+ npm install --save-dev @tomgrv/devcontainer-features-gateway
54
+ ```
55
+
56
+ ## Options
57
+
58
+ | Option | Type | Default | Description |
59
+ | ------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ |
60
+ | `replaceCurl` | boolean | `true` | Divert the system `curl` to the `gateway-curl` wrapper inside the container (the real binary is kept as `curl.real`) |
61
+ | `vsix` | string | `""` | VS Code extensions (`publisher.name[@version]`, comma or space separated) to download with `curl` into the image at build time |
62
+
63
+ ## Host installation — get ready for devcontainer creation
64
+
65
+ Declaring the feature in `devcontainer.json` is not always sufficient: the **host** needs to trust the gateway root CA too, otherwise `docker pull`, the devcontainer feature downloads, and any build-time HTTPS traffic fail before your container even exists.
66
+
67
+ ### Automated (Linux / WSL, Debian-based)
68
+
69
+ From the root of your project, on the host. Any `npx tomgrv/devcontainer-features --` call below can be replaced with the no-node/npm `curl` form shown in [Quick Install](#quick-install--console-recommended) — just swap `add gateway` in after `-s --`.
70
+
71
+ ```sh
72
+ # 1. Deploy the stubs and install gateway-curl on the host
73
+ npx tomgrv/devcontainer-features -- add gateway
74
+
75
+ # 2. Drop your root CA in place (PEM format)
76
+ cp /path/to/your-root-ca.pem .devcontainer/.gateway/certs/gateway.pem
77
+
78
+ # 3. Re-run the configuration to install the certificate into the host trust store
79
+ npx tomgrv/devcontainer-features -- add gateway
80
+ ```
81
+
82
+ The host system `curl` is **never replaced automatically**. To also divert the host `curl` to the wrapper:
83
+
84
+ ```sh
85
+ GATEWAY_REPLACE_CURL=1 npx tomgrv/devcontainer-features -- add gateway
86
+ ```
87
+
88
+ Restart Docker after installing the certificate so the daemon picks up the new trust store:
89
+
90
+ ```sh
91
+ sudo systemctl restart docker
92
+ ```
93
+
94
+ ### Manual (other hosts)
95
+
96
+ - **macOS**: `sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain your-root-ca.pem`, then restart Docker Desktop.
97
+ - **Windows**: `certutil -addstore -f ROOT your-root-ca.pem` (elevated prompt), then restart Docker Desktop. The `ukoloff.win-ca` VS Code extension (pre-configured in the stub) propagates Windows certificates to VS Code.
98
+ - **Docker registries behind the gateway**: if pulls still fail, also place the certificate in `/etc/docker/certs.d/<registry>/ca.crt`.
99
+
100
+ Once the host trusts the CA and the certificate sits in `.devcontainer/.gateway/certs/`, the repository is ready: **Reopen in Container** just works.
101
+
102
+ ## How it works
103
+
104
+ | Context | What `add gateway` does |
105
+ | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
106
+ | Host (optional, Debian-based) | Installs `gateway-curl`, leaves the system `curl` untouched unless `GATEWAY_REPLACE_CURL=1`, and (on Debian-based Linux/WSL) installs the CA into the host trust store when present |
107
+ | Inside a container (devcontainer feature build or an already-running container) | Installs `gateway-curl` and diverts the system `curl` to it, unless the `replaceCurl` option is set to `false` |
108
+
109
+ ## Availability during the OCI image build
110
+
111
+ Trusting the gateway root CA and diverting `curl` normally only happen at container-create time (`postCreateCommand`), which runs **after** the image is built — too late for any `RUN curl ...` in a custom Dockerfile, or for an earlier-ordered feature that fetches something over HTTPS during its own `install.sh`.
112
+
113
+ The `.gateway/Dockerfile` stub closes that gap: it bakes both the root CA trust and the `gateway-curl` diversion into the very first layer of the image, before any feature runs. The mechanics it runs (`install-certs-core.sh`, `install-curl-wrapper-core.sh`, `gateway-curl.sh`) live under `stubs/.devcontainer/.gateway/` and are the single source of truth: `configure-certs.sh`/`install-wrapper.sh` call the very same scripts from that same relative path at container-create time, rather than keeping a second copy at the feature root.
114
+
115
+ ## Modified repository structure
116
+
117
+ ```
118
+ .devcontainer/
119
+ ├── devcontainer.json # Dev Container configuration (references the feature + Dockerfile)
120
+ └── .gateway/
121
+ ├── Dockerfile # Bakes the certificate at image build time
122
+ └── certs/
123
+ ├── .gitignore # Keeps your corporate CA out of the repository
124
+ └── gateway.pem # Gateway root CA certificate ← YOU MUST SUPPLY THIS
125
+ ```
126
+
127
+ ## VS Code extensions behind the gateway
128
+
129
+ The VS Code server installs extensions itself, from the Marketplace, with Node's own `http` stack: it never goes through `curl`, so the `gateway-curl` wrapper can't answer the gateway's interception form on its behalf, and every extension download fails. Trusting the root CA (`NODE_EXTRA_CA_CERTS`) fixes TLS, not the form.
130
+
131
+ The feature works around it in two flows, both downloading the `.vsix` packages with `curl` (hence through `gateway-curl`) and installing them from disk with the server's own CLI, which then never has to reach the Marketplace:
132
+
133
+ 1. **Build time (docker)** — extensions listed in the `vsix` option are fetched into the image, under `/usr/local/share/gateway/vsix/`:
134
+
135
+ ```json
136
+ "features": {
137
+ "ghcr.io/tomgrv/devcontainer-features/gateway:11": {
138
+ "vsix": "esbenp.prettier-vscode, ms-python.python@2024.2.1"
139
+ }
140
+ }
141
+ ```
142
+
143
+ Build-time failures (e.g. no root CA baked by the [Dockerfile stub](#availability-during-the-oci-image-build) yet) don't break the build: flow 2 retries.
144
+
145
+ 2. **Container creation (parallel)** — `postCreateCommand` detaches `gateway-vsix sync`, so container creation never waits on it. It fetches every extension your `devcontainer.json` lists under `customizations.vscode.extensions` that the image doesn't already hold (into `~/.cache/gateway/vsix/`), waits for the VS Code server to show up (15 min max), then installs everything cached. Log: `/tmp/gateway-vsix.log`.
146
+
147
+ VS Code still attempts its own Marketplace install of the `devcontainer.json` extensions in the meantime: those attempts may fail with a notification until `gateway-vsix sync` has installed them — run **Developer: Reload Window** if one doesn't activate. The feature also preconfigures the server with `extensions.autoUpdate` / `extensions.autoCheckUpdates` turned off, so it doesn't keep hitting the Marketplace (and failing) afterwards.
148
+
149
+ The extension list is resolved recursively from the root `devcontainer.json`: its own `customizations.vscode.extensions`, then those of every feature it references and, in turn, of their `dependsOn` (each feature visited once). OCI features are read from their registry manifest (`dev.containers.metadata` annotation, anonymous pull token, fetched with `curl` too), local `./` features from disk. A `-publisher.name` entry anywhere removes that extension. A feature whose metadata can't be reached is skipped with a log line.
150
+
151
+ Manual use:
152
+
153
+ ```sh
154
+ gateway-vsix fetch ~/.cache/gateway/vsix publisher.name[@version]... # download
155
+ gateway-vsix ids .devcontainer/devcontainer.json # list what devcontainer.json wants
156
+ gateway-vsix sync # fetch + wait for server + install
157
+ ```
158
+
159
+ | Variable | Purpose |
160
+ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------- |
161
+ | `GATEWAY_VSIX_URL` | Download URL template with `{publisher}` `{name}` `{version}` placeholders (default: Visual Studio Marketplace) |
162
+ | `GATEWAY_VSIX_DIR` | Runtime download cache (default: `~/.cache/gateway/vsix`) |
163
+ | `GATEWAY_VSIX_CURL` | curl command (default: `gateway-curl` when on `PATH`, else `curl`) |
164
+ | `GATEWAY_VSIX_TIMEOUT` | Seconds `sync` waits for the VS Code server (default: `900`) |
165
+ | `GATEWAY_VSIX_CLI` | VS Code server CLI to install with (default: newest `code-server` found under `~/.vscode-server`, insiders or Codespaces) |
166
+
167
+ For Open VSX (pinned versions only): `GATEWAY_VSIX_URL='https://open-vsx.org/api/{publisher}/{name}/{version}/file/{publisher}.{name}-{version}.vsix'`.
168
+
169
+ Alternative, when the **host** VS Code gets past the gateway (e.g. Windows with `ukoloff.win-ca`): set `"remote.downloadExtensionsLocally": true` in your local user settings, so the host downloads extensions and pushes them into the container.
170
+
171
+ ## Environment variables set automatically
172
+
173
+ All variables point to the system CA bundle (`/etc/ssl/certs/ca-certificates.crt`), which includes the gateway root CA once installed:
174
+
175
+ | Variable | Purpose |
176
+ | --------------------- | --------------------------------- |
177
+ | `NODE_EXTRA_CA_CERTS` | Node.js / npm TLS trust |
178
+ | `REQUESTS_CA_BUNDLE` | Python `requests` / pip TLS trust |
179
+ | `SSL_CERT_FILE` | OpenSSL-based tools |
180
+ | `CURL_CA_BUNDLE` | curl TLS trust |
181
+ | `GIT_SSL_CAINFO` | git TLS trust |
182
+ | `COMPOSER_CA_FILE` | PHP Composer TLS trust |
183
+
184
+ ## How the curl wrapper works
185
+
186
+ When a request is intercepted by the gateway and answered with an authentication/acceptance form, the wrapper:
187
+
188
+ 1. Detects the HTML form response from the gateway.
189
+ 2. Parses and auto-submits the form fields.
190
+ 3. Saves the resulting session cookies to `~/.gateway_cookies.txt`.
191
+ 4. Re-issues the original request transparently.
192
+
193
+ All other requests — including anything the wrapper cannot intercept safely (`-I`, `-O`, `-T`, `-w`, multiple URLs, …) — are passed through to the real curl unchanged, preserving arguments, output destinations and exit codes.
194
+
195
+ Wrapper environment variables:
196
+
197
+ | Variable | Purpose |
198
+ | --------------------- | ----------------------------------------------------------------- |
199
+ | `GATEWAY_COOKIE_FILE` | Path to the cookie jar (default: `~/.gateway_cookies.txt`) |
200
+ | `GATEWAY_VERBOSE` | Set to `1` to trace what the wrapper does (silent by default) |
201
+ | `GATEWAY_MARKER` | Pattern identifying the gateway form (default: `gateway.zscaler`) |
202
+
203
+ ## Troubleshooting
204
+
205
+ **Certificate errors still occurring**
206
+ Verify that `gateway.pem` contains the correct root CA (not an intermediate or leaf certificate). You can inspect it with:
207
+
208
+ ```sh
209
+ openssl x509 -in .devcontainer/.gateway/certs/gateway.pem -noout -subject -issuer
210
+ ```
211
+
212
+ **Certificate added after the container was created**
213
+ Run `feature-configure gateway` inside the container (or rebuild it) to install the newly added certificate.
214
+
215
+ **Container creation fails with `bind source path does not exist` on the certs mount**
216
+ Only relevant if your `devcontainer.json` declares the optional dedicated `certs` bind mount (added by the `add gateway` stub). Either create `.devcontainer/.gateway/certs` on the host before creating the container, or — in a nested/docker-outside-of-docker setup, where `${localWorkspaceFolder}` isn't a path the Docker daemon itself can resolve — remove that `mounts` entry from `devcontainer.json` entirely; certificates are still picked up through the workspace's own standard mount.
217
+
218
+ **VS Code extensions fail to install**
219
+ Check `/tmp/gateway-vsix.log`, then re-run `gateway-vsix sync` in a terminal once the certificate is in place.
220
+
221
+ **curl wrapper causes issues**
222
+ Call `curl.real` directly to bypass the wrapper, set `replaceCurl` to `false` to keep the system curl untouched, or set `GATEWAY_VERBOSE=1` to see what the wrapper is doing.
223
+
224
+ ## License
225
+
226
+ MIT
@@ -0,0 +1,310 @@
1
+ #!/bin/sh
2
+
3
+ # Provision VS Code extensions (VSIX) with curl, then hand them to the VS Code
4
+ # server once it shows up.
5
+ #
6
+ # The VS Code server downloads extensions with Node's own http stack: it never
7
+ # goes through curl, so the gateway-curl wrapper cannot answer the SSL
8
+ # inspection gateway's interception form on its behalf, and every Marketplace
9
+ # download fails. This script fetches the VSIX packages with curl instead
10
+ # (i.e. through gateway-curl), and installs them from disk with the server's
11
+ # own CLI, which then never needs to reach the Marketplace.
12
+ #
13
+ # Usage:
14
+ # gateway-vsix fetch <dir> <publisher.name[@version]>...
15
+ # Download each extension into <dir>/<publisher.name>.vsix (skipped when
16
+ # already there). Ids prefixed with "-" (devcontainer.json removal
17
+ # syntax) are ignored.
18
+ # gateway-vsix ids [devcontainer.json]
19
+ # Print customizations.vscode.extensions from a devcontainer.json
20
+ # (default: .devcontainer/devcontainer.json) and, recursively, from every
21
+ # feature it references and their dependsOn: OCI features through their
22
+ # registry manifest ("dev.containers.metadata" annotation), local ./
23
+ # features from disk. "-publisher.name" entries remove an extension.
24
+ # Full-line // comments are tolerated, block comments and trailing
25
+ # commas are not.
26
+ # gateway-vsix install <cli> <dir>...
27
+ # Install every *.vsix found in <dir>... with the VS Code server <cli>.
28
+ # gateway-vsix sync
29
+ # The whole flow, meant to run in the background while VS Code attaches:
30
+ # fetch whatever devcontainer.json lists and isn't cached yet, wait for
31
+ # the VS Code server CLI to appear, then install everything cached.
32
+ #
33
+ # Environment variables:
34
+ # GATEWAY_VSIX_DIR Runtime download cache (default: ~/.cache/gateway/vsix)
35
+ # GATEWAY_VSIX_PREFETCH Build-time cache, read-only here (default: /usr/local/share/gateway/vsix)
36
+ # GATEWAY_VSIX_CURL curl command (default: gateway-curl when on PATH, else curl)
37
+ # GATEWAY_VSIX_URL Download URL template, {publisher} {name} {version}
38
+ # placeholders (default: Visual Studio Marketplace)
39
+ # GATEWAY_VSIX_PLATFORM Target platform (default: derived from the OS/arch)
40
+ # GATEWAY_VSIX_CLI VS Code server CLI (default: auto-detected)
41
+ # GATEWAY_VSIX_TIMEOUT Seconds to wait for the VS Code server (default: 900)
42
+
43
+ PREFETCH_DIR="${GATEWAY_VSIX_PREFETCH:-/usr/local/share/gateway/vsix}"
44
+ CACHE_DIR="${GATEWAY_VSIX_DIR:-${XDG_CACHE_HOME:-${HOME:-/tmp}/.cache}/gateway/vsix}"
45
+ # Not a ${:-} default: its "}" placeholders would close the expansion early
46
+ URL_TEMPLATE="$GATEWAY_VSIX_URL"
47
+ [ -n "$URL_TEMPLATE" ] || URL_TEMPLATE="https://marketplace.visualstudio.com/_apis/public/gallery/publishers/{publisher}/vsextensions/{name}/{version}/vspackage"
48
+
49
+ log() {
50
+ echo "[gateway-vsix] $*" >&2
51
+ }
52
+
53
+ resolve_curl() {
54
+ if [ -n "${GATEWAY_VSIX_CURL:-}" ]; then
55
+ echo "$GATEWAY_VSIX_CURL"
56
+ elif command -v gateway-curl >/dev/null 2>&1; then
57
+ echo gateway-curl
58
+ else
59
+ echo curl
60
+ fi
61
+ }
62
+
63
+ # Marketplace target platform of this machine, empty when unknown
64
+ resolve_platform() {
65
+ if [ -n "${GATEWAY_VSIX_PLATFORM+x}" ]; then
66
+ echo "$GATEWAY_VSIX_PLATFORM"
67
+ return
68
+ fi
69
+ os=linux
70
+ [ -f /etc/alpine-release ] && os=alpine
71
+ case "$(uname -m)" in
72
+ x86_64 | amd64) echo "$os-x64" ;;
73
+ aarch64 | arm64) echo "$os-arm64" ;;
74
+ armv7l | armhf) echo "$os-armhf" ;;
75
+ esac
76
+ }
77
+
78
+ # A VSIX is a zip archive: anything else is an error page or a gateway form
79
+ is_vsix() {
80
+ [ -s "$1" ] && [ "$(head -c2 "$1")" = "PK" ]
81
+ }
82
+
83
+ vsix_name() {
84
+ echo "${1%%@*}" | tr '[:upper:]' '[:lower:]'
85
+ }
86
+
87
+ download() {
88
+ tmp="$2.part"
89
+ # No -S: a 404 on the platform-specific probe is expected, not an error
90
+ if "$CURL" -fsL --compressed --retry 2 -o "$tmp" "$1" 2>/dev/null && is_vsix "$tmp"; then
91
+ # gateway-curl writes through mktemp (0600): keep it readable by the remote user
92
+ mv "$tmp" "$2" && chmod 644 "$2"
93
+ return 0
94
+ fi
95
+ rm -f "$tmp"
96
+ return 1
97
+ }
98
+
99
+ fetch() {
100
+ dir="$1"
101
+ shift
102
+ [ -n "$dir" ] || {
103
+ log "Usage: gateway-vsix fetch <dir> <publisher.name[@version]>..."
104
+ return 1
105
+ }
106
+ mkdir -p "$dir" || return 1
107
+
108
+ CURL=$(resolve_curl)
109
+ platform=$(resolve_platform)
110
+ rc=0
111
+
112
+ for spec in "$@"; do
113
+ case "$spec" in
114
+ "" | -*) continue ;;
115
+ esac
116
+
117
+ id="${spec%%@*}"
118
+ version=latest
119
+ [ "$id" != "$spec" ] && version="${spec#*@}"
120
+ publisher="${id%%.*}"
121
+ name="${id#*.}"
122
+ if [ -z "$publisher" ] || [ -z "$name" ] || [ "$name" = "$id" ]; then
123
+ log "Invalid extension id: $spec"
124
+ rc=1
125
+ continue
126
+ fi
127
+
128
+ file="$dir/$(vsix_name "$id").vsix"
129
+ if is_vsix "$file"; then
130
+ log "$id already cached"
131
+ continue
132
+ fi
133
+
134
+ url=$(echo "$URL_TEMPLATE" | sed -e "s|{publisher}|$publisher|g" -e "s|{name}|$name|g" -e "s|{version}|$version|g")
135
+ case "$url" in
136
+ *\?*) sep="&" ;;
137
+ *) sep="?" ;;
138
+ esac
139
+
140
+ # Platform-specific build first, universal package as a fallback
141
+ if { [ -n "$platform" ] && download "$url${sep}targetPlatform=$platform" "$file"; } || download "$url" "$file"; then
142
+ log "$id fetched"
143
+ else
144
+ log "$id could not be fetched from $url"
145
+ rc=1
146
+ fi
147
+ done
148
+ return $rc
149
+ }
150
+
151
+ # devcontainer-feature.json of a feature reference, on stdout
152
+ feature_meta() {
153
+ ref="$1"
154
+ case "$ref" in
155
+ ./* | ../*)
156
+ sed 's#^[[:space:]]*//.*$##' "$2/$ref/devcontainer-feature.json" 2>/dev/null
157
+ return
158
+ ;;
159
+ esac
160
+
161
+ registry="${ref%%/*}"
162
+ path="${ref#*/}"
163
+ case "$registry" in
164
+ *.* | *:* | localhost) ;;
165
+ *) return 1 ;; # legacy GitHub-release feature id, no manifest to read
166
+ esac
167
+ case "$path" in
168
+ *@*) repo="${path%@*}" tag="${path#*@}" ;;
169
+ *:*) repo="${path%:*}" tag="${path##*:}" ;;
170
+ *) repo="$path" tag=latest ;;
171
+ esac
172
+
173
+ url="https://$registry/v2/$repo/manifests/$tag"
174
+ accept="Accept: application/vnd.oci.image.manifest.v1+json"
175
+
176
+ # Anonymous pull token, as advertised by the registry's challenge
177
+ auth="X-Anonymous: 1"
178
+ challenge=$("$CURL" -sI -H "$accept" "$url" 2>/dev/null | tr -d '\r' | sed -n 's/^[Ww][Ww][Ww]-[Aa]uthenticate: *Bearer *//p')
179
+ if [ -n "$challenge" ]; then
180
+ realm=$(echo "$challenge" | sed -n 's/.*realm="\([^"]*\)".*/\1/p')
181
+ service=$(echo "$challenge" | sed -n 's/.*service="\([^"]*\)".*/\1/p')
182
+ scope=$(echo "$challenge" | sed -n 's/.*scope="\([^"]*\)".*/\1/p')
183
+ token=$("$CURL" -fsS "$realm?service=$service&scope=$scope" 2>/dev/null | jq -r '.token // .access_token // empty')
184
+ [ -n "$token" ] && auth="Authorization: Bearer $token"
185
+ fi
186
+
187
+ "$CURL" -fsS -H "$accept" -H "$auth" "$url" 2>/dev/null |
188
+ jq -r '.annotations["dev.containers.metadata"] // empty'
189
+ }
190
+
191
+ ids() {
192
+ file="${1:-.devcontainer/devcontainer.json}"
193
+ [ -f "$file" ] || return 0
194
+ base=$(dirname "$file")
195
+ CURL=$(resolve_curl)
196
+
197
+ # Breadth-first over features and their dependsOn, each visited once
198
+ json=$(sed 's#^[[:space:]]*//.*$##' "$file")
199
+ queue=""
200
+ seen=""
201
+ while :; do
202
+ printf '%s' "$json" | jq -r '.customizations.vscode.extensions[]? | select(type == "string")' 2>/dev/null
203
+
204
+ for ref in $(printf '%s' "$json" | jq -r '(.features // {}), (.dependsOn // {}) | keys[]' 2>/dev/null); do
205
+ case " $seen " in
206
+ *" $ref "*) continue ;;
207
+ esac
208
+ seen="$seen $ref"
209
+ queue="$queue $ref"
210
+ done
211
+
212
+ # shellcheck disable=SC2086 # one word per feature reference
213
+ set -- $queue
214
+ [ $# -gt 0 ] || break
215
+ ref="$1"
216
+ shift
217
+ queue="$*"
218
+
219
+ json=$(feature_meta "$ref" "$base")
220
+ [ -n "$json" ] || log "No metadata for feature $ref, its extensions are skipped"
221
+ done | awk '
222
+ /^-/ { removed[tolower(substr($0, 2))] = 1; next }
223
+ { id = tolower($0); sub(/@.*/, "", id); if (!(($0) in listed)) { listed[$0] = 1; order[++n] = $0; key[n] = id } }
224
+ END { for (i = 1; i <= n; i++) if (!(key[i] in removed)) print order[i] }'
225
+ }
226
+
227
+ # Newest VS Code server CLI found on this machine, if any
228
+ server_cli() {
229
+ # shellcheck disable=SC2086 # globs are meant to expand here
230
+ ls -td \
231
+ "$HOME"/.vscode-server/cli/servers/*/server/bin/code-server \
232
+ "$HOME"/.vscode-server/bin/*/bin/code-server \
233
+ "$HOME"/.vscode-server-insiders/cli/servers/*/server/bin/code-server-insiders \
234
+ "$HOME"/.vscode-server-insiders/bin/*/bin/code-server-insiders \
235
+ /vscode/bin/*/*/bin/code-server* \
236
+ 2>/dev/null | head -n1
237
+ }
238
+
239
+ # Wait until the server CLI exists and actually runs (it can show up before
240
+ # its archive has finished extracting)
241
+ wait_cli() {
242
+ deadline=$(($(date +%s) + ${GATEWAY_VSIX_TIMEOUT:-900}))
243
+ while :; do
244
+ cli="${GATEWAY_VSIX_CLI:-$(server_cli)}"
245
+ if [ -n "$cli" ] && [ -x "$cli" ] && "$cli" --version >/dev/null 2>&1; then
246
+ echo "$cli"
247
+ return 0
248
+ fi
249
+ [ "$(date +%s)" -ge "$deadline" ] && return 1
250
+ sleep "${GATEWAY_VSIX_POLL:-2}"
251
+ done
252
+ }
253
+
254
+ install() {
255
+ cli="$1"
256
+ shift
257
+ [ -n "$cli" ] || {
258
+ log "Usage: gateway-vsix install <cli> <dir>..."
259
+ return 1
260
+ }
261
+
262
+ set -- $(for dir in "$@"; do
263
+ for vsix in "$dir"/*.vsix; do
264
+ is_vsix "$vsix" && printf '%s\n' "--install-extension" "$vsix"
265
+ done
266
+ done)
267
+
268
+ if [ $# -eq 0 ]; then
269
+ log "No VSIX to install"
270
+ return 0
271
+ fi
272
+
273
+ # Already installed extensions are left as they are (no --force): a
274
+ # newer version installed meanwhile is never downgraded.
275
+ "$cli" "$@"
276
+ }
277
+
278
+ sync() {
279
+ missing=""
280
+ for id in $({ ids .devcontainer/devcontainer.json; ids .devcontainer.json; } | sort -u); do
281
+ is_vsix "$PREFETCH_DIR/$(vsix_name "$id").vsix" || missing="$missing $id"
282
+ done
283
+
284
+ # shellcheck disable=SC2086 # one argument per extension id
285
+ [ -n "$missing" ] && ! fetch "$CACHE_DIR" $missing && log "Some extensions could not be fetched"
286
+
287
+ if [ -z "$(ls "$PREFETCH_DIR" "$CACHE_DIR" 2>/dev/null | grep '\.vsix$')" ]; then
288
+ log "Nothing to provision"
289
+ return 0
290
+ fi
291
+
292
+ log "Waiting for the VS Code server..."
293
+ if ! cli=$(wait_cli); then
294
+ log "No VS Code server showed up, giving up"
295
+ return 1
296
+ fi
297
+
298
+ log "Installing extensions with $cli"
299
+ install "$cli" "$PREFETCH_DIR" "$CACHE_DIR"
300
+ }
301
+
302
+ cmd="$1"
303
+ [ $# -gt 0 ] && shift
304
+ case "$cmd" in
305
+ fetch | ids | install | sync) "$cmd" "$@" ;;
306
+ *)
307
+ sed -n '/^# Usage:/,/^$/s/^# \{0,1\}//p' "$0" >&2
308
+ exit 1
309
+ ;;
310
+ esac
@@ -0,0 +1,66 @@
1
+ #!/bin/sh
2
+
3
+ # Install the SSL inspection root CA certificate(s) into the system trust store.
4
+ #
5
+ # Certificates (*.pem) are looked up in the first existing location among:
6
+ # 1. $GATEWAY_CERTS_DIR (explicit override)
7
+ # 2. /usr/local/share/gateway/certs (optional dedicated bind mount, see below)
8
+ # 3. ./.devcontainer/.gateway/certs (repository folder — covers both host use and
9
+ # postCreateCommand, since it runs with cwd set
10
+ # to the workspace folder, already reachable
11
+ # through the workspace's own standard mount)
12
+ #
13
+ # The dedicated mount at #2 is declared in the stub devcontainer.json (not in this
14
+ # feature's own devcontainer-feature.json), so it's opt-in and freely editable per
15
+ # project — useful for non-standard workspace layouts, but not required, and it's the
16
+ # one thing to remove if it fails to resolve in a nested/docker-outside-of-docker setup
17
+ # (its ${localWorkspaceFolder} source needs to be a path the Docker daemon itself can
18
+ # see, which isn't guaranteed when it's reached through a mounted docker.sock).
19
+ #
20
+ # Missing certificates are not an error: the feature stays dormant until the
21
+ # user drops the gateway root CA in place and re-runs 'feature-configure gateway'.
22
+
23
+ . zz-colors
24
+
25
+ # Escalate only when needed and possible
26
+ asroot=""
27
+ if [ "$(id -u)" != "0" ] && command -v sudo >/dev/null 2>&1; then
28
+ asroot="sudo"
29
+ fi
30
+
31
+ # Find the first location containing certificates
32
+ certs_dir=""
33
+ for dir in "${GATEWAY_CERTS_DIR:-}" /usr/local/share/gateway/certs .devcontainer/.gateway/certs; do
34
+ [ -n "$dir" ] && [ -d "$dir" ] || continue
35
+ if ls "$dir"/*.pem >/dev/null 2>&1; then
36
+ certs_dir="$dir"
37
+ break
38
+ fi
39
+ done
40
+
41
+ if [ -z "$certs_dir" ]; then
42
+ zz-log w "No gateway root CA certificate found (*.pem)"
43
+ zz-log - "Export your SSL inspection root CA in PEM format to {U .devcontainer/.gateway/certs/gateway.pem}"
44
+ zz-log - "then run {B feature-configure gateway} again (or rebuild the container)"
45
+ exit 0
46
+ fi
47
+
48
+ if ! command -v update-ca-certificates >/dev/null 2>&1; then
49
+ zz-log w "update-ca-certificates not available on this system"
50
+ zz-log - "Install the certificates from {U $certs_dir} into your trust store manually"
51
+ exit 0
52
+ fi
53
+
54
+ core="$(dirname "$0")/stubs/.devcontainer/.gateway/install-certs-core.sh"
55
+ if [ ! -f "$core" ]; then
56
+ zz-log e "Core script not found at {U $core}"
57
+ exit 1
58
+ fi
59
+
60
+ zz-log i "Installing certificate(s) from {U $certs_dir}..."
61
+ if $asroot sh "$core" "$certs_dir"; then
62
+ zz-log s "Gateway root CA trust store up to date from {U $certs_dir}"
63
+ else
64
+ zz-log w "Cannot install certificate(s) from {U $certs_dir} (insufficient privileges)"
65
+ zz-log - "Re-run as root or ensure sudo is available"
66
+ fi
@@ -0,0 +1,30 @@
1
+ #!/bin/sh
2
+
3
+ # Provision VS Code extensions from VSIX, in parallel with VS Code attaching.
4
+ #
5
+ # Detaches 'gateway-vsix sync' so container creation never waits on it: it
6
+ # fetches (with curl) whatever devcontainer.json lists and the image build
7
+ # didn't already pre-fetch, waits for the VS Code server to show up, then
8
+ # installs every cached VSIX with the server's own CLI.
9
+ #
10
+ # Sorted after configure-certs.sh by feature-configure, so the root CA is
11
+ # already trusted when the downloads start. Container-only: on a host there's
12
+ # no VS Code server to wait for.
13
+
14
+ . zz-colors
15
+
16
+ if [ ! -f /.dockerenv ] && [ -z "${REMOTE_CONTAINERS:-}" ] && [ "${CODESPACES:-}" != "true" ]; then
17
+ exit 0
18
+ fi
19
+
20
+ if ! command -v gateway-vsix >/dev/null 2>&1; then
21
+ zz-log w "gateway-vsix not found on PATH, VS Code extensions left to VS Code itself"
22
+ exit 0
23
+ fi
24
+
25
+ logfile="${TMPDIR:-/tmp}/gateway-vsix.log"
26
+ detach=""
27
+ command -v setsid >/dev/null 2>&1 && detach=setsid
28
+
29
+ nohup $detach gateway-vsix sync >"$logfile" 2>&1 </dev/null &
30
+ zz-log s "VS Code extensions provisioning started in background, log at {U $logfile}"
@@ -0,0 +1,36 @@
1
+ #!/bin/sh
2
+
3
+ # Pre-fetch the VS Code extensions listed in the "vsix" feature option into the
4
+ # image, with curl, during the docker build itself — so the VS Code server
5
+ # never has to download them with its own Node.js http stack, which cannot get
6
+ # past the SSL inspection gateway's interception form.
7
+ #
8
+ # The gateway-curl wrapper is called by path, not through the (possibly not
9
+ # yet) diverted system curl, as install-*.sh scripts run in no fixed order.
10
+ #
11
+ # Download failures are not fatal: 'feature-configure gateway' (configure-vsix.sh)
12
+ # retries whatever devcontainer.json lists at container creation, once the
13
+ # root CA is trusted.
14
+
15
+ . zz-colors
16
+
17
+ eval $(
18
+ zz-context "$@"
19
+ )
20
+
21
+ list=$(echo "${VSIX:-}" | tr ',' ' ')
22
+ [ -n "$(echo "$list" | tr -d ' ')" ] || exit 0
23
+
24
+ wrapper="$target/stubs/.devcontainer/.gateway/gateway-curl.sh"
25
+ [ -f "$wrapper" ] && export GATEWAY_VSIX_CURL="$wrapper"
26
+
27
+ dest="$target/vsix"
28
+ zz-log i "Pre-fetching VS Code extensions into {U $dest}..."
29
+ # shellcheck disable=SC2086 # one argument per extension id
30
+ if sh "$target/bin/gateway-vsix.sh" fetch "$dest" $list; then
31
+ zz-log s "VS Code extensions pre-fetched"
32
+ else
33
+ zz-log w "Some VS Code extensions could not be pre-fetched, retried at container creation"
34
+ fi
35
+ chmod -R a+rX "$dest" 2>/dev/null
36
+ exit 0
@@ -0,0 +1,85 @@
1
+ #!/bin/sh
2
+
3
+ # Install the gateway-curl wrapper and optionally divert the system curl to it,
4
+ # so that SSL inspection gateway forms are handled transparently.
5
+ #
6
+ # - devcontainer build: diversion enabled by default (feature option "replaceCurl")
7
+ # - host install: wrapper is installed as 'gateway-curl' only, diversion is
8
+ # opt-in via GATEWAY_REPLACE_CURL=1
9
+
10
+ . zz-colors
11
+
12
+ eval $(
13
+ zz-context "$@"
14
+ )
15
+
16
+ stub_dir="$target/stubs/.devcontainer/.gateway"
17
+
18
+ wrapper="$stub_dir/gateway-curl.sh"
19
+ if [ ! -f "$wrapper" ]; then
20
+ zz-log e "Wrapper not found at {U $wrapper}"
21
+ exit 1
22
+ fi
23
+ chmod +x "$wrapper"
24
+
25
+ core="$stub_dir/install-curl-wrapper-core.sh"
26
+ if [ ! -f "$core" ]; then
27
+ zz-log e "Core script not found at {U $core}"
28
+ exit 1
29
+ fi
30
+
31
+ # Escalate only when needed and possible
32
+ asroot=""
33
+ if [ "$(id -u)" != "0" ] && command -v sudo >/dev/null 2>&1; then
34
+ asroot="sudo"
35
+ fi
36
+
37
+ # Expose the wrapper as 'gateway-curl'
38
+ bindir="/usr/local/bin"
39
+ if [ -w "$bindir" ]; then
40
+ sh "$core" install "$wrapper" "$bindir"
41
+ elif [ -n "$asroot" ] && $asroot sh "$core" install "$wrapper" "$bindir" 2>/dev/null; then
42
+ :
43
+ else
44
+ bindir="${HOME:-/tmp}/.local/bin"
45
+ sh "$core" install "$wrapper" "$bindir"
46
+ fi
47
+ zz-log s "Wrapper installed as {U $bindir/gateway-curl}"
48
+
49
+ # Decide whether to divert the system curl to the wrapper
50
+ if [ -n "${_REMOTE_USER:-}" ] || [ -n "${DEV_CONTAINER_FILE_PATH:-}" ] || [ "${CODESPACES:-}" = "true" ] || [ "${REMOTE_CONTAINERS:-}" = "true" ]; then
51
+ # devcontainer context: honour the feature option (default: true)
52
+ replace=$(echo "${REPLACECURL:-true}" | tr '[:upper:]' '[:lower:]')
53
+ else
54
+ # host context: never touch the system curl unless explicitly asked
55
+ case "${GATEWAY_REPLACE_CURL:-}" in
56
+ 1 | true | yes) replace=true ;;
57
+ *) replace=false ;;
58
+ esac
59
+ fi
60
+
61
+ if [ "$replace" != "true" ]; then
62
+ zz-log i "System curl left untouched, call {B gateway-curl} explicitly when needed"
63
+ zz-log - "Set {B GATEWAY_REPLACE_CURL=1} before installing to divert the system curl"
64
+ exit 0
65
+ fi
66
+
67
+ curl_bin=$(command -v curl 2>/dev/null || echo /usr/bin/curl)
68
+ was_diverted=0
69
+ [ -x "${curl_bin}.real" ] && was_diverted=1
70
+
71
+ if [ "$was_diverted" = "0" ] && [ ! -e "$curl_bin" ]; then
72
+ zz-log w "No system curl found to divert, use {B gateway-curl} explicitly"
73
+ exit 0
74
+ fi
75
+
76
+ if ! $asroot sh "$core" divert "$bindir"; then
77
+ zz-log w "Cannot divert {U $curl_bin} (insufficient rights), use {B gateway-curl} explicitly"
78
+ exit 0
79
+ fi
80
+
81
+ if [ "$was_diverted" = "1" ]; then
82
+ zz-log i "System curl already diverted to the wrapper"
83
+ else
84
+ zz-log s "System curl diverted to gateway-curl (real curl kept at ${curl_bin}.real)"
85
+ fi
package/install.sh ADDED
@@ -0,0 +1,4 @@
1
+ #!/bin/sh
2
+
3
+ ### Install this feature
4
+ feature-install $0
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@tomgrv/devcontainer-features-gateway",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "11.10.0",
4
+ "description": "SSL Inspection Gateway handling",
5
+ "files": [
6
+ "bin/*.sh",
7
+ "configure-*.sh",
8
+ "install-*.sh",
9
+ "install.sh",
10
+ "stubs/**/*"
11
+ ],
12
+ "bin": {
13
+ "gateway-curl": "stubs/.devcontainer/.gateway/gateway-curl.sh",
14
+ "gateway-vsix": "bin/gateway-vsix.sh"
15
+ },
16
+ "scripts": {
17
+ "install": "if [ \"$INIT_CWD\" = \"$PWD\" ]; then feature-install -s .; fi",
18
+ "postinstall": "if [ \"$INIT_CWD\" = \"$PWD\" ]; then feature-configure -s . gateway; fi",
19
+ "test": "bats tests/"
20
+ },
21
+ "dependencies": {},
22
+ "peerDependencies": {
23
+ "@tomgrv/devcontainer-features-common-utils": "*"
24
+ },
25
+ "peerDependenciesMeta": {
26
+ "@tomgrv/devcontainer-features-common-utils": {
27
+ "optional": true
28
+ }
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/tomgrv/devcontainer-features.git",
33
+ "directory": "src/gateway"
34
+ }
35
+ }
@@ -0,0 +1,36 @@
1
+ FROM mcr.microsoft.com/devcontainers/base:noble
2
+
3
+ # Bake the SSL inspection gateway handling into the image so that HTTPS
4
+ # already works during the image build itself and the devcontainer features
5
+ # installation that follows it — both the root CA trust and the curl form
6
+ # interception wrapper are otherwise only installed by the gateway feature's
7
+ # own postCreateCommand/install script, which runs too late to help this
8
+ # build stage or any earlier-ordered feature.
9
+ #
10
+ # install-certs-core.sh / install-curl-wrapper-core.sh / gateway-curl.sh
11
+ # are the single source of truth for this mechanics (also used at container
12
+ # runtime by configure-certs.sh/install-wrapper.sh, and referenced from the
13
+ # same relative path there) — they live here, under the stub tree, because a
14
+ # Docker build context cannot reach outside .devcontainer/.
15
+ #
16
+ # Tolerates an empty certs folder and a missing curl: the build succeeds
17
+ # even before the gateway root CA is dropped in .devcontainer/.gateway/certs/.
18
+ COPY ./certs/ /tmp/gateway/certs/
19
+ COPY ./install-certs-core.sh ./install-curl-wrapper-core.sh ./gateway-curl.sh /tmp/gateway/
20
+ RUN chmod +x /tmp/gateway/gateway-curl.sh \
21
+ && sh /tmp/gateway/install-certs-core.sh /tmp/gateway/certs \
22
+ && sh /tmp/gateway/install-curl-wrapper-core.sh install /tmp/gateway/gateway-curl.sh /usr/local/bin \
23
+ && sh /tmp/gateway/install-curl-wrapper-core.sh divert /usr/local/bin \
24
+ && rm -rf /tmp/gateway
25
+
26
+ # Tools that don't consult the OS trust store on their own (npm/pnpm/Node,
27
+ # pip, Composer, ...) still need to be told about it explicitly. The feature
28
+ # itself sets these as containerEnv, but that only takes effect once the
29
+ # container is created — too late for a `RUN npm install` here, or in any
30
+ # feature layer that follows this Dockerfile during the image build.
31
+ ENV COMPOSER_CA_FILE=/etc/ssl/certs/ca-certificates.crt \
32
+ CURL_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt \
33
+ GIT_SSL_CAINFO=/etc/ssl/certs/ca-certificates.crt \
34
+ NODE_EXTRA_CA_CERTS=/etc/ssl/certs/ca-certificates.crt \
35
+ REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt \
36
+ SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
@@ -0,0 +1,13 @@
1
+ *.pem
2
+ *.crt
3
+ *.key
4
+ *.csr
5
+ *.pfx
6
+ *.p12
7
+ *.jks
8
+ *.keystore
9
+ *.truststore
10
+ *.der
11
+ *.csr
12
+ *.srl
13
+ *.csr
File without changes
@@ -0,0 +1,321 @@
1
+ #!/bin/bash
2
+ # Gateway curl wrapper
3
+ #
4
+ # Transparently handles SSL inspection gateway interception forms (e.g. Zscaler):
5
+ # when a request is answered by the gateway redirect form instead of the real
6
+ # content, the wrapper auto-submits the form, saves the session cookies and
7
+ # replays the original request.
8
+ #
9
+ # Environment variables:
10
+ # GATEWAY_COOKIE_FILE Cookie jar path (default: ~/.gateway_cookies.txt)
11
+ # GATEWAY_VERBOSE Set to 1 to trace what the wrapper does (also: VERBOSE)
12
+ # GATEWAY_MARKER Pattern identifying the gateway form (default: gateway.zscaler)
13
+
14
+ COOKIE_FILE="${GATEWAY_COOKIE_FILE:-${HOME:-/tmp}/.gateway_cookies.txt}"
15
+ VERBOSE="${GATEWAY_VERBOSE:-${VERBOSE:-0}}"
16
+ MARKER="${GATEWAY_MARKER:-gateway.zscaler}"
17
+
18
+ RED='\033[0;31m'
19
+ GREEN='\033[0;32m'
20
+ YELLOW='\033[1;33m'
21
+ NC='\033[0m'
22
+
23
+ log() {
24
+ [ "$VERBOSE" = "1" ] && echo -e "${GREEN}[gateway-curl]${NC} $*" >&2
25
+ return 0
26
+ }
27
+
28
+ warn() {
29
+ [ "$VERBOSE" = "1" ] && echo -e "${YELLOW}[gateway-curl]${NC} $*" >&2
30
+ return 0
31
+ }
32
+
33
+ error() {
34
+ echo -e "${RED}[gateway-curl]${NC} $*" >&2
35
+ }
36
+
37
+ # Locate the real curl binary, never this script itself
38
+ resolve_real_curl() {
39
+ local self candidate
40
+ self=$(readlink -f "${BASH_SOURCE[0]}")
41
+ for candidate in /usr/bin/curl.real /usr/local/bin/curl.real; do
42
+ if [ -x "$candidate" ]; then
43
+ echo "$candidate"
44
+ return 0
45
+ fi
46
+ done
47
+ while IFS= read -r candidate; do
48
+ [ "$(readlink -f "$candidate")" = "$self" ] && continue
49
+ echo "$candidate"
50
+ return 0
51
+ done < <(type -aP curl)
52
+ return 1
53
+ }
54
+
55
+ usage() {
56
+ cat <<EOF
57
+ Usage: $(basename "$0") [curl options] <URL>
58
+
59
+ Wrapper around curl that automatically handles SSL inspection gateway forms.
60
+ Detects redirects to gateway authentication forms, submits the form, saves
61
+ cookies, and retries the original request. All other requests are passed
62
+ through to the real curl unchanged.
63
+
64
+ Environment variables:
65
+ GATEWAY_COOKIE_FILE Path to cookie file (default: ~/.gateway_cookies.txt)
66
+ GATEWAY_VERBOSE Set to 1 to enable verbose wrapper output
67
+ GATEWAY_MARKER Pattern identifying the gateway form (default: gateway.zscaler)
68
+
69
+ Examples:
70
+ $(basename "$0") https://example.com/file.tar.gz
71
+ $(basename "$0") -H "Accept: application/json" https://example.com/api/data
72
+ EOF
73
+ }
74
+
75
+ # Percent-encode a string (jq if available, pure bash fallback)
76
+ urlencode() {
77
+ if command -v jq >/dev/null 2>&1; then
78
+ printf '%s' "$1" | jq -sRr @uri
79
+ else
80
+ local s="$1" out="" c i hex
81
+ for ((i = 0; i < ${#s}; i++)); do
82
+ c="${s:$i:1}"
83
+ case "$c" in
84
+ [a-zA-Z0-9.~_-]) out+="$c" ;;
85
+ *)
86
+ printf -v hex '%%%02X' "'$c"
87
+ out+="$hex"
88
+ ;;
89
+ esac
90
+ done
91
+ printf '%s' "$out"
92
+ fi
93
+ }
94
+
95
+ # Check if a response body is a gateway interception form
96
+ is_gateway_form() {
97
+ grep -qF "$MARKER" "$1" 2>/dev/null && grep -q "_sm_ctn" "$1" 2>/dev/null
98
+ }
99
+
100
+ # Extract the value of a named form field
101
+ parse_form_field() {
102
+ sed -n "s/.*name=[\"']$2[\"'][^>]*value=[\"']\([^\"']*\)[\"'].*/\1/p" "$1" \
103
+ | head -n1 \
104
+ | sed -e 's/&amp;/\&/g' -e 's/&#38;/\&/g' -e 's/&#x26;/\&/g' -e 's/&#X26;/\&/g'
105
+ }
106
+
107
+ # Extract the form action URL
108
+ get_form_action() {
109
+ sed -n 's/.*<form[^>]*action="\(https:\/\/[^"]*\)".*/\1/p' "$1" | head -n1
110
+ }
111
+
112
+ # Submit the gateway form to obtain session cookies
113
+ submit_gateway_form() {
114
+ local response_file="$1"
115
+ local form_action sm_url sm_rid sm_cat query=""
116
+
117
+ log "Gateway form detected, extracting fields..."
118
+
119
+ form_action=$(get_form_action "$response_file")
120
+ sm_url=$(parse_form_field "$response_file" "_sm_url")
121
+ sm_rid=$(parse_form_field "$response_file" "_sm_rid")
122
+ sm_cat=$(parse_form_field "$response_file" "_sm_cat")
123
+
124
+ if [ -z "$form_action" ]; then
125
+ error "Could not extract gateway form action URL"
126
+ return 1
127
+ fi
128
+
129
+ [ -n "$sm_url" ] && query="${query}&_sm_url=$(urlencode "$sm_url")"
130
+ [ -n "$sm_rid" ] && query="${query}&_sm_rid=$(urlencode "$sm_rid")"
131
+ [ -n "$sm_cat" ] && query="${query}&_sm_cat=$(urlencode "$sm_cat")"
132
+ query="${query#&}"
133
+
134
+ log "Submitting gateway form to: ${form_action}?${query}"
135
+
136
+ if "$CURL_CMD" -L -sS -c "$COOKIE_FILE" -b "$COOKIE_FILE" \
137
+ -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) Chrome/120.0" \
138
+ -o /dev/null \
139
+ "${form_action}?${query}"; then
140
+ log "Gateway form submitted, cookies saved to: $COOKIE_FILE"
141
+ return 0
142
+ fi
143
+
144
+ error "Gateway form submission failed"
145
+ return 1
146
+ }
147
+
148
+ main() {
149
+ if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
150
+ if [ "$(basename "$0")" = "curl" ]; then
151
+ log "Detected invocation as 'curl', passing through to real curl"
152
+ exec "$CURL_CMD" "$@"
153
+ fi
154
+ usage
155
+ exit 0
156
+ fi
157
+
158
+ # Scan arguments: find the URL, the requested output file, and any option
159
+ # that makes body interception unsafe (in which case: pass through).
160
+ local args=("$@") probe_args=()
161
+ local url="" output_file="" passthrough=0 had_fail=0 url_count=0 has_ua=0 remote_name=0
162
+ local i=0 a cluster
163
+
164
+ log "Scanning arguments: ${args[*]}"
165
+
166
+ while [ $i -lt ${#args[@]} ]; do
167
+ a="${args[$i]}"
168
+ case "$a" in
169
+ -o | --output)
170
+ output_file="${args[$((i + 1))]}"
171
+ i=$((i + 1))
172
+ ;;
173
+ -f | --fail)
174
+ had_fail=1
175
+ ;;
176
+ -O | --remote-name)
177
+ # Save as the URL's own file name, same as real curl -O.
178
+ remote_name=1
179
+ ;;
180
+ -I | --head | --remote-name-all | -J | \
181
+ --remote-header-name | -D | --dump-header | -T | --upload-file | -w | --write-out | \
182
+ -K | --config | --output-dir | -Z | --parallel)
183
+ passthrough=1
184
+ probe_args+=("$a")
185
+ ;;
186
+ --url)
187
+ url="${args[$((i + 1))]}"
188
+ url_count=$((url_count + 1))
189
+ i=$((i + 1))
190
+ ;;
191
+ http://* | https://*)
192
+ [ -z "$url" ] && url="$a"
193
+ url_count=$((url_count + 1))
194
+ ;;
195
+ --*)
196
+ probe_args+=("$a")
197
+ ;;
198
+ -?*)
199
+ cluster="${a#-}"
200
+ if [[ "$cluster" =~ ^[sSfLkvigqnN460O#]*o?$ ]]; then
201
+ # Cluster of known boolean flags, optionally ending with -o <file>:
202
+ # strip -f/-O (re-applied on delivery) and split a trailing -o.
203
+ if [[ "$cluster" == *f* ]]; then
204
+ had_fail=1
205
+ cluster="${cluster//f/}"
206
+ fi
207
+ if [[ "$cluster" == *O* ]]; then
208
+ remote_name=1
209
+ cluster="${cluster//O/}"
210
+ fi
211
+ if [[ "$cluster" == *o ]]; then
212
+ cluster="${cluster%o}"
213
+ output_file="${args[$((i + 1))]}"
214
+ i=$((i + 1))
215
+ fi
216
+ [ -n "$cluster" ] && probe_args+=("-$cluster")
217
+ else
218
+ # Unknown cluster or option with attached value (e.g. -XPOST,
219
+ # -ofile): keep as-is, pass through if interception looks unsafe
220
+ [[ "$cluster" =~ [IJTZw] ]] && passthrough=1
221
+ probe_args+=("$a")
222
+ fi
223
+ ;;
224
+ *)
225
+ probe_args+=("$a")
226
+ ;;
227
+ esac
228
+ case "$a" in
229
+ -H | --header)
230
+ case "${args[$((i + 1))]}" in
231
+ [Uu]ser-[Aa]gent:*) has_ua=1 ;;
232
+ esac
233
+ ;;
234
+ -A | --user-agent) has_ua=1 ;;
235
+ esac
236
+ i=$((i + 1))
237
+ done
238
+
239
+ # Requests we cannot safely intercept are passed through unchanged
240
+ if [ "$passthrough" = "1" ] || [ -z "$url" ] || [ "$url_count" -gt 1 ]; then
241
+ log "Passing request through to $CURL_CMD"
242
+ exec "$CURL_CMD" "$@"
243
+ fi
244
+
245
+ # -O: derive the output file name from the URL itself, unless an
246
+ # explicit -o/--output already set one (explicit wins, like real curl).
247
+ if [ "$remote_name" = "1" ] && [ -z "$output_file" ]; then
248
+ output_file="${url%%[?#]*}"
249
+ output_file="${output_file##*/}"
250
+ if [ -z "$output_file" ]; then
251
+ error "Remote file name has no length"
252
+ exit 23
253
+ fi
254
+ fi
255
+
256
+ local temp_file peek_file rc http_code
257
+ temp_file=$(mktemp "${TMPDIR:-/tmp}/gateway-curl.XXXXXX") || exit 1
258
+ peek_file=$(mktemp "${TMPDIR:-/tmp}/gateway-curl.peek.XXXXXX") || exit 1
259
+ trap 'rm -f "$temp_file" "$peek_file"' EXIT
260
+
261
+ # Probe request: capture the body so a gateway form can be detected
262
+ local probe_extra=()
263
+ [ "$has_ua" = "0" ] && probe_extra+=(-H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) Chrome/120.0")
264
+
265
+ log "Fetching: $url"
266
+ http_code=$("$CURL_CMD" -c "$COOKIE_FILE" -b "$COOKIE_FILE" \
267
+ -o "$temp_file" -w '%{http_code}' \
268
+ "${probe_extra[@]}" "${probe_args[@]}" "$url")
269
+ rc=$?
270
+
271
+ # Some gateways intercept via an inline form in the body (caught above);
272
+ # others answer with a genuine redirect to the form instead. If the probe
273
+ # didn't already follow redirects (no -L/-L-implying flag from the
274
+ # caller) and came back as one, peek at where it leads before giving up —
275
+ # purely to detect a gateway form, without changing what gets delivered
276
+ # if it turns out to be an unrelated, legitimate redirect.
277
+ if [ $rc -eq 0 ] && ! is_gateway_form "$temp_file" && [ "${http_code:-0}" -ge 300 ] 2>/dev/null && [ "${http_code:-0}" -lt 400 ] 2>/dev/null; then
278
+ log "Redirect ($http_code) without an inline form, checking where it leads..."
279
+ if "$CURL_CMD" -s --location-trusted -c "$COOKIE_FILE" -b "$COOKIE_FILE" \
280
+ "${probe_extra[@]}" "${probe_args[@]}" -o "$peek_file" "$url" \
281
+ && is_gateway_form "$peek_file"; then
282
+ temp_file="$peek_file"
283
+ fi
284
+ fi
285
+
286
+ if [ $rc -eq 0 ] && is_gateway_form "$temp_file"; then
287
+ log "Gateway interception detected, processing..."
288
+ if submit_gateway_form "$temp_file"; then
289
+ log "Replaying original request with session cookies..."
290
+ "$CURL_CMD" -c "$COOKIE_FILE" -b "$COOKIE_FILE" "${args[@]}"
291
+ exit $?
292
+ fi
293
+ error "Failed to process gateway redirect, returning original response"
294
+ fi
295
+
296
+ # No gateway involved: deliver the response as the real curl would have
297
+ if [ "$had_fail" = "1" ] && [ "${http_code:-0}" -ge 400 ] 2>/dev/null; then
298
+ error "The requested URL returned error: $http_code"
299
+ exit 22
300
+ fi
301
+
302
+ if [ -n "$output_file" ] && [ "$output_file" != "-" ]; then
303
+ if mv "$temp_file" "$output_file"; then
304
+ trap - EXIT
305
+ else
306
+ exit $?
307
+ fi
308
+ else
309
+ cat "$temp_file"
310
+ fi
311
+ exit $rc
312
+ }
313
+
314
+ CURL_CMD=$(resolve_real_curl)
315
+ if [ -z "$CURL_CMD" ]; then
316
+ error "Could not find a real curl binary to wrap"
317
+ exit 127
318
+ fi
319
+ log "Using real curl: $CURL_CMD"
320
+
321
+ main "$@"
@@ -0,0 +1,35 @@
1
+ #!/bin/sh
2
+
3
+ # Mechanical CA install: copy *.pem from $1 into the system trust store and
4
+ # refresh it. No policy, no logging, no privilege handling — callers decide
5
+ # when/how/as-whom to invoke it. Runs unprivileged and privileged alike
6
+ # (image build stage, postCreateCommand via sudo, ...).
7
+ #
8
+ # Usage: install-certs-core.sh <certs_dir>
9
+ # Exit codes: 0 = nothing to do / up to date / installed, 1 = copy failed
10
+ #
11
+ # CERT_STORE_DIR overrides the trust store directory (default:
12
+ # /usr/local/share/ca-certificates) and UPDATE_CA_CMD overrides the refresh
13
+ # command (default: update-ca-certificates) — used by tests to avoid
14
+ # touching the real system trust store.
15
+
16
+ certs_dir="$1"
17
+ store_dir="${CERT_STORE_DIR:-/usr/local/share/ca-certificates}"
18
+ update_cmd="${UPDATE_CA_CMD:-update-ca-certificates}"
19
+ [ -n "$certs_dir" ] && [ -d "$certs_dir" ] || exit 0
20
+ command -v "$update_cmd" >/dev/null 2>&1 || exit 0
21
+
22
+ installed=0
23
+ for pem in "$certs_dir"/*.pem; do
24
+ [ -f "$pem" ] || continue
25
+ grep -q "BEGIN CERTIFICATE" "$pem" 2>/dev/null || continue
26
+
27
+ crt="$store_dir/$(basename "$pem" .pem).crt"
28
+ [ -f "$crt" ] && cmp -s "$pem" "$crt" && continue
29
+
30
+ cp "$pem" "$crt" || exit 1
31
+ installed=1
32
+ done
33
+
34
+ [ "$installed" = "1" ] && "$update_cmd" >/dev/null
35
+ exit 0
@@ -0,0 +1,40 @@
1
+ #!/bin/sh
2
+
3
+ # Mechanical gateway-curl install/divert steps. No policy, no logging, no
4
+ # privilege handling — callers decide bindir selection, whether to divert,
5
+ # and as-whom to invoke it (image build stage, postCreateCommand via sudo,
6
+ # host install, ...).
7
+ #
8
+ # Usage:
9
+ # install-curl-wrapper-core.sh install <wrapper_src> <bindir>
10
+ # install-curl-wrapper-core.sh divert <bindir>
11
+ #
12
+ # 'install' copies <wrapper_src> to <bindir>/gateway-curl.
13
+ # 'divert' points the system curl to <bindir>/gateway-curl, keeping the real
14
+ # binary at <curl_bin>.real. Idempotent: a no-op if already diverted.
15
+
16
+ mode="$1"
17
+
18
+ case "$mode" in
19
+ install)
20
+ src="$2"
21
+ bindir="$3"
22
+ [ -n "$src" ] && [ -n "$bindir" ] || exit 1
23
+ mkdir -p "$bindir" 2>/dev/null
24
+ cp "$src" "$bindir/gateway-curl" || exit 1
25
+ chmod 755 "$bindir/gateway-curl"
26
+ ;;
27
+ divert)
28
+ bindir="$2"
29
+ [ -n "$bindir" ] || exit 1
30
+ curl_bin=$(command -v curl 2>/dev/null || echo /usr/bin/curl)
31
+ [ -x "${curl_bin}.real" ] && exit 0
32
+ if [ -e "$curl_bin" ]; then
33
+ mv "$curl_bin" "${curl_bin}.real" || exit 1
34
+ fi
35
+ ln -sf "$bindir/gateway-curl" "$curl_bin"
36
+ ;;
37
+ *)
38
+ exit 1
39
+ ;;
40
+ esac
@@ -0,0 +1,24 @@
1
+ {
2
+ "build": {
3
+ "dockerfile": ".gateway/Dockerfile"
4
+ },
5
+ "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
6
+ "features": {
7
+ "ghcr.io/tomgrv/devcontainer-features/gateway:11": {}
8
+ },
9
+ "mounts": [
10
+ {
11
+ "source": "${localWorkspaceFolder}/.devcontainer/.gateway/certs",
12
+ "target": "/usr/local/share/gateway/certs",
13
+ "type": "bind"
14
+ }
15
+ ],
16
+ "remoteUser": "vscode",
17
+ "customizations": {
18
+ "vscode": {
19
+ "extensions": [
20
+ "ukoloff.win-ca"
21
+ ]
22
+ }
23
+ }
24
+ }