Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f79c64cd44 | |||
| 4972adb213 | |||
| 2c45b343c2 | |||
| 8e76caddb2 | |||
| 6f8d47a8de |
@@ -33,6 +33,11 @@ coverage.txt
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# VS Code extension build artifacts
|
||||
editors/vscode/node_modules/
|
||||
editors/vscode/out/
|
||||
editors/vscode/*.vsix
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
@@ -5,6 +5,38 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
This project uses [Semantic Versioning](https://semver.org).
|
||||
|
||||
## [0.2.31] - 2026-06-26
|
||||
|
||||
### Added
|
||||
|
||||
- **Proxy support** — `--proxy <URL>` flag on `glint check`, `glint graph`, and `glint lsp`; also configurable via `proxy:` in `.glint.yml`. When set it takes precedence over `HTTP_PROXY` / `HTTPS_PROXY` env vars; when unset, system proxy settings are honoured automatically. Covers all remote include fetches and GitLab API calls.
|
||||
|
||||
- **GL045: HTTP remote include warning** — new pipeline-level lint rule that warns when `include: remote:` uses a plain `http://` URL. CI templates fetched over unencrypted HTTP are at risk of in-transit tampering; `https://` is always preferred.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Path traversal in local includes** — `include: local:` paths containing `../` sequences that would escape the repository root (e.g. `../../etc/passwd`) are now rejected with a warning instead of reading arbitrary files from the host.
|
||||
|
||||
- **HTTP timeout on remote fetches** — all HTTP calls in `internal/fetcher` now use a 30-second timeout; previously the client had no timeout and could hang indefinitely on slow or unresponsive servers.
|
||||
|
||||
- **Unbounded response size** — remote include and GitLab API responses are now capped at 10 MiB using `io.LimitReader`; previously an arbitrarily large response could exhaust process memory.
|
||||
|
||||
- **Cache file permissions** — the cache directory is created with mode `0700` (was `0755`) and cache files with `0600` (was `0644`), preventing other local users from reading cached GitLab tokens or pipeline content.
|
||||
|
||||
- **LSP Content-Length DoS** — `glint lsp` now rejects incoming messages whose `Content-Length` header exceeds 64 MiB, preventing memory exhaustion from a malicious or misbehaving LSP client.
|
||||
|
||||
## [0.2.30] - 2026-06-26
|
||||
|
||||
### Added
|
||||
|
||||
- **VS Code extension** (`editors/vscode/`) — TypeScript extension that starts `glint lsp` as a language server and connects to it via `vscode-languageclient`. Activates on YAML files; the `documentSelector` restricts LSP processing to `**/.gitlab-ci.yml` so other YAML files are unaffected. Inline error/warning squiggles appear on every save or edit. The `glint.executablePath` setting controls the binary path (default: `glint` on `PATH`). Build: `task ext-compile`; package as `.vsix`: `task ext-package`.
|
||||
|
||||
## [0.2.29] - 2026-06-26
|
||||
|
||||
### Added
|
||||
|
||||
- **LSP server** (`glint lsp`) — new `internal/lsp` package and `glint lsp` subcommand that starts a Language Server Protocol server over stdin/stdout using Content-Length–framed JSON-RPC 2.0. Editors (VS Code, Neovim, Emacs, JetBrains, etc.) can connect with any generic LSP client configuration. Supported methods: `initialize`, `initialized`, `shutdown`, `exit`, `textDocument/didOpen`, `textDocument/didChange`, `textDocument/didSave`, `textDocument/didClose`. On every document open or change the server runs the full glint lint pipeline and publishes diagnostics via `textDocument/publishDiagnostics`; each diagnostic carries the rule ID as its `code` field and `"glint"` as `source`. Parse errors are surfaced as an Error diagnostic at the top of the document. Include resolution is best-effort (uses `GITLAB_TOKEN` / `GITLAB_URL` env vars; default cache dir `~/.cache/glint`). CLI flags: `--token`, `--gitlab-url`, `--cache-dir`, `--offline`.
|
||||
|
||||
## [0.2.28] - 2026-06-26
|
||||
|
||||
### Added
|
||||
|
||||
+8
-2
@@ -7,7 +7,7 @@ For planned work see [ROADMAP.md](ROADMAP.md).
|
||||
|
||||
## Lint rules
|
||||
|
||||
Every finding carries a stable rule ID (`GL001` – `GL043`) that can be used to
|
||||
Every finding carries a stable rule ID (`GL001` – `GL045`) that can be used to
|
||||
suppress, filter, or look up the check. Run `glint explain <ID>` for a
|
||||
description, bad-YAML example, and fix.
|
||||
|
||||
@@ -19,6 +19,7 @@ description, bad-YAML example, and fix.
|
||||
| GL002 | ERR | `workflow.rules[*].when` must be `always` or `never` |
|
||||
| GL036 | ERR | `default.timeout` is not a valid GitLab CI duration string |
|
||||
| GL040 | WARN | A stage name appears more than once in `stages:` |
|
||||
| GL045 | WARN | `include: remote:` uses plain `http://` — CI templates fetched unencrypted; prefer `https://` |
|
||||
|
||||
### Job structure
|
||||
|
||||
@@ -243,9 +244,14 @@ url: https://gitlab.example.com
|
||||
|
||||
# Default cache directory.
|
||||
cache_dir: ~/.cache/glint
|
||||
|
||||
# HTTP proxy for remote includes and GitLab API calls.
|
||||
# Overrides HTTP_PROXY / HTTPS_PROXY env vars when set.
|
||||
# Leave empty to use system proxy settings.
|
||||
proxy: http://proxy.example.com:8080
|
||||
```
|
||||
|
||||
**Priority chain:** `--token`/`--gitlab-url` flags > `.glint.yml` > environment variables.
|
||||
**Priority chain:** `--token`/`--gitlab-url`/`--proxy` flags > `.glint.yml` > environment variables.
|
||||
|
||||
### Inline suppression (`# glint: ignore`)
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="License"></a>
|
||||
<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/release-v0.2.28-blue.svg" alt="Release"></a>
|
||||
<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/release-v0.2.31-blue.svg" alt="Release"></a>
|
||||
</p>
|
||||
|
||||
> **Disclaimer:** This tool was built through iterative AI-assisted development with [Claude](https://claude.ai). It is experimental, incomplete, and not intended for production use. Coverage of GitLab CI keywords is best-effort and may lag behind GitLab's evolving spec. Use it at your own discretion — no correctness guarantees are made. Contributions and bug reports are welcome.
|
||||
@@ -15,12 +15,14 @@ A local tool to validate and lint `.gitlab-ci.yml` pipelines without needing a G
|
||||
|
||||
## What it does
|
||||
|
||||
- **Lints** — 43 rules covering pipeline structure, keyword constraints, `needs:`/`dependencies:` graphs, expression reachability, and deprecations (GL001–GL043); run `glint explain <ID>` for any rule
|
||||
- **Resolves includes** — local files, HTTPS URLs, GitLab project templates, and CI/CD Catalog components, with offline cache support
|
||||
- **Lints** — 45 rules covering pipeline structure, keyword constraints, `needs:`/`dependencies:` graphs, expression reachability, and deprecations (GL001–GL045); run `glint explain <ID>` for any rule
|
||||
- **Resolves includes** — local files, HTTPS URLs, GitLab project templates, and CI/CD Catalog components, with offline cache support and HTTP proxy support (`--proxy` flag or `proxy:` in `.glint.yml`)
|
||||
- **Simulates context** — `--branch`, `--tag`, `--source` flags evaluate `rules:if:` and `only`/`except` to show which jobs would be active, manual, or skipped; `--context branch=main --context branch=develop` prints a multi-column comparison table across multiple contexts in one run
|
||||
- **Multiple output formats** — `--format text` (default, ruff-style), `json`, `sarif` (GitHub Code Scanning / GitLab SAST), `junit`, `github` (PR annotations)
|
||||
- **Project config** — `.glint.yml` for rule suppression, severity overrides, token/URL defaults; `# glint: ignore RULE` for per-job inline suppression
|
||||
- **Project config** — `.glint.yml` for rule suppression, severity overrides, token/URL/proxy defaults; `# glint: ignore RULE` for per-job inline suppression
|
||||
- **Graph visualization** — `glint graph` prints a terminal job tree; `glint graph pipeline` renders a GitLab CI-style SVG/PNG; `--format mermaid` emits a Mermaid flowchart; `--format html` produces a self-contained HTML file with pan/zoom and a job-detail sidebar; context flags grey out skipped jobs
|
||||
- **LSP server** — `glint lsp` starts a Language Server Protocol server over stdin/stdout; connect with any LSP client to get inline diagnostics (rule ID as code, error/warning severity) in VS Code, Neovim, Emacs, JetBrains, etc.
|
||||
- **VS Code extension** — `editors/vscode/` wraps the LSP server; inline squiggles for every glint rule directly in the editor
|
||||
|
||||
See [FEATURES.md](FEATURES.md) for the complete feature reference and lint rules table, and [ROADMAP.md](ROADMAP.md) for planned improvements.
|
||||
|
||||
@@ -52,6 +54,7 @@ Commands:
|
||||
check Lint a pipeline file — exits 0 (clean) or 1 (errors found)
|
||||
graph Visualise the pipeline as a job tree or Mermaid graph
|
||||
explain Print description and fix for a lint rule
|
||||
lsp Start a Language Server Protocol server (stdin/stdout)
|
||||
```
|
||||
|
||||
Run `glint <command> --help` for all flags. See [USAGE.md](USAGE.md) for full
|
||||
@@ -106,6 +109,27 @@ Copy [`action.yml`](action.yml) from this repository, or mirror this repo to Git
|
||||
|
||||
The action downloads the glint Linux binary into `$RUNNER_TEMP` and runs `glint check`. Only Linux runners are supported (matches the available release binary).
|
||||
|
||||
### VS Code extension
|
||||
|
||||
Clone this repository and load the extension from `editors/vscode/`:
|
||||
|
||||
```bash
|
||||
cd editors/vscode
|
||||
npm install # install dependencies (once)
|
||||
npm run compile # compile TypeScript → out/
|
||||
```
|
||||
|
||||
Then in VS Code: **Run → Start Debugging** (F5) — this opens an Extension Development Host with glint diagnostics active for any `.gitlab-ci.yml` you open.
|
||||
|
||||
Make sure `glint` is on your `PATH`, or set `glint.executablePath` in VS Code settings to the full path of the binary.
|
||||
|
||||
To package a `.vsix` for local installation:
|
||||
|
||||
```bash
|
||||
task ext-package # produces glint-X.Y.Z.vsix
|
||||
code --install-extension glint-X.Y.Z.vsix
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
This project uses [Task](https://taskfile.dev) as a task runner.
|
||||
@@ -120,6 +144,9 @@ task ci # full check: vet → test → build → validate
|
||||
task fuzz # run fuzz tests for the YAML parser (Ctrl-C to stop; FUZZ_TIME=60s to set duration)
|
||||
task changelog # regenerate CHANGELOG.md from git history via git-cliff
|
||||
task changelog-next # preview unreleased section (dry-run, no file written)
|
||||
task ext-install # install VS Code extension npm dependencies
|
||||
task ext-compile # compile the VS Code extension TypeScript source
|
||||
task ext-package # package the VS Code extension as a .vsix
|
||||
task build-windows # cross-compile for Windows x64 (requires a tagged commit → glint-<tag>.exe)
|
||||
task build-linux # cross-compile for Linux x64 (requires a tagged commit → glint-<tag>-linux-amd64)
|
||||
task clean # remove build artifacts
|
||||
|
||||
+80
-72
@@ -8,23 +8,23 @@ This document tracks planned improvements to `glint`. Items are grouped by theme
|
||||
|
||||
Pass `--branch`, `--tag`, `--source`, or `--var` to `glint check` or `glint graph` to evaluate `rules:if:` expressions and `only`/`except` filters against a specific pipeline event.
|
||||
|
||||
- ~~**Single-context simulation**~~ — ✓ shipped v0.2.0; `--branch`, `--tag`, `--source`, `--var` flags on both subcommands; jobs classified as active / manual / skipped
|
||||
- ~~**`workflow:rules:variables:` propagation**~~ — ✓ shipped post-v0.2.0; variables from the matching workflow rule entry injected into the evaluation context before job `rules:if:` expressions are evaluated
|
||||
- ~~**Expression evaluator: multi-line `if:` values**~~ — ✓ shipped post-v0.2.0; newlines in block-scalar and folded YAML `if:` values treated as whitespace
|
||||
- ~~**Expression evaluator: `${VAR}` syntax**~~ — ✓ shipped post-v0.2.0; `${CI_COMMIT_BRANCH}` equivalent to `$CI_COMMIT_BRANCH` everywhere
|
||||
- ~~**Expression evaluator: regex flags**~~ — ✓ shipped post-v0.2.0; `/pattern/i`, `/pattern/m`, `/pattern/s` supported
|
||||
- ~~**Expression evaluator: variable as regex RHS**~~ — ✓ shipped post-v0.2.0; `$BRANCH =~ $PATTERN` where `$PATTERN` holds a `/regex/` string evaluates correctly
|
||||
- ~~**Expression evaluator: bare `true`/`false` and integer literals**~~ — ✓ shipped post-v0.2.0; `$FLAG == true`, `$COUNT == 4` compare as decimal strings matching GitLab CI behaviour
|
||||
- ~~**Implicit default context**~~ — ✓ shipped v0.2.11; defaults to `--branch main --source push` when no context flag is given, so `rules:if:` is always evaluated
|
||||
- ~~**`--list-vars` debug flag**~~ — ✓ shipped v0.2.11; prints sorted `KEY=VALUE` of all collected pipeline variables (root file + includes + workflow-rule union + effective context) to stderr
|
||||
- ~~**Variable expansion**~~ — ✓ shipped v0.2.13; `$VAR`/`${VAR}` references within variable values expanded after all sources are merged; transitive chains resolved; visible in `--list-vars`
|
||||
- ~~**Non-string scalar variables**~~ — ✓ shipped v0.2.13; `BUILD: true`, `RETRIES: 3` rendered and injected correctly instead of being silently dropped
|
||||
- ~~**YAML `\/` escape in double-quoted strings**~~ — ✓ shipped v0.2.13; regex patterns like `/^us\//` in double-quoted `if:` blocks no longer cause a parse error
|
||||
- ~~**Workflow rule strict evaluation**~~ — ✓ shipped v0.2.14; unparseable `if:` skips the rule instead of matching everything; prevents wrong variables being injected
|
||||
- ~~**Single `=` operator**~~ — ✓ shipped v0.2.14; bare `=` accepted as alias for `==` in `rules:if:` expressions
|
||||
- ~~**`rules:changes:` evaluation**~~ — ✓ shipped v0.2.21; `--changes PATH` and `--changes-from REF` flags; doublestar glob matching (`*` within segment, `**` across segments); permissive when no file list provided
|
||||
- ~~**Multi-context simulation**~~ — ✓ shipped v0.2.22; `--context KEY=VALUE[,...]`; repeatable; prints a comparison table of `active`/`manual`/`skipped`/`blocked` per job across all contexts
|
||||
- ~~**Context-scoped linting**~~ — ✓ shipped v0.2.23; jobs evaluated as `JobSkipped` in the supplied context are excluded from `needs:`/`dependencies:` cross-checks (GL027–GL031) to eliminate false-positive errors for conditionally-gated jobs
|
||||
- [x] **Single-context simulation** — shipped v0.2.0; `--branch`, `--tag`, `--source`, `--var` flags on both subcommands; jobs classified as active / manual / skipped
|
||||
- [x] **`workflow:rules:variables:` propagation** — shipped post-v0.2.0; variables from the matching workflow rule entry injected into the evaluation context before job `rules:if:` expressions are evaluated
|
||||
- [x] **Expression evaluator: multi-line `if:` values** — shipped post-v0.2.0; newlines in block-scalar and folded YAML `if:` values treated as whitespace
|
||||
- [x] **Expression evaluator: `${VAR}` syntax** — shipped post-v0.2.0; `${CI_COMMIT_BRANCH}` equivalent to `$CI_COMMIT_BRANCH` everywhere
|
||||
- [x] **Expression evaluator: regex flags** — shipped post-v0.2.0; `/pattern/i`, `/pattern/m`, `/pattern/s` supported
|
||||
- [x] **Expression evaluator: variable as regex RHS** — shipped post-v0.2.0; `$BRANCH =~ $PATTERN` where `$PATTERN` holds a `/regex/` string evaluates correctly
|
||||
- [x] **Expression evaluator: bare `true`/`false` and integer literals** — shipped post-v0.2.0; `$FLAG == true`, `$COUNT == 4` compare as decimal strings matching GitLab CI behaviour
|
||||
- [x] **Implicit default context** — shipped v0.2.11; defaults to `--branch main --source push` when no context flag is given, so `rules:if:` is always evaluated
|
||||
- [x] **`--list-vars` debug flag** — shipped v0.2.11; prints sorted `KEY=VALUE` of all collected pipeline variables (root file + includes + workflow-rule union + effective context) to stderr
|
||||
- [x] **Variable expansion** — shipped v0.2.13; `$VAR`/`${VAR}` references within variable values expanded after all sources are merged; transitive chains resolved; visible in `--list-vars`
|
||||
- [x] **Non-string scalar variables** — shipped v0.2.13; `BUILD: true`, `RETRIES: 3` rendered and injected correctly instead of being silently dropped
|
||||
- [x] **YAML `\/` escape in double-quoted strings** — shipped v0.2.13; regex patterns like `/^us\//` in double-quoted `if:` blocks no longer cause a parse error
|
||||
- [x] **Workflow rule strict evaluation** — shipped v0.2.14; unparseable `if:` skips the rule instead of matching everything; prevents wrong variables being injected
|
||||
- [x] **Single `=` operator** — shipped v0.2.14; bare `=` accepted as alias for `==` in `rules:if:` expressions
|
||||
- [x] **`rules:changes:` evaluation** — shipped v0.2.21; `--changes PATH` and `--changes-from REF` flags; doublestar glob matching (`*` within segment, `**` across segments); permissive when no file list provided
|
||||
- [x] **Multi-context simulation** — shipped v0.2.22; `--context KEY=VALUE[,...]`; repeatable; prints a comparison table of `active`/`manual`/`skipped`/`blocked` per job across all contexts
|
||||
- [x] **Context-scoped linting** — shipped v0.2.23; jobs evaluated as `JobSkipped` in the supplied context are excluded from `needs:`/`dependencies:` cross-checks (GL027–GL031) to eliminate false-positive errors for conditionally-gated jobs
|
||||
|
||||
---
|
||||
|
||||
@@ -32,36 +32,36 @@ Pass `--branch`, `--tag`, `--source`, or `--var` to `glint check` or `glint grap
|
||||
|
||||
The current rule set covers the most common sources of broken pipelines. These are the gaps most likely to matter in practice.
|
||||
|
||||
- ~~**Variable reference validation (GL032)**~~ — ✓ shipped v0.2.11; warns when a `rules:if:` expression references `$VAR` / `${VAR}` not declared anywhere in pipeline YAML; predefined GitLab namespaces (`CI_*`, `GITLAB_*`, …) exempt; variables from included files are also considered
|
||||
- ~~**`rules:if:` static reachability (GL033)**~~ — ✓ shipped v0.2.15; warns when every rule in a job's `rules:` block has `when: never`, making the job permanently excluded from any pipeline run; no `if:` evaluation required
|
||||
- ~~**`services:` validation (GL034)**~~ — ✓ shipped v0.2.16; map form requires `name`; `alias` must be a valid DNS label
|
||||
- ~~**`rules:changes` / `rules:exists` absolute path detection (GL035)**~~ — ✓ shipped v0.2.16; warns when a path starts with `/`; GitLab CI paths are always relative to the repo root
|
||||
- ~~**`timeout` format validation (GL036)**~~ — ✓ shipped v0.2.16; validates job-level and `default.timeout` against recognised GitLab CI duration strings
|
||||
- ~~**`id_tokens:` / `secrets:` required-key checks (GL037, GL038)**~~ — ✓ shipped v0.2.16; `id_tokens` entries must have `aud`; `secrets` entries must declare a provider
|
||||
- ~~**`pages:publish` + `artifacts.paths` consistency (GL039)**~~ — ✓ shipped v0.2.16; warns when the publish directory is missing from `artifacts.paths`
|
||||
- ~~**Duplicate stage names (GL040)**~~ — ✓ shipped v0.2.16; warns when a stage appears more than once in `stages:`
|
||||
- ~~**`cache:key:files` must be exact paths (GL041)**~~ — ✓ shipped v0.2.16; warns when entries look like glob patterns
|
||||
- ~~**Unreachable jobs**~~ — covered by GL033 (shipped v0.2.15); every-`when:never` rules block is statically dead
|
||||
- ~~**`inherit:` completeness (GL043)**~~ — ✓ shipped v0.2.20; warns when `inherit: default:` is declared but there's no `default:` block, or list form names fields not set in `default:`
|
||||
- [x] **Variable reference validation (GL032)** — shipped v0.2.11; warns when a `rules:if:` expression references `$VAR` / `${VAR}` not declared anywhere in pipeline YAML; predefined GitLab namespaces (`CI_*`, `GITLAB_*`, …) exempt; variables from included files are also considered
|
||||
- [x] **`rules:if:` static reachability (GL033)** — shipped v0.2.15; warns when every rule in a job's `rules:` block has `when: never`, making the job permanently excluded from any pipeline run; no `if:` evaluation required
|
||||
- [x] **`services:` validation (GL034)** — shipped v0.2.16; map form requires `name`; `alias` must be a valid DNS label
|
||||
- [x] **`rules:changes` / `rules:exists` absolute path detection (GL035)** — shipped v0.2.16; warns when a path starts with `/`; GitLab CI paths are always relative to the repo root
|
||||
- [x] **`timeout` format validation (GL036)** — shipped v0.2.16; validates job-level and `default.timeout` against recognised GitLab CI duration strings
|
||||
- [x] **`id_tokens:` / `secrets:` required-key checks (GL037, GL038)** — shipped v0.2.16; `id_tokens` entries must have `aud`; `secrets` entries must declare a provider
|
||||
- [x] **`pages:publish` + `artifacts.paths` consistency (GL039)** — shipped v0.2.16; warns when the publish directory is missing from `artifacts.paths`
|
||||
- [x] **Duplicate stage names (GL040)** — shipped v0.2.16; warns when a stage appears more than once in `stages:`
|
||||
- [x] **`cache:key:files` must be exact paths (GL041)** — shipped v0.2.16; warns when entries look like glob patterns
|
||||
- [x] **Unreachable jobs** — covered by GL033 (shipped v0.2.15); every-`when:never` rules block is statically dead
|
||||
- [x] **`inherit:` completeness (GL043)** — shipped v0.2.20; warns when `inherit: default:` is declared but there's no `default:` block, or list form names fields not set in `default:`
|
||||
|
||||
---
|
||||
|
||||
## Include resolution
|
||||
|
||||
- ~~**`include: local:`** full resolution~~ — ✓ shipped in v0.2.0; local files are read from disk, recursively resolved, and merged before linting
|
||||
- ~~**`include: remote:`** (URL)~~ — ✓ shipped post-v0.2.0; plain HTTPS URLs are fetched (unauthenticated), parsed, and merged; sub-includes are resolved recursively; unreachable URLs emit `[WARNING]` and linting continues
|
||||
- ~~**Recursive include depth limit**~~ — ✓ shipped v0.2.17; depth capped at 100 (matching GitLab); project/component includes now tracked in visited set to prevent cross-file cycles
|
||||
- ~~**Offline mode / cache**~~ — ✓ shipped v0.2.17; `--cache-dir DIR` persists fetched templates; `--offline` serves from cache only; default cache dir (`~/.cache/glint`) used automatically with `--offline`
|
||||
- ~~**`include: inputs:`**~~ — ✓ shipped v0.2.17; `$[[ inputs.KEY ]]` and `$[[ inputs.KEY | default(…) ]]` placeholders in fetched component YAML are substituted from the include's `with:` block before parsing
|
||||
- [x] **`include: local:` full resolution** — shipped v0.2.0; local files are read from disk, recursively resolved, and merged before linting
|
||||
- [x] **`include: remote:` (URL)** — shipped post-v0.2.0; plain HTTPS URLs are fetched (unauthenticated), parsed, and merged; sub-includes are resolved recursively; unreachable URLs emit `[WARNING]` and linting continues
|
||||
- [x] **Recursive include depth limit** — shipped v0.2.17; depth capped at 100 (matching GitLab); project/component includes now tracked in visited set to prevent cross-file cycles
|
||||
- [x] **Offline mode / cache** — shipped v0.2.17; `--cache-dir DIR` persists fetched templates; `--offline` serves from cache only; default cache dir (`~/.cache/glint`) used automatically with `--offline`
|
||||
- [x] **`include: inputs:`** — shipped v0.2.17; `$[[ inputs.KEY ]]` and `$[[ inputs.KEY | default(…) ]]` placeholders in fetched component YAML are substituted from the include's `with:` block before parsing
|
||||
|
||||
---
|
||||
|
||||
## Output formats — ✓ shipped v0.2.18
|
||||
## Output formats
|
||||
|
||||
- ~~**JSON** (`--format json`)~~ — ✓ shipped v0.2.18; machine-readable findings with stable schema (version 1)
|
||||
- ~~**SARIF** (`--format sarif`)~~ — ✓ shipped v0.2.18; SARIF 2.1.0; consumed natively by GitHub Code Scanning and GitLab SAST
|
||||
- ~~**JUnit XML** (`--format junit`)~~ — ✓ shipped v0.2.18; lets CI pipelines publish lint results as a test report artifact
|
||||
- ~~**GitHub annotation format** (`--format github`)~~ — ✓ shipped v0.2.18; emits `::error file=…,line=…,title=RULE::message` lines so findings appear as inline comments in PR diffs
|
||||
- [x] **JSON** (`--format json`) — shipped v0.2.18; machine-readable findings with stable schema (version 1)
|
||||
- [x] **SARIF** (`--format sarif`) — shipped v0.2.18; SARIF 2.1.0; consumed natively by GitHub Code Scanning and GitLab SAST
|
||||
- [x] **JUnit XML** (`--format junit`) — shipped v0.2.18; lets CI pipelines publish lint results as a test report artifact
|
||||
- [x] **GitHub annotation format** (`--format github`) — shipped v0.2.18; emits `::error file=…,line=…,title=RULE::message` lines so findings appear as inline comments in PR diffs
|
||||
|
||||
---
|
||||
|
||||
@@ -69,55 +69,63 @@ The current rule set covers the most common sources of broken pipelines. These a
|
||||
|
||||
The SVG renderer and terminal tree cover the basic layout. These would bring it closer to GitLab's full interactive view.
|
||||
|
||||
- ~~**Terminal job tree**~~ — ✓ shipped in v0.2.0 as `glint graph tree`; stages as branches, jobs as leaves, context-aware annotations
|
||||
- ~~**`glint graph includes` shows jobs per file**~~ — ✓ shipped post-v0.2.0; each include node shows the jobs it defines as dashed-arrow rounded nodes in a distinct style
|
||||
- ~~**Multi-job connector accuracy**~~ — ✓ shipped v0.2.25; classic mode uses a bus-bar pattern (vertical rail at the midpoint + horizontal stubs per job) instead of a single center-to-center line, so uneven columns look correct
|
||||
- ~~**Job tooltip / detail panel**~~ — ✓ shipped v0.2.25; each chip is wrapped in `<g data-job="…"><title>…</title><desc>…</desc>` — SVG viewers show stage, when, image, and needs on hover; HTML output uses the data for the sidebar
|
||||
- ~~**`when: on_failure` visual distinction**~~ — ✓ shipped v0.2.25; dashed chip border + X-mark icon + red circle (`#d9534f`); legend entry added; Mermaid `on_failure` class wired
|
||||
- ~~**Blocked / skipped state colouring**~~ — ✓ shipped v0.2.25; `glint graph pipeline` accepts context flags (`--branch`, `--tag`, etc.); jobs evaluated as skipped are greyed out (`#868686`) with dimmed text and no icon
|
||||
- ~~**Interactive HTML output**~~ — ✓ shipped v0.2.25; `glint graph pipeline --format html` writes a self-contained `.html` file with mouse pan/zoom and a click-to-open job-detail sidebar; no external dependencies
|
||||
- ~~**Mermaid pipeline output**~~ — ✓ shipped v0.2.25; `glint graph pipeline --format mermaid` prints a Mermaid flowchart to stdout (paste into mermaid.live)
|
||||
- ~~**Same-stage job ordering**~~ — ✓ shipped v0.2.26; jobs within a stage that have `needs:` between each other are placed in topological sub-columns (left-to-right by depth); stage header spans all sub-columns
|
||||
- ~~**Graph links rendered behind job chips**~~ — ✓ shipped v0.2.26; SVG connectors (Bézier curves and bus-bar stubs) are drawn before job chips so lines pass behind rectangles
|
||||
- [x] **Terminal job tree** — shipped v0.2.0 as `glint graph tree`; stages as branches, jobs as leaves, context-aware annotations
|
||||
- [x] **`glint graph includes` shows jobs per file** — shipped post-v0.2.0; each include node shows the jobs it defines as dashed-arrow rounded nodes in a distinct style
|
||||
- [x] **Multi-job connector accuracy** — shipped v0.2.25; classic mode uses a bus-bar pattern (vertical rail at the midpoint + horizontal stubs per job) instead of a single center-to-center line, so uneven columns look correct
|
||||
- [x] **Job tooltip / detail panel** — shipped v0.2.25; each chip is wrapped in `<g data-job="…"><title>…</title><desc>…</desc>` — SVG viewers show stage, when, image, and needs on hover; HTML output uses the data for the sidebar
|
||||
- [x] **`when: on_failure` visual distinction** — shipped v0.2.25; dashed chip border + X-mark icon + red circle (`#d9534f`); legend entry added; Mermaid `on_failure` class wired
|
||||
- [x] **Blocked / skipped state colouring** — shipped v0.2.25; `glint graph pipeline` accepts context flags (`--branch`, `--tag`, etc.); jobs evaluated as skipped are greyed out (`#868686`) with dimmed text and no icon
|
||||
- [x] **Interactive HTML output** — shipped v0.2.25; `glint graph pipeline --format html` writes a self-contained `.html` file with mouse pan/zoom and a click-to-open job-detail sidebar; no external dependencies
|
||||
- [x] **Mermaid pipeline output** — shipped v0.2.25; `glint graph pipeline --format mermaid` prints a Mermaid flowchart to stdout (paste into mermaid.live)
|
||||
- [x] **Same-stage job ordering** — shipped v0.2.26; jobs within a stage that have `needs:` between each other are placed in topological sub-columns (left-to-right by depth); stage header spans all sub-columns
|
||||
- [x] **Graph links rendered behind job chips** — shipped v0.2.26; SVG connectors (Bézier curves and bus-bar stubs) are drawn before job chips so lines pass behind rectangles
|
||||
|
||||
---
|
||||
|
||||
## Findings quality — ✓ file and line numbers shipped post-v0.2.0; ruff-style format shipped v0.2.11
|
||||
## Findings quality
|
||||
|
||||
~~**File and line numbers on findings**~~ — ✓ shipped post-v0.2.0; every finding includes the source file and exact line of the job key. Works across local includes, remote project templates, and fetched component templates.
|
||||
|
||||
~~**Ruff-style output format**~~ — ✓ shipped v0.2.11; findings follow `file:line: RULEID [severity] message` matching the convention used by ruff and other modern linters.
|
||||
|
||||
**Remaining improvements**
|
||||
|
||||
- ~~**`needs: optional: true` false-positive errors**~~ — ✓ shipped post-v0.2.0; optional missing needs are downgraded to `[WARNING]`
|
||||
- ~~**`extends:` jobs with missing script false errors**~~ — ✓ shipped post-v0.2.0; jobs using `extends:` that have no `script` after resolution emit `[WARNING]` (the script may come from an unfetchable remote base)
|
||||
- ~~**`rules:if:` static reachability (GL042)**~~ — ✓ shipped v0.2.20; warns when all `rules:if:` conditions evaluate to false given declared variable values (only fires when all referenced vars are declared in YAML)
|
||||
- [x] **File and line numbers on findings** — shipped post-v0.2.0; every finding includes the source file and exact line of the job key; works across local includes, remote project templates, and fetched component templates
|
||||
- [x] **Ruff-style output format** — shipped v0.2.11; findings follow `file:line: RULEID [severity] message` matching the convention used by ruff and other modern linters
|
||||
- [x] **`needs: optional: true` false-positive errors** — shipped post-v0.2.0; optional missing needs are downgraded to `[WARNING]`
|
||||
- [x] **`extends:` jobs with missing script false errors** — shipped post-v0.2.0; jobs using `extends:` that have no `script` after resolution emit `[WARNING]` (the script may come from an unfetchable remote base)
|
||||
- [x] **`rules:if:` static reachability (GL042)** — shipped v0.2.20; warns when all `rules:if:` conditions evaluate to false given declared variable values (only fires when all referenced vars are declared in YAML)
|
||||
|
||||
---
|
||||
|
||||
## CI / editor integration
|
||||
|
||||
- ~~**GitLab CI template**~~ — ✓ shipped v0.2.28; `templates/check.yml` is a GitLab CI/CD Catalog component with `spec:` inputs for stage, file, version, allow_failure, and extra args; also usable as a plain local/remote include
|
||||
- ~~**GitHub Actions action**~~ — ✓ shipped v0.2.28; `action.yml` composite action downloads the glint Linux binary and runs `glint check`; mirror to GitHub as `k3nny/glint` to reference as `uses: k3nny/glint@v0.2.28`
|
||||
- ~~**Pre-commit hook**~~ — ✓ shipped v0.2.28; `.pre-commit-hooks.yaml` defines `language: golang` hook; pre-commit builds glint from source on first run and re-runs on staged `.gitlab-ci.yml` changes
|
||||
- **LSP server** — `glint lsp` mode exposing diagnostics over the Language Server Protocol; enables inline squiggles in VS Code, JetBrains, Neovim, etc. without a dedicated extension
|
||||
- **VS Code extension** — thin wrapper around the LSP server with syntax highlighting for `.gitlab-ci.yml`
|
||||
- [x] **GitLab CI template** — shipped v0.2.28; `templates/check.yml` is a GitLab CI/CD Catalog component with `spec:` inputs for stage, file, version, allow_failure, and extra args; also usable as a plain local/remote include
|
||||
- [x] **GitHub Actions action** — shipped v0.2.28; `action.yml` composite action downloads the glint Linux binary and runs `glint check`; mirror to GitHub as `k3nny/glint` to reference as `uses: k3nny/glint@v0.2.28`
|
||||
- [x] **Pre-commit hook** — shipped v0.2.28; `.pre-commit-hooks.yaml` defines `language: golang` hook; pre-commit builds glint from source on first run and re-runs on staged `.gitlab-ci.yml` changes
|
||||
- [x] **LSP server** — shipped v0.2.29; `glint lsp` runs a JSON-RPC 2.0 LSP server over stdin/stdout; `textDocument/didOpen`, `didChange`, `didSave`, `didClose` all publish diagnostics; rule IDs appear as the diagnostic `code`; include resolution is best-effort using env-var token and default cache dir
|
||||
- [x] **VS Code extension** — shipped v0.2.30; `editors/vscode/` TypeScript extension wraps `glint lsp` via `vscode-languageclient`; activates on YAML files and restricts LSP processing to `**/.gitlab-ci.yml`; configurable binary path via `glint.executablePath`; build with `task ext-compile`, package with `task ext-package`
|
||||
|
||||
---
|
||||
|
||||
## Configuration — ✓ shipped v0.2.19
|
||||
## Configuration
|
||||
|
||||
- ~~**`.glint.yml` config file**~~ — ✓ shipped v0.2.19; `ignore:`, `severity:`, `stages:`, `token:`, `url:`, `cache_dir:`; searched from the pipeline directory up to the git root
|
||||
- ~~**Inline suppression comments**~~ — ✓ shipped v0.2.19; `# glint: ignore GL007` before a job definition; comma/space-separated rules; `# glint: ignore all` wildcard
|
||||
- [x] **`.glint.yml` config file** — shipped v0.2.19; `ignore:`, `severity:`, `stages:`, `token:`, `url:`, `cache_dir:`; searched from the pipeline directory up to the git root
|
||||
- [x] **Inline suppression comments** — shipped v0.2.19; `# glint: ignore GL007` before a job definition; comma/space-separated rules; `# glint: ignore all` wildcard
|
||||
- [x] **Proxy support** — shipped v0.2.31; `--proxy` flag on `check`, `graph`, and `lsp` subcommands; also configurable via `proxy:` in `.glint.yml`; overrides `HTTP_PROXY` / `HTTPS_PROXY` env vars when set
|
||||
|
||||
---
|
||||
|
||||
## Security & hardening
|
||||
|
||||
- [x] **Path traversal guard for local includes** — shipped v0.2.31; `include: local:` paths containing `../../` or similar sequences are rejected instead of reading files outside the repository root
|
||||
- [x] **HTTP timeout on remote fetches** — shipped v0.2.31; all HTTP calls via the fetcher use a 30-second timeout to prevent indefinite hangs on slow or unresponsive servers
|
||||
- [x] **Unbounded response size cap** — shipped v0.2.31; remote include and GitLab API responses are capped at 10 MiB; responses exceeding the limit are rejected to prevent memory exhaustion
|
||||
- [x] **Cache file permissions** — shipped v0.2.31; cache directories are created with mode `0700` and cache files with mode `0600`; previously used world-readable `0755`/`0644`
|
||||
- [x] **GL045: HTTP remote include warning** — shipped v0.2.31; warns when `include: remote:` uses a plain `http://` URL; CI templates fetched unencrypted are at risk of tampering
|
||||
- [x] **LSP Content-Length DoS cap** — shipped v0.2.31; `glint lsp` rejects messages with `Content-Length` exceeding 64 MiB to prevent memory exhaustion from a malicious client
|
||||
|
||||
---
|
||||
|
||||
## Reliability and developer experience
|
||||
|
||||
- ~~**Structured rule IDs**~~ — ✓ shipped post-v0.2.0; GL001–GL031 assigned; GL032 added v0.2.11; GL033 added v0.2.15; GL034–GL041 added v0.2.16; output formats (--format json/sarif/junit/github) added v0.2.18; GL042–GL043 added v0.2.20; GL044 added v0.2.24; graph improvements shipped v0.2.25–v0.2.26
|
||||
- ~~**`glint explain <rule-id>`**~~ — ✓ shipped v0.2.20; prints rule description, rationale, bad-YAML example, and fix; `glint explain` (no arg) lists all rules
|
||||
- ~~**Semantic versioning and first release**~~ — shipped as `v0.1.0` (2026-06-07)
|
||||
- ~~**Subcommand CLI**~~ — shipped as `v0.2.0` (2026-06-11); `glint check` / `glint graph [mode]` with ruff-style `--help`
|
||||
- ~~**Changelog automation**~~ — ✓ shipped v0.2.27; `cliff.toml` configures git-cliff to produce Keep-a-Changelog–compatible release notes from Conventional Commits; `task changelog` regenerates `CHANGELOG.md`, `task changelog-next` previews unreleased entries
|
||||
- ~~**Fuzz testing**~~ — ✓ shipped v0.2.27; `FuzzParseBytes` and `FuzzSanitizeYAMLEscapes` in `internal/model/fuzz_test.go`; seeds run as regular tests in CI; `task fuzz` runs them continuously (default 30 s)
|
||||
- [x] **Structured rule IDs** — shipped post-v0.2.0; GL001–GL031 assigned; GL032 added v0.2.11; GL033 added v0.2.15; GL034–GL041 added v0.2.16; output formats added v0.2.18; GL042–GL043 added v0.2.20; GL044 added v0.2.24; graph improvements shipped v0.2.25–v0.2.26
|
||||
- [x] **`glint explain <rule-id>`** — shipped v0.2.20; prints rule description, rationale, bad-YAML example, and fix; `glint explain` (no arg) lists all rules
|
||||
- [x] **Semantic versioning and first release** — shipped v0.1.0 (2026-06-07)
|
||||
- [x] **Subcommand CLI** — shipped v0.2.0 (2026-06-11); `glint check` / `glint graph [mode]` with ruff-style `--help`
|
||||
- [x] **Changelog automation** — shipped v0.2.27; `cliff.toml` configures git-cliff to produce Keep-a-Changelog–compatible release notes from Conventional Commits; `task changelog` regenerates `CHANGELOG.md`, `task changelog-next` previews unreleased entries
|
||||
- [x] **Fuzz testing** — shipped v0.2.27; `FuzzParseBytes` and `FuzzSanitizeYAMLEscapes` in `internal/model/fuzz_test.go`; seeds run as regular tests in CI; `task fuzz` runs them continuously (default 30 s)
|
||||
|
||||
@@ -123,6 +123,8 @@ tasks:
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} explain GL044
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check testdata/insecure_remote_include.yml
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} explain
|
||||
ignore_error: false
|
||||
|
||||
@@ -192,6 +194,22 @@ tasks:
|
||||
desc: "Preview unreleased changelog entries without writing (requires git-cliff)"
|
||||
cmd: git cliff --config cliff.toml --unreleased
|
||||
|
||||
ext-install:
|
||||
desc: Install VS Code extension npm dependencies (run once after checkout)
|
||||
dir: editors/vscode
|
||||
cmd: npm install
|
||||
|
||||
ext-compile:
|
||||
desc: Compile the VS Code extension TypeScript source
|
||||
dir: editors/vscode
|
||||
cmd: npm run compile
|
||||
|
||||
ext-package:
|
||||
desc: Package the VS Code extension into a .vsix file
|
||||
dir: editors/vscode
|
||||
deps: [ext-compile]
|
||||
cmd: npm run package
|
||||
|
||||
clean:
|
||||
desc: Remove build artifacts
|
||||
cmd: rm -f {{.BINARY}} {{.BINARY}}-*.exe {{.BINARY}}-*-linux-amd64
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.k3nny.fr/glint/internal/config"
|
||||
"git.k3nny.fr/glint/internal/fetcher"
|
||||
"git.k3nny.fr/glint/internal/lsp"
|
||||
)
|
||||
|
||||
func cmdLSP(args []string) {
|
||||
fs := flag.NewFlagSet("glint lsp", flag.ExitOnError)
|
||||
token := fs.String("token", "", "GitLab personal access token (overrides GITLAB_TOKEN)")
|
||||
gitlabURL := fs.String("gitlab-url", "", "GitLab instance URL (overrides CI_SERVER_URL / GITLAB_URL)")
|
||||
cacheDir := fs.String("cache-dir", "", "directory for caching fetched remote includes")
|
||||
offline := fs.Bool("offline", false, "skip all network calls; serve only from --cache-dir")
|
||||
proxy := fs.String("proxy", "", "HTTP proxy URL for remote includes and GitLab API calls (e.g. http://proxy:8080); overrides system proxy env vars")
|
||||
fs.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "glint %s\n\n", version)
|
||||
fmt.Fprint(os.Stderr, `Start a Language Server Protocol server for .gitlab-ci.yml files.
|
||||
|
||||
Reads JSON-RPC 2.0 messages from stdin and writes responses to stdout using
|
||||
the standard Content-Length framing. Connect with any LSP client (VS Code,
|
||||
Neovim, Emacs, etc.).
|
||||
|
||||
Usage: glint lsp [OPTIONS]
|
||||
|
||||
Options:
|
||||
--token <TOKEN>
|
||||
GitLab personal access token used for resolving project: and
|
||||
component: includes. Defaults to GITLAB_TOKEN env var.
|
||||
|
||||
--gitlab-url <URL>
|
||||
GitLab instance URL for resolving remote includes.
|
||||
[env: CI_SERVER_URL | GITLAB_URL] [default: https://gitlab.com]
|
||||
|
||||
--cache-dir <DIR>
|
||||
Cache directory for fetched remote includes. Defaults to
|
||||
~/.cache/glint so subsequent opens are served from cache.
|
||||
|
||||
--offline
|
||||
Do not make any network calls; resolve only local includes.
|
||||
Implies --cache-dir default (~/.cache/glint) when not set.
|
||||
|
||||
--proxy <URL>
|
||||
HTTP proxy URL for remote includes and GitLab API calls
|
||||
(e.g. http://proxy:8080). Overrides system proxy env vars
|
||||
(HTTP_PROXY / HTTPS_PROXY). Also configurable via proxy: in
|
||||
.glint.yml.
|
||||
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
Examples:
|
||||
glint lsp
|
||||
glint lsp --token glpat-xxxx --cache-dir ~/.cache/glint
|
||||
glint lsp --offline
|
||||
glint lsp --proxy http://proxy.example.com:8080
|
||||
`)
|
||||
}
|
||||
_ = fs.Parse(args)
|
||||
|
||||
// Load project config from the working directory (the project root from
|
||||
// which the LSP server is launched). CLI flags take priority.
|
||||
wd, _ := os.Getwd()
|
||||
glintCfg, cfgErr := config.Load(wd)
|
||||
if cfgErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "glint lsp: [warning] %s: %v\n", config.Filename, cfgErr)
|
||||
}
|
||||
|
||||
fetcherToken := *token
|
||||
if fetcherToken == "" {
|
||||
fetcherToken = glintCfg.Token
|
||||
}
|
||||
fetcherURL := *gitlabURL
|
||||
if fetcherURL == "" {
|
||||
fetcherURL = glintCfg.URL
|
||||
}
|
||||
resolvedCacheDir := *cacheDir
|
||||
if resolvedCacheDir == "" {
|
||||
resolvedCacheDir = glintCfg.CacheDir
|
||||
}
|
||||
if resolvedCacheDir == "" {
|
||||
resolvedCacheDir = defaultCacheDir()
|
||||
}
|
||||
resolvedProxy := *proxy
|
||||
if resolvedProxy == "" {
|
||||
resolvedProxy = glintCfg.Proxy
|
||||
}
|
||||
|
||||
cfg := fetcher.AutoConfig().WithOverrides(fetcherURL, fetcherToken, resolvedCacheDir, *offline).WithProxy(resolvedProxy)
|
||||
|
||||
srv := lsp.New(os.Stdin, os.Stdout, cfg, version)
|
||||
if err := srv.Run(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "glint lsp: %v\n", err)
|
||||
exit(2)
|
||||
}
|
||||
}
|
||||
+32
-3
@@ -69,6 +69,7 @@ Commands:
|
||||
check Lint a pipeline file — exits 0 (clean) or 1 (errors found)
|
||||
graph Visualise the pipeline as a job tree or Mermaid graph
|
||||
explain Show description and fix for a lint rule (e.g. glint explain GL007)
|
||||
lsp Start a Language Server Protocol server (stdin/stdout)
|
||||
|
||||
Options:
|
||||
-h, --help Print help
|
||||
@@ -90,6 +91,8 @@ func main() {
|
||||
cmdGraph(os.Args[2:])
|
||||
case "explain":
|
||||
cmdExplain(os.Args[2:])
|
||||
case "lsp":
|
||||
cmdLSP(os.Args[2:])
|
||||
case "-h", "--help", "help":
|
||||
fmt.Fprintf(os.Stderr, "glint %s\n\n", version)
|
||||
fmt.Fprint(os.Stderr, globalUsage)
|
||||
@@ -116,6 +119,7 @@ func cmdCheck(args []string) {
|
||||
gitlabURL := fs.String("gitlab-url", "", "GitLab instance URL (overrides CI_SERVER_URL / GITLAB_URL)")
|
||||
cacheDir := fs.String("cache-dir", "", "directory to cache fetched remote includes (created if needed)")
|
||||
offline := fs.Bool("offline", false, "skip all network calls; serve only from --cache-dir")
|
||||
proxy := fs.String("proxy", "", "HTTP proxy URL for remote includes and GitLab API calls (e.g. http://proxy:8080); overrides system proxy env vars")
|
||||
format := fs.String("format", "text", "output format: text, json, sarif, junit, github")
|
||||
branch := fs.String("branch", "", "simulate a branch push (sets CI_COMMIT_BRANCH, …)")
|
||||
tag := fs.String("tag", "", "simulate a tag push (sets CI_COMMIT_TAG, …)")
|
||||
@@ -283,8 +287,12 @@ Examples:
|
||||
if *offline && resolvedCacheDir == "" {
|
||||
resolvedCacheDir = defaultCacheDir()
|
||||
}
|
||||
resolvedProxy := *proxy
|
||||
if resolvedProxy == "" {
|
||||
resolvedProxy = glintCfg.Proxy
|
||||
}
|
||||
|
||||
cfg := fetcher.AutoConfig().WithOverrides(fetcherURL, fetcherToken, resolvedCacheDir, *offline)
|
||||
cfg := fetcher.AutoConfig().WithOverrides(fetcherURL, fetcherToken, resolvedCacheDir, *offline).WithProxy(resolvedProxy)
|
||||
|
||||
p, err := model.Parse(path)
|
||||
if err != nil {
|
||||
@@ -445,6 +453,7 @@ func cmdGraph(args []string) {
|
||||
gitlabURL := fs.String("gitlab-url", "", "GitLab instance URL (overrides CI_SERVER_URL / GITLAB_URL)")
|
||||
cacheDir := fs.String("cache-dir", "", "directory to cache fetched remote includes (created if needed)")
|
||||
offline := fs.Bool("offline", false, "skip all network calls; serve only from --cache-dir")
|
||||
proxy := fs.String("proxy", "", "HTTP proxy URL for remote includes and GitLab API calls (e.g. http://proxy:8080)")
|
||||
out := fs.String("out", "glint-out", "output directory for rendered graph files (pipeline mode)")
|
||||
format := fs.String("format", "svg", "pipeline output format: svg, mermaid, or html")
|
||||
fs.Usage = func() {
|
||||
@@ -556,13 +565,34 @@ Examples:
|
||||
return
|
||||
}
|
||||
path := fs.Arg(0)
|
||||
rootDir := filepath.Dir(filepath.Clean(path))
|
||||
|
||||
glintCfg, cfgErr := config.Load(rootDir)
|
||||
if cfgErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s: [warning] %s: %v\n", path, config.Filename, cfgErr)
|
||||
}
|
||||
|
||||
fetcherToken := *token
|
||||
if fetcherToken == "" {
|
||||
fetcherToken = glintCfg.Token
|
||||
}
|
||||
fetcherURL := *gitlabURL
|
||||
if fetcherURL == "" {
|
||||
fetcherURL = glintCfg.URL
|
||||
}
|
||||
resolvedCacheDir := *cacheDir
|
||||
if resolvedCacheDir == "" {
|
||||
resolvedCacheDir = glintCfg.CacheDir
|
||||
}
|
||||
if *offline && resolvedCacheDir == "" {
|
||||
resolvedCacheDir = defaultCacheDir()
|
||||
}
|
||||
resolvedProxy := *proxy
|
||||
if resolvedProxy == "" {
|
||||
resolvedProxy = glintCfg.Proxy
|
||||
}
|
||||
|
||||
cfg := fetcher.AutoConfig().WithOverrides(*gitlabURL, *token, resolvedCacheDir, *offline)
|
||||
cfg := fetcher.AutoConfig().WithOverrides(fetcherURL, fetcherToken, resolvedCacheDir, *offline).WithProxy(resolvedProxy)
|
||||
|
||||
p, err := model.Parse(path)
|
||||
if err != nil {
|
||||
@@ -571,7 +601,6 @@ Examples:
|
||||
return
|
||||
}
|
||||
|
||||
rootDir := filepath.Dir(filepath.Clean(path))
|
||||
resolver.ResolveIncludes(p, cfg, rootDir) //nolint:errcheck
|
||||
resolver.Resolve(p) //nolint:errcheck
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
out/
|
||||
*.vsix
|
||||
@@ -0,0 +1,8 @@
|
||||
src/**
|
||||
tsconfig.json
|
||||
.gitignore
|
||||
node_modules/**
|
||||
!node_modules/vscode-languageclient/**
|
||||
!node_modules/vscode-languageserver-protocol/**
|
||||
!node_modules/vscode-languageserver-types/**
|
||||
!node_modules/vscode-jsonrpc/**
|
||||
Generated
+2532
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "glint",
|
||||
"displayName": "glint — GitLab CI Linter",
|
||||
"description": "Inline diagnostics for .gitlab-ci.yml pipelines powered by the glint language server",
|
||||
"version": "0.2.29",
|
||||
"publisher": "k3nny",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.k3nny.fr/k3nny/glint"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.82.0"
|
||||
},
|
||||
"categories": [
|
||||
"Linters"
|
||||
],
|
||||
"keywords": [
|
||||
"gitlab",
|
||||
"ci",
|
||||
"yaml",
|
||||
"lint",
|
||||
"pipeline"
|
||||
],
|
||||
"activationEvents": [
|
||||
"onLanguage:yaml"
|
||||
],
|
||||
"main": "./out/extension.js",
|
||||
"contributes": {
|
||||
"configuration": {
|
||||
"type": "object",
|
||||
"title": "glint",
|
||||
"properties": {
|
||||
"glint.executablePath": {
|
||||
"type": "string",
|
||||
"default": "glint",
|
||||
"markdownDescription": "Path to the `glint` binary. Leave as `glint` if it is on your `PATH`, or set an absolute path (e.g. `/usr/local/bin/glint`)."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"compile": "tsc -p ./",
|
||||
"watch": "tsc --watch -p ./",
|
||||
"package": "vsce package"
|
||||
},
|
||||
"dependencies": {
|
||||
"vscode-languageclient": "^9.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20",
|
||||
"@types/vscode": "^1.82.0",
|
||||
"@vscode/vsce": "^2.22.0",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import * as vscode from 'vscode';
|
||||
import {
|
||||
LanguageClient,
|
||||
LanguageClientOptions,
|
||||
ServerOptions,
|
||||
TransportKind,
|
||||
} from 'vscode-languageclient/node';
|
||||
|
||||
let client: LanguageClient | undefined;
|
||||
|
||||
export function activate(context: vscode.ExtensionContext): void {
|
||||
const cfg = vscode.workspace.getConfiguration('glint');
|
||||
const glintPath = cfg.get<string>('executablePath') || 'glint';
|
||||
|
||||
const serverOptions: ServerOptions = {
|
||||
command: glintPath,
|
||||
args: ['lsp'],
|
||||
transport: TransportKind.stdio,
|
||||
};
|
||||
|
||||
const clientOptions: LanguageClientOptions = {
|
||||
// Only process .gitlab-ci.yml files, not all YAML.
|
||||
documentSelector: [
|
||||
{ scheme: 'file', language: 'yaml', pattern: '**/.gitlab-ci.yml' },
|
||||
],
|
||||
};
|
||||
|
||||
client = new LanguageClient(
|
||||
'glint',
|
||||
'glint — GitLab CI Linter',
|
||||
serverOptions,
|
||||
clientOptions,
|
||||
);
|
||||
|
||||
client.start();
|
||||
context.subscriptions.push(client);
|
||||
}
|
||||
|
||||
export async function deactivate(): Promise<void> {
|
||||
await client?.stop();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "ES2020",
|
||||
"lib": ["ES2020"],
|
||||
"outDir": "out",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"sourceMap": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules", "out"]
|
||||
}
|
||||
@@ -2,14 +2,15 @@ module git.k3nny.fr/glint
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c // indirect
|
||||
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 // indirect
|
||||
golang.org/x/mod v0.31.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/tools v0.40.1-0.20260108161641-ca281cf95054 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
honnef.co/go/tools v0.7.0 // indirect
|
||||
golang.org/x/mod v0.35.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/tools v0.44.1-0.20260420230617-19499e7caabc // indirect
|
||||
honnef.co/go/tools v0.8.0-rc.1 // indirect
|
||||
)
|
||||
|
||||
tool honnef.co/go/tools/cmd/staticcheck
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c h1:pxW6RcqyfI9/kWtOwnv/G+AzdKuy2ZrqINhenH4HyNs=
|
||||
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa h1:FRnLl4eNAQl8hwxVVC17teOw8kdjVDVAiFMtgUdTSRQ=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 h1:1P7xPZEwZMoBoz0Yze5Nx2/4pxj6nw9ZqHWXqP0iRgQ=
|
||||
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/tools v0.40.1-0.20260108161641-ca281cf95054 h1:CHVDrNHx9ZoOrNN9kKWYIbT5Rj+WF2rlwPkhbQQ5V4U=
|
||||
golang.org/x/tools v0.40.1-0.20260108161641-ca281cf95054/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/tools v0.44.1-0.20260420230617-19499e7caabc h1:vSv/HN1q9eoPD7lMyJYVJ/GPYnqtqu6adMxUmrxOB78=
|
||||
golang.org/x/tools v0.44.1-0.20260420230617-19499e7caabc/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=
|
||||
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
|
||||
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=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.7.0 h1:w6WUp1VbkqPEgLz4rkBzH/CSU6HkoqNLp6GstyTx3lU=
|
||||
honnef.co/go/tools v0.7.0/go.mod h1:pm29oPxeP3P82ISxZDgIYeOaf9ta6Pi0EWvCFoLG2vc=
|
||||
honnef.co/go/tools v0.8.0-rc.1 h1:wqMm2kjcEXMOr+6yau+pdKqJKe6l2N1aKPkpini+Kzk=
|
||||
honnef.co/go/tools v0.8.0-rc.1/go.mod h1:XA+OnlRA9EDh/ukGvXMNSZNKGwFQJ+5dER0ioUkOxks=
|
||||
|
||||
@@ -38,6 +38,12 @@ type Config struct {
|
||||
// CacheDir is the default directory for caching fetched remote includes.
|
||||
// Overridden by the --cache-dir flag.
|
||||
CacheDir string `yaml:"cache_dir"`
|
||||
|
||||
// Proxy is the HTTP proxy URL for fetching remote includes and GitLab API
|
||||
// calls (e.g. "http://proxy.example.com:8080"). Overridden by the --proxy
|
||||
// flag. When empty, system proxy settings (HTTP_PROXY / HTTPS_PROXY /
|
||||
// NO_PROXY env vars) are used automatically.
|
||||
Proxy string `yaml:"proxy"`
|
||||
}
|
||||
|
||||
// Load searches for a .glint.yml file starting from dir and walking up toward
|
||||
|
||||
@@ -26,10 +26,10 @@ func cacheWrite(dir, key string, data []byte) {
|
||||
if dir == "" {
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.WriteFile(cachePath(dir, key), data, 0o644)
|
||||
_ = os.WriteFile(cachePath(dir, key), data, 0o600)
|
||||
}
|
||||
|
||||
// cachePath returns the filesystem path for a cache entry.
|
||||
|
||||
@@ -71,3 +71,28 @@ func TestCacheWrite_MkdirAll(t *testing.T) {
|
||||
t.Errorf("directory not created: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheWrite_FilePermissions(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cacheWrite(dir, "seckey", []byte("secret"))
|
||||
info, err := os.Stat(cachePath(dir, "seckey"))
|
||||
if err != nil {
|
||||
t.Fatalf("stat cache file: %v", err)
|
||||
}
|
||||
if mode := info.Mode().Perm(); mode != 0o600 {
|
||||
t.Errorf("cache file mode = %04o; want 0600", mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheWrite_DirPermissions(t *testing.T) {
|
||||
parent := t.TempDir()
|
||||
dir := filepath.Join(parent, "glint-cache")
|
||||
cacheWrite(dir, "k", []byte("v"))
|
||||
info, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("stat cache dir: %v", err)
|
||||
}
|
||||
if mode := info.Mode().Perm(); mode != 0o700 {
|
||||
t.Errorf("cache dir mode = %04o; want 0700", mode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,18 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// httpClient is the shared HTTP client for all fetcher requests.
|
||||
// Timeout guards against hung remote servers. Transport is intentionally nil
|
||||
// so http.DefaultTransport is used dynamically — allowing tests to swap it.
|
||||
var httpClient = &http.Client{Timeout: 30 * time.Second}
|
||||
|
||||
// maxResponseBytes is the per-response size cap. Responses larger than this
|
||||
// are rejected to prevent memory exhaustion from pathological servers.
|
||||
const maxResponseBytes int64 = 10 << 20 // 10 MiB
|
||||
|
||||
// TokenSource describes where a token was found, which determines the correct
|
||||
// authentication header to use with the GitLab API.
|
||||
type TokenSource int
|
||||
@@ -27,6 +37,10 @@ type GitLabConfig struct {
|
||||
Source TokenSource
|
||||
CacheDir string // local cache directory; empty = caching disabled
|
||||
Offline bool // when true, return an error instead of making network calls
|
||||
// ProxyURL overrides the HTTP proxy for all requests made with this config.
|
||||
// Empty string means use system proxy settings (HTTP_PROXY / HTTPS_PROXY /
|
||||
// NO_PROXY env vars honoured automatically by http.DefaultTransport).
|
||||
ProxyURL string
|
||||
}
|
||||
|
||||
// AutoConfig builds a GitLabConfig from environment variables.
|
||||
@@ -56,6 +70,33 @@ func AutoConfig() GitLabConfig {
|
||||
return cfg
|
||||
}
|
||||
|
||||
// WithProxy returns a copy of cfg with ProxyURL set.
|
||||
func (cfg GitLabConfig) WithProxy(proxyURL string) GitLabConfig {
|
||||
cfg.ProxyURL = proxyURL
|
||||
return cfg
|
||||
}
|
||||
|
||||
// client returns an HTTP client for this config.
|
||||
// When ProxyURL is set it takes precedence over system proxy env vars;
|
||||
// otherwise http.DefaultTransport's built-in ProxyFromEnvironment is used.
|
||||
func (cfg GitLabConfig) client() *http.Client {
|
||||
if cfg.ProxyURL == "" {
|
||||
return httpClient
|
||||
}
|
||||
proxyURL, err := url.Parse(cfg.ProxyURL)
|
||||
if err != nil {
|
||||
return httpClient
|
||||
}
|
||||
// Clone the default transport so all TLS/dial settings are preserved.
|
||||
t, ok := http.DefaultTransport.(*http.Transport)
|
||||
if !ok {
|
||||
return httpClient
|
||||
}
|
||||
transport := t.Clone()
|
||||
transport.Proxy = http.ProxyURL(proxyURL)
|
||||
return &http.Client{Timeout: httpClient.Timeout, Transport: transport}
|
||||
}
|
||||
|
||||
// WithOverrides returns a copy of cfg with the provided overrides applied.
|
||||
// Non-empty strings overwrite the corresponding field; booleans are always
|
||||
// applied (so offline: false explicitly clears offline mode).
|
||||
@@ -128,16 +169,19 @@ func (cfg GitLabConfig) FetchFile(project, filePath, ref string) ([]byte, error)
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := cfg.client().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GET %s: %w", apiURL, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading response body: %w", err)
|
||||
}
|
||||
if int64(len(body)) > maxResponseBytes {
|
||||
return nil, fmt.Errorf("response body exceeds maximum size (%d MiB)", maxResponseBytes>>20)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
msg := strings.TrimSpace(string(body))
|
||||
@@ -169,15 +213,18 @@ func (cfg GitLabConfig) FetchURL(rawURL string) ([]byte, error) {
|
||||
return nil, fmt.Errorf("offline mode: %s is not in the local cache (run without --offline first to populate the cache)", rawURL)
|
||||
}
|
||||
|
||||
resp, err := http.Get(rawURL) //nolint:noctx
|
||||
resp, err := cfg.client().Get(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GET %s: %w", rawURL, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading body: %w", err)
|
||||
}
|
||||
if int64(len(body)) > maxResponseBytes {
|
||||
return nil, fmt.Errorf("response body exceeds maximum size (%d MiB)", maxResponseBytes>>20)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("GET %s: status %d", rawURL, resp.StatusCode)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -339,3 +340,46 @@ func TestFetchURL_NotOK(t *testing.T) {
|
||||
_, err := cfg.FetchURL(srv.URL)
|
||||
if err == nil { t.Fatal("expected error for non-200 status") }
|
||||
}
|
||||
|
||||
func TestFetchFile_ResponseTooLarge(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
// Write maxResponseBytes+1 bytes to exceed the cap.
|
||||
chunk := make([]byte, 4096)
|
||||
written := int64(0)
|
||||
for written <= maxResponseBytes {
|
||||
n, _ := w.Write(chunk)
|
||||
written += int64(n)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
cfg := GitLabConfig{BaseURL: srv.URL}
|
||||
_, err := cfg.FetchFile("group/project", "/ci.yml", "main")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for oversized response")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchURL_ResponseTooLarge(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
chunk := make([]byte, 4096)
|
||||
written := int64(0)
|
||||
for written <= maxResponseBytes {
|
||||
n, _ := w.Write(chunk)
|
||||
written += int64(n)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
cfg := GitLabConfig{}
|
||||
_, err := cfg.FetchURL(srv.URL)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for oversized response")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -853,4 +853,18 @@ test:
|
||||
- if: $CI_COMMIT_BRANCH == "main"
|
||||
needs: [build, lint]`,
|
||||
},
|
||||
|
||||
RuleInsecureRemoteInclude: {
|
||||
Title: "remote include uses plain HTTP",
|
||||
Severity: Warning,
|
||||
Description: "An include: remote: entry uses an http:// URL instead of https://. " +
|
||||
"CI templates fetched over plain HTTP are transmitted in cleartext; an " +
|
||||
"attacker with network access could intercept or modify the template " +
|
||||
"before it is parsed. Use https:// so the connection is encrypted and " +
|
||||
"the server's identity is verified.",
|
||||
Example: `include:
|
||||
- remote: http://ci-templates.example.com/build.yml`,
|
||||
Fix: `include:
|
||||
- remote: https://ci-templates.example.com/build.yml`,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package linter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.k3nny.fr/glint/internal/model"
|
||||
)
|
||||
|
||||
// checkInsecureRemoteInclude warns when an include: remote: entry uses plain
|
||||
// HTTP (GL045). The file is still fetched and linted; the finding is a warning
|
||||
// so pipelines that use HTTP for internal infra are not blocked.
|
||||
func checkInsecureRemoteInclude(p *model.Pipeline) []Finding {
|
||||
var findings []Finding
|
||||
for _, inc := range p.Include {
|
||||
m, ok := inc.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
remote, _ := m["remote"].(string)
|
||||
if strings.HasPrefix(remote, "http://") {
|
||||
findings = append(findings, Finding{
|
||||
Severity: Warning,
|
||||
Rule: RuleInsecureRemoteInclude,
|
||||
File: p.SourceFile,
|
||||
Message: fmt.Sprintf("remote include %q uses plain HTTP; CI templates are fetched unencrypted — prefer HTTPS", remote),
|
||||
})
|
||||
}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package linter
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.k3nny.fr/glint/internal/model"
|
||||
)
|
||||
|
||||
func TestCheckInsecureRemoteInclude(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
include []any
|
||||
wantGL string // expected rule ID, empty = no findings
|
||||
}{
|
||||
{
|
||||
name: "http URL triggers GL045",
|
||||
include: []any{map[string]any{"remote": "http://example.com/ci.yml"}},
|
||||
wantGL: RuleInsecureRemoteInclude,
|
||||
},
|
||||
{
|
||||
name: "https URL is clean",
|
||||
include: []any{map[string]any{"remote": "https://example.com/ci.yml"}},
|
||||
},
|
||||
{
|
||||
name: "local include ignored",
|
||||
include: []any{map[string]any{"local": "/templates/ci.yml"}},
|
||||
},
|
||||
{
|
||||
name: "string include ignored",
|
||||
include: []any{"/templates/ci.yml"},
|
||||
},
|
||||
{
|
||||
name: "no includes",
|
||||
include: nil,
|
||||
},
|
||||
{
|
||||
name: "mixed: http fires, https does not",
|
||||
include: []any{
|
||||
map[string]any{"remote": "https://ok.example.com/ci.yml"},
|
||||
map[string]any{"remote": "http://bad.example.com/ci.yml"},
|
||||
},
|
||||
wantGL: RuleInsecureRemoteInclude,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := &model.Pipeline{
|
||||
Include: tc.include,
|
||||
Jobs: map[string]model.Job{},
|
||||
}
|
||||
findings := checkInsecureRemoteInclude(p)
|
||||
if tc.wantGL == "" {
|
||||
if len(findings) != 0 {
|
||||
t.Errorf("expected no findings, got: %v", findings)
|
||||
}
|
||||
return
|
||||
}
|
||||
found := false
|
||||
for _, f := range findings {
|
||||
if f.Rule == tc.wantGL {
|
||||
found = true
|
||||
if f.Severity != Warning {
|
||||
t.Errorf("severity = %v; want Warning", f.Severity)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("expected finding %s, got: %v", tc.wantGL, findings)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,7 @@ func Lint(p *model.Pipeline, skipped map[string]bool) []Finding {
|
||||
findings = append(findings, checkVariableRefs(p)...)
|
||||
findings = append(findings, checkRulesIfReachability(p)...)
|
||||
findings = append(findings, checkInheritCompleteness(p)...)
|
||||
findings = append(findings, checkInsecureRemoteInclude(p)...)
|
||||
slices.SortStableFunc(findings, func(a, b Finding) int {
|
||||
if c := cmp.Compare(a.File, b.File); c != 0 {
|
||||
return c
|
||||
|
||||
@@ -158,4 +158,9 @@ const (
|
||||
// GL044: a rules:needs: entry references a job that does not exist in the pipeline.
|
||||
// rules:needs: overrides the top-level needs: when a specific rule matches (GitLab CI 16.4+).
|
||||
RuleRulesNeedsUnknown = "GL044"
|
||||
|
||||
// GL045: an include: remote: entry uses plain HTTP instead of HTTPS.
|
||||
// CI templates fetched over HTTP are transmitted in cleartext and can be
|
||||
// intercepted or modified in transit.
|
||||
RuleInsecureRemoteInclude = "GL045"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
package lsp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.k3nny.fr/glint/internal/fetcher"
|
||||
"git.k3nny.fr/glint/internal/linter"
|
||||
"git.k3nny.fr/glint/internal/model"
|
||||
"git.k3nny.fr/glint/internal/resolver"
|
||||
)
|
||||
|
||||
// Server is a minimal Language Server Protocol server that publishes glint
|
||||
// diagnostics for .gitlab-ci.yml files opened in an editor.
|
||||
//
|
||||
// Transport: JSON-RPC 2.0 over stdin/stdout with Content-Length framing.
|
||||
// Sync mode: Full — the client sends the complete document text on every change.
|
||||
type Server struct {
|
||||
in *bufio.Reader
|
||||
out io.Writer
|
||||
cfg fetcher.GitLabConfig
|
||||
version string
|
||||
docs map[string]string // uri → current document text
|
||||
|
||||
// Exit is called with the process exit code when the LSP client sends the
|
||||
// "exit" notification. Defaults to os.Exit; replace in tests.
|
||||
Exit func(int)
|
||||
|
||||
shutdownReceived bool
|
||||
}
|
||||
|
||||
// New creates a Server reading from r and writing to w.
|
||||
func New(r io.Reader, w io.Writer, cfg fetcher.GitLabConfig, version string) *Server {
|
||||
return &Server{
|
||||
in: bufio.NewReader(r),
|
||||
out: w,
|
||||
cfg: cfg,
|
||||
version: version,
|
||||
docs: make(map[string]string),
|
||||
Exit: os.Exit,
|
||||
}
|
||||
}
|
||||
|
||||
// Run processes LSP messages until the connection closes or a fatal error occurs.
|
||||
// It returns nil on a clean EOF (client disconnected) and a non-nil error for
|
||||
// unrecoverable protocol failures.
|
||||
func (s *Server) Run() error {
|
||||
for {
|
||||
msg, err := s.readMessage()
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading LSP message: %w", err)
|
||||
}
|
||||
if err := s.dispatch(msg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// maxLSPMessageBytes caps the body size accepted from an LSP client.
|
||||
// A legitimate editor message is never this large; enforcing the cap prevents
|
||||
// a crafted Content-Length from triggering a multi-gigabyte allocation.
|
||||
const maxLSPMessageBytes = 64 << 20 // 64 MiB
|
||||
|
||||
// readMessage reads one Content-Length–framed JSON-RPC message from the stream.
|
||||
func (s *Server) readMessage() (*Message, error) {
|
||||
var contentLength int
|
||||
for {
|
||||
line, err := s.in.ReadString('\n')
|
||||
if err != nil {
|
||||
if err == io.EOF && line == "" {
|
||||
return nil, io.EOF
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
break // blank line separates headers from body
|
||||
}
|
||||
if strings.HasPrefix(line, "Content-Length: ") {
|
||||
n, parseErr := strconv.Atoi(strings.TrimPrefix(line, "Content-Length: "))
|
||||
if parseErr != nil {
|
||||
return nil, fmt.Errorf("invalid Content-Length: %w", parseErr)
|
||||
}
|
||||
contentLength = n
|
||||
}
|
||||
}
|
||||
if contentLength == 0 {
|
||||
return nil, fmt.Errorf("missing or zero Content-Length header")
|
||||
}
|
||||
if contentLength > maxLSPMessageBytes {
|
||||
return nil, fmt.Errorf("Content-Length %d exceeds maximum %d", contentLength, maxLSPMessageBytes)
|
||||
}
|
||||
|
||||
body := make([]byte, contentLength)
|
||||
if _, err := io.ReadFull(s.in, body); err != nil {
|
||||
return nil, fmt.Errorf("reading message body: %w", err)
|
||||
}
|
||||
|
||||
var msg Message
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
return nil, fmt.Errorf("unmarshalling message: %w", err)
|
||||
}
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
// writeMessage encodes v as JSON and sends it with a Content-Length header.
|
||||
func (s *Server) writeMessage(v any) error {
|
||||
body, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(body))
|
||||
if _, err := io.WriteString(s.out, header); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.out.Write(body)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) respond(id json.RawMessage, result any) error {
|
||||
raw, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.writeMessage(struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
}{"2.0", id, raw})
|
||||
}
|
||||
|
||||
func (s *Server) respondError(id json.RawMessage, code int, message string) error {
|
||||
return s.writeMessage(struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Error RPCError `json:"error"`
|
||||
}{"2.0", id, RPCError{Code: code, Message: message}})
|
||||
}
|
||||
|
||||
func (s *Server) notify(method string, params any) error {
|
||||
raw, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.writeMessage(struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
}{"2.0", method, raw})
|
||||
}
|
||||
|
||||
// isRequest reports whether msg is a JSON-RPC request (has a non-null id).
|
||||
func isRequest(msg *Message) bool {
|
||||
return len(msg.ID) > 0 && string(msg.ID) != "null"
|
||||
}
|
||||
|
||||
func (s *Server) dispatch(msg *Message) error {
|
||||
switch msg.Method {
|
||||
case "initialize":
|
||||
return s.handleInitialize(msg)
|
||||
case "initialized":
|
||||
return nil // notification; no response required
|
||||
case "shutdown":
|
||||
s.shutdownReceived = true
|
||||
if isRequest(msg) {
|
||||
return s.respond(msg.ID, nil)
|
||||
}
|
||||
return nil
|
||||
case "exit":
|
||||
code := 1
|
||||
if s.shutdownReceived {
|
||||
code = 0
|
||||
}
|
||||
s.Exit(code)
|
||||
return nil
|
||||
case "textDocument/didOpen":
|
||||
return s.handleDidOpen(msg)
|
||||
case "textDocument/didChange":
|
||||
return s.handleDidChange(msg)
|
||||
case "textDocument/didSave":
|
||||
return s.handleDidSave(msg)
|
||||
case "textDocument/didClose":
|
||||
return s.handleDidClose(msg)
|
||||
default:
|
||||
if isRequest(msg) {
|
||||
return s.respondError(msg.ID, -32601, "method not found: "+msg.Method)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleInitialize(msg *Message) error {
|
||||
return s.respond(msg.ID, InitializeResult{
|
||||
Capabilities: ServerCapabilities{TextDocumentSync: 1},
|
||||
ServerInfo: &ServerInfo{Name: "glint", Version: s.version},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleDidOpen(msg *Message) error {
|
||||
var p DidOpenTextDocumentParams
|
||||
if err := json.Unmarshal(msg.Params, &p); err != nil {
|
||||
return nil // ignore malformed notifications
|
||||
}
|
||||
s.docs[p.TextDocument.URI] = p.TextDocument.Text
|
||||
return s.lintAndPublish(p.TextDocument.URI, p.TextDocument.Text)
|
||||
}
|
||||
|
||||
func (s *Server) handleDidChange(msg *Message) error {
|
||||
var p DidChangeTextDocumentParams
|
||||
if err := json.Unmarshal(msg.Params, &p); err != nil {
|
||||
return nil
|
||||
}
|
||||
if len(p.ContentChanges) == 0 {
|
||||
return nil
|
||||
}
|
||||
// Full sync: the last change event holds the complete new text.
|
||||
text := p.ContentChanges[len(p.ContentChanges)-1].Text
|
||||
s.docs[p.TextDocument.URI] = text
|
||||
return s.lintAndPublish(p.TextDocument.URI, text)
|
||||
}
|
||||
|
||||
func (s *Server) handleDidSave(msg *Message) error {
|
||||
var p DidSaveTextDocumentParams
|
||||
if err := json.Unmarshal(msg.Params, &p); err != nil {
|
||||
return nil
|
||||
}
|
||||
text := s.docs[p.TextDocument.URI]
|
||||
if p.Text != nil {
|
||||
text = *p.Text
|
||||
s.docs[p.TextDocument.URI] = text
|
||||
}
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
return s.lintAndPublish(p.TextDocument.URI, text)
|
||||
}
|
||||
|
||||
func (s *Server) handleDidClose(msg *Message) error {
|
||||
var p DidCloseTextDocumentParams
|
||||
if err := json.Unmarshal(msg.Params, &p); err != nil {
|
||||
return nil
|
||||
}
|
||||
delete(s.docs, p.TextDocument.URI)
|
||||
// Clear diagnostics so the editor doesn't show stale squiggles.
|
||||
return s.notify("textDocument/publishDiagnostics", PublishDiagnosticsParams{
|
||||
URI: p.TextDocument.URI,
|
||||
Diagnostics: []Diagnostic{},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) lintAndPublish(uri, text string) error {
|
||||
diags := s.lintDocument(uri, text)
|
||||
return s.notify("textDocument/publishDiagnostics", PublishDiagnosticsParams{
|
||||
URI: uri,
|
||||
Diagnostics: diags,
|
||||
})
|
||||
}
|
||||
|
||||
// lintDocument parses text and runs all lint rules, returning LSP Diagnostics.
|
||||
// Findings that originate from included files (not the root document) are
|
||||
// excluded; their URIs are not tracked so line numbers would be incorrect.
|
||||
func (s *Server) lintDocument(uri, text string) []Diagnostic {
|
||||
path := uriToPath(uri)
|
||||
if path == "" {
|
||||
return []Diagnostic{}
|
||||
}
|
||||
rootDir := filepath.Dir(filepath.Clean(path))
|
||||
|
||||
pipeline, err := model.ParseBytes([]byte(text))
|
||||
if err != nil {
|
||||
return []Diagnostic{{
|
||||
Range: Range{Start: Position{}, End: Position{}},
|
||||
Severity: 1,
|
||||
Source: "glint",
|
||||
Message: "YAML parse error: " + err.Error(),
|
||||
}}
|
||||
}
|
||||
pipeline.SourceFile = path
|
||||
pipeline.SetJobOrigin(path)
|
||||
|
||||
// Include resolution is best-effort: network failures produce warnings that
|
||||
// are intentionally discarded here. The linter operates on whatever was
|
||||
// successfully resolved.
|
||||
_, _ = resolver.ResolveIncludes(pipeline, s.cfg, rootDir)
|
||||
_, _ = resolver.Resolve(pipeline)
|
||||
|
||||
findings := linter.Lint(pipeline, nil)
|
||||
|
||||
diags := make([]Diagnostic, 0, len(findings))
|
||||
for _, f := range findings {
|
||||
// Skip findings from included files — their line numbers reference
|
||||
// a different document URI that the server has not opened.
|
||||
if f.File != path && f.File != "" {
|
||||
continue
|
||||
}
|
||||
line := 0
|
||||
if f.Line > 0 {
|
||||
line = f.Line - 1 // glint uses 1-based lines; LSP uses 0-based
|
||||
}
|
||||
sev := 1 // DiagnosticSeverity: Error
|
||||
if f.Severity == linter.Warning {
|
||||
sev = 2 // DiagnosticSeverity: Warning
|
||||
}
|
||||
msg := f.Message
|
||||
if f.Job != "" {
|
||||
msg = fmt.Sprintf("job %q: %s", f.Job, f.Message)
|
||||
}
|
||||
diags = append(diags, Diagnostic{
|
||||
Range: Range{
|
||||
Start: Position{Line: line},
|
||||
End: Position{Line: line},
|
||||
},
|
||||
Severity: sev,
|
||||
Code: f.Rule,
|
||||
Source: "glint",
|
||||
Message: msg,
|
||||
})
|
||||
}
|
||||
return diags
|
||||
}
|
||||
|
||||
// uriToPath converts a file:// URI to a local filesystem path.
|
||||
// Returns an empty string for non-file URIs or on parse error.
|
||||
func uriToPath(uri string) string {
|
||||
u, err := url.Parse(uri)
|
||||
if err != nil || u.Scheme != "file" {
|
||||
return ""
|
||||
}
|
||||
return filepath.FromSlash(u.Path)
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
package lsp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.k3nny.fr/glint/internal/fetcher"
|
||||
)
|
||||
|
||||
// frame encodes v as a Content-Length–framed LSP message.
|
||||
func frame(t *testing.T, v any) []byte {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hdr := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(body))
|
||||
return append([]byte(hdr), body...)
|
||||
}
|
||||
|
||||
// readMsg reads one Content-Length–framed JSON object from r.
|
||||
func readMsg(t *testing.T, r *bufio.Reader) map[string]json.RawMessage {
|
||||
t.Helper()
|
||||
var contentLength int
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("reading header: %v", err)
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(line, "Content-Length: ") {
|
||||
n, err := strconv.Atoi(strings.TrimPrefix(line, "Content-Length: "))
|
||||
if err != nil {
|
||||
t.Fatalf("invalid Content-Length: %v", err)
|
||||
}
|
||||
contentLength = n
|
||||
}
|
||||
}
|
||||
body := make([]byte, contentLength)
|
||||
if _, err := io.ReadFull(r, body); err != nil {
|
||||
t.Fatalf("reading body: %v", err)
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &m); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// newTestServer returns a Server with a captured exit code and a bufio.Reader
|
||||
// wrapping the output buffer so tests can read back server messages.
|
||||
func newTestServer(input []byte) (*Server, *bytes.Buffer, *int) {
|
||||
var out bytes.Buffer
|
||||
exitCode := -1
|
||||
srv := New(bytes.NewReader(input), &out, fetcher.GitLabConfig{}, "test")
|
||||
srv.Exit = func(code int) { exitCode = code }
|
||||
return srv, &out, &exitCode
|
||||
}
|
||||
|
||||
func TestServer_Initialize(t *testing.T) {
|
||||
input := frame(t, map[string]any{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": map[string]any{},
|
||||
})
|
||||
srv, out, _ := newTestServer(input)
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
resp := readMsg(t, bufio.NewReader(out))
|
||||
if string(resp["id"]) != "1" {
|
||||
t.Errorf("response id = %s; want 1", resp["id"])
|
||||
}
|
||||
|
||||
var result InitializeResult
|
||||
if err := json.Unmarshal(resp["result"], &result); err != nil {
|
||||
t.Fatalf("unmarshal result: %v", err)
|
||||
}
|
||||
if result.Capabilities.TextDocumentSync != 1 {
|
||||
t.Errorf("textDocumentSync = %d; want 1", result.Capabilities.TextDocumentSync)
|
||||
}
|
||||
if result.ServerInfo == nil || result.ServerInfo.Name != "glint" {
|
||||
t.Errorf("serverInfo.name = %v; want glint", result.ServerInfo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_ShutdownExit(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
buf.Write(frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": map[string]any{},
|
||||
}))
|
||||
buf.Write(frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "method": "initialized", "params": map[string]any{},
|
||||
}))
|
||||
buf.Write(frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "id": 2, "method": "shutdown",
|
||||
}))
|
||||
buf.Write(frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "method": "exit",
|
||||
}))
|
||||
|
||||
srv, out, exitCode := newTestServer(buf.Bytes())
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
r := bufio.NewReader(out)
|
||||
initResp := readMsg(t, r)
|
||||
if string(initResp["id"]) != "1" {
|
||||
t.Errorf("init response id = %s; want 1", initResp["id"])
|
||||
}
|
||||
shutResp := readMsg(t, r)
|
||||
if string(shutResp["id"]) != "2" {
|
||||
t.Errorf("shutdown response id = %s; want 2", shutResp["id"])
|
||||
}
|
||||
if string(shutResp["result"]) != "null" {
|
||||
t.Errorf("shutdown result = %s; want null", shutResp["result"])
|
||||
}
|
||||
if *exitCode != 0 {
|
||||
t.Errorf("exit code = %d; want 0", *exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_ExitWithoutShutdown(t *testing.T) {
|
||||
input := frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "method": "exit",
|
||||
})
|
||||
srv, _, exitCode := newTestServer(input)
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
if *exitCode != 1 {
|
||||
t.Errorf("exit code = %d; want 1 (no prior shutdown)", *exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_MethodNotFound(t *testing.T) {
|
||||
input := frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "id": 99, "method": "workspace/unknownMethod",
|
||||
})
|
||||
srv, out, _ := newTestServer(input)
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
resp := readMsg(t, bufio.NewReader(out))
|
||||
if resp["error"] == nil {
|
||||
t.Errorf("expected error response for unknown method, got: %v", resp)
|
||||
}
|
||||
var rpcErr RPCError
|
||||
if err := json.Unmarshal(resp["error"], &rpcErr); err != nil {
|
||||
t.Fatalf("unmarshal error: %v", err)
|
||||
}
|
||||
if rpcErr.Code != -32601 {
|
||||
t.Errorf("error code = %d; want -32601", rpcErr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_UnknownNotificationIgnored(t *testing.T) {
|
||||
// Notifications (no id) for unknown methods must be silently ignored.
|
||||
input := frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "method": "$/setTrace", "params": map[string]any{"value": "off"},
|
||||
})
|
||||
srv, out, _ := newTestServer(input)
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
if out.Len() > 0 {
|
||||
t.Errorf("server wrote %d bytes for unknown notification; want 0", out.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_DidOpen_CleanPipeline(t *testing.T) {
|
||||
yaml := `stages: [build]
|
||||
|
||||
build-job:
|
||||
stage: build
|
||||
script: echo hello
|
||||
`
|
||||
// Use a pseudo file:// URI that maps to the tmp path; include resolution
|
||||
// will fail silently (no network, no local includes) which is fine.
|
||||
uri := "file:///tmp/test.gitlab-ci.yml"
|
||||
|
||||
input := frame(t, map[string]any{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "textDocument/didOpen",
|
||||
"params": map[string]any{
|
||||
"textDocument": map[string]any{
|
||||
"uri": uri, "languageId": "yaml", "version": 1, "text": yaml,
|
||||
},
|
||||
},
|
||||
})
|
||||
srv, out, _ := newTestServer(input)
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
notif := readMsg(t, bufio.NewReader(out))
|
||||
if string(notif["method"]) != `"textDocument/publishDiagnostics"` {
|
||||
t.Fatalf("method = %s; want textDocument/publishDiagnostics", notif["method"])
|
||||
}
|
||||
var params PublishDiagnosticsParams
|
||||
if err := json.Unmarshal(notif["params"], ¶ms); err != nil {
|
||||
t.Fatalf("unmarshal params: %v", err)
|
||||
}
|
||||
if params.URI != uri {
|
||||
t.Errorf("uri = %q; want %q", params.URI, uri)
|
||||
}
|
||||
// A clean pipeline should produce no diagnostics (or only warnings from
|
||||
// include resolution being skipped — but those are filtered since they
|
||||
// originate from a different file path).
|
||||
for _, d := range params.Diagnostics {
|
||||
if d.Severity == 1 {
|
||||
t.Errorf("unexpected error diagnostic: %s", d.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_DidOpen_WithErrors(t *testing.T) {
|
||||
// A pipeline with a job in an undeclared stage triggers GL004.
|
||||
yaml := `stages: [build]
|
||||
|
||||
bad-job:
|
||||
stage: missing-stage
|
||||
script: echo hi
|
||||
`
|
||||
uri := "file:///tmp/bad.gitlab-ci.yml"
|
||||
input := frame(t, map[string]any{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "textDocument/didOpen",
|
||||
"params": map[string]any{
|
||||
"textDocument": map[string]any{
|
||||
"uri": uri, "languageId": "yaml", "version": 1, "text": yaml,
|
||||
},
|
||||
},
|
||||
})
|
||||
srv, out, _ := newTestServer(input)
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
notif := readMsg(t, bufio.NewReader(out))
|
||||
var params PublishDiagnosticsParams
|
||||
if err := json.Unmarshal(notif["params"], ¶ms); err != nil {
|
||||
t.Fatalf("unmarshal params: %v", err)
|
||||
}
|
||||
if len(params.Diagnostics) == 0 {
|
||||
t.Error("expected diagnostics for pipeline with unknown stage, got none")
|
||||
}
|
||||
found := false
|
||||
for _, d := range params.Diagnostics {
|
||||
if d.Code == "GL004" {
|
||||
found = true
|
||||
if d.Severity != 1 {
|
||||
t.Errorf("GL004 severity = %d; want 1 (Error)", d.Severity)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("expected GL004 diagnostic, got: %v", params.Diagnostics)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_DidOpen_ParseError(t *testing.T) {
|
||||
uri := "file:///tmp/broken.gitlab-ci.yml"
|
||||
input := frame(t, map[string]any{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "textDocument/didOpen",
|
||||
"params": map[string]any{
|
||||
"textDocument": map[string]any{
|
||||
"uri": uri, "languageId": "yaml", "version": 1,
|
||||
"text": "?", // bare ? yields empty job name → parse error
|
||||
},
|
||||
},
|
||||
})
|
||||
srv, out, _ := newTestServer(input)
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
notif := readMsg(t, bufio.NewReader(out))
|
||||
var params PublishDiagnosticsParams
|
||||
if err := json.Unmarshal(notif["params"], ¶ms); err != nil {
|
||||
t.Fatalf("unmarshal params: %v", err)
|
||||
}
|
||||
if len(params.Diagnostics) == 0 {
|
||||
t.Fatal("expected parse-error diagnostic, got none")
|
||||
}
|
||||
d := params.Diagnostics[0]
|
||||
if d.Severity != 1 {
|
||||
t.Errorf("severity = %d; want 1 (Error)", d.Severity)
|
||||
}
|
||||
if !strings.Contains(d.Message, "YAML parse error") {
|
||||
t.Errorf("message = %q; want YAML parse error", d.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_DidChange(t *testing.T) {
|
||||
uri := "file:///tmp/ci.gitlab-ci.yml"
|
||||
var buf bytes.Buffer
|
||||
// Open with clean content.
|
||||
buf.Write(frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "method": "textDocument/didOpen",
|
||||
"params": map[string]any{"textDocument": map[string]any{
|
||||
"uri": uri, "languageId": "yaml", "version": 1,
|
||||
"text": "stages: [build]\nbuild: {stage: build, script: echo}\n",
|
||||
}},
|
||||
}))
|
||||
// Change to content with an error.
|
||||
buf.Write(frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "method": "textDocument/didChange",
|
||||
"params": map[string]any{
|
||||
"textDocument": map[string]any{"uri": uri, "version": 2},
|
||||
"contentChanges": []map[string]any{
|
||||
{"text": "stages: [build]\nbad: {stage: gone, script: hi}\n"},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
srv, out, _ := newTestServer(buf.Bytes())
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
r := bufio.NewReader(out)
|
||||
_ = readMsg(t, r) // first publishDiagnostics (clean)
|
||||
second := readMsg(t, r)
|
||||
|
||||
var params PublishDiagnosticsParams
|
||||
if err := json.Unmarshal(second["params"], ¶ms); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(params.Diagnostics) == 0 {
|
||||
t.Error("expected diagnostics after change to broken content, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_DidClose_ClearsdiAgnostics(t *testing.T) {
|
||||
uri := "file:///tmp/toclose.gitlab-ci.yml"
|
||||
var buf bytes.Buffer
|
||||
buf.Write(frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "method": "textDocument/didOpen",
|
||||
"params": map[string]any{"textDocument": map[string]any{
|
||||
"uri": uri, "languageId": "yaml", "version": 1,
|
||||
"text": "stages: [build]\nj: {stage: build, script: echo}\n",
|
||||
}},
|
||||
}))
|
||||
buf.Write(frame(t, map[string]any{
|
||||
"jsonrpc": "2.0", "method": "textDocument/didClose",
|
||||
"params": map[string]any{"textDocument": map[string]any{"uri": uri}},
|
||||
}))
|
||||
|
||||
srv, out, _ := newTestServer(buf.Bytes())
|
||||
srv.Run() //nolint:errcheck
|
||||
|
||||
r := bufio.NewReader(out)
|
||||
_ = readMsg(t, r) // publishDiagnostics from didOpen
|
||||
|
||||
closeNotif := readMsg(t, r)
|
||||
var params PublishDiagnosticsParams
|
||||
if err := json.Unmarshal(closeNotif["params"], ¶ms); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if params.URI != uri {
|
||||
t.Errorf("uri = %q; want %q", params.URI, uri)
|
||||
}
|
||||
if len(params.Diagnostics) != 0 {
|
||||
t.Errorf("expected empty diagnostics on close, got %v", params.Diagnostics)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_ContentLengthTooLarge(t *testing.T) {
|
||||
// Craft a header with a content-length that exceeds the cap.
|
||||
// The server must reject it before allocating a giant buffer.
|
||||
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", maxLSPMessageBytes+1)
|
||||
srv, _, _ := newTestServer([]byte(header))
|
||||
err := srv.Run()
|
||||
if err == nil {
|
||||
t.Fatal("expected error for oversized Content-Length, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum") {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_UriToPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
uri string
|
||||
want string
|
||||
}{
|
||||
{"file:///tmp/ci.yml", "/tmp/ci.yml"},
|
||||
{"file:///home/user/project/.gitlab-ci.yml", "/home/user/project/.gitlab-ci.yml"},
|
||||
{"https://example.com/file.yml", ""},
|
||||
{"not-a-uri", ""},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
got := uriToPath(tc.uri)
|
||||
if got != tc.want {
|
||||
t.Errorf("uriToPath(%q) = %q; want %q", tc.uri, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// Package lsp implements a minimal Language Server Protocol server for glint.
|
||||
package lsp
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Message is a JSON-RPC 2.0 message (request, response, or notification).
|
||||
type Message struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Params json.RawMessage `json:"params,omitempty"`
|
||||
Result json.RawMessage `json:"result,omitempty"`
|
||||
Error *RPCError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// RPCError is a JSON-RPC 2.0 error object.
|
||||
type RPCError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// InitializeResult is the server's response to the initialize request.
|
||||
type InitializeResult struct {
|
||||
Capabilities ServerCapabilities `json:"capabilities"`
|
||||
ServerInfo *ServerInfo `json:"serverInfo,omitempty"`
|
||||
}
|
||||
|
||||
// ServerCapabilities advertises what the server supports.
|
||||
type ServerCapabilities struct {
|
||||
// TextDocumentSync: 1 = Full (send entire document on every change).
|
||||
TextDocumentSync int `json:"textDocumentSync"`
|
||||
}
|
||||
|
||||
// ServerInfo identifies the server to the client.
|
||||
type ServerInfo struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version,omitempty"`
|
||||
}
|
||||
|
||||
// TextDocumentItem is a text document opened by the client.
|
||||
type TextDocumentItem struct {
|
||||
URI string `json:"uri"`
|
||||
LanguageID string `json:"languageId"`
|
||||
Version int `json:"version"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// TextDocumentIdentifier references a text document by URI.
|
||||
type TextDocumentIdentifier struct {
|
||||
URI string `json:"uri"`
|
||||
}
|
||||
|
||||
// VersionedTextDocumentIdentifier includes a version number.
|
||||
type VersionedTextDocumentIdentifier struct {
|
||||
URI string `json:"uri"`
|
||||
Version int `json:"version"`
|
||||
}
|
||||
|
||||
// TextDocumentContentChangeEvent is a single content change event.
|
||||
// With Full sync the Text field contains the complete new document text.
|
||||
type TextDocumentContentChangeEvent struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// DidOpenTextDocumentParams is the params for textDocument/didOpen.
|
||||
type DidOpenTextDocumentParams struct {
|
||||
TextDocument TextDocumentItem `json:"textDocument"`
|
||||
}
|
||||
|
||||
// DidChangeTextDocumentParams is the params for textDocument/didChange.
|
||||
type DidChangeTextDocumentParams struct {
|
||||
TextDocument VersionedTextDocumentIdentifier `json:"textDocument"`
|
||||
ContentChanges []TextDocumentContentChangeEvent `json:"contentChanges"`
|
||||
}
|
||||
|
||||
// DidSaveTextDocumentParams is the params for textDocument/didSave.
|
||||
type DidSaveTextDocumentParams struct {
|
||||
TextDocument TextDocumentIdentifier `json:"textDocument"`
|
||||
Text *string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
// DidCloseTextDocumentParams is the params for textDocument/didClose.
|
||||
type DidCloseTextDocumentParams struct {
|
||||
TextDocument TextDocumentIdentifier `json:"textDocument"`
|
||||
}
|
||||
|
||||
// PublishDiagnosticsParams is the params for textDocument/publishDiagnostics.
|
||||
type PublishDiagnosticsParams struct {
|
||||
URI string `json:"uri"`
|
||||
Diagnostics []Diagnostic `json:"diagnostics"`
|
||||
}
|
||||
|
||||
// Diagnostic is a lint finding expressed in LSP terms.
|
||||
type Diagnostic struct {
|
||||
Range Range `json:"range"`
|
||||
Severity int `json:"severity"` // 1=Error, 2=Warning, 3=Information, 4=Hint
|
||||
Code string `json:"code,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// Range is a zero-based line/character range within a text document.
|
||||
type Range struct {
|
||||
Start Position `json:"start"`
|
||||
End Position `json:"end"`
|
||||
}
|
||||
|
||||
// Position is a zero-based line and character offset.
|
||||
type Position struct {
|
||||
Line int `json:"line"`
|
||||
Character int `json:"character"`
|
||||
}
|
||||
@@ -133,6 +133,12 @@ func resolveLocalInclude(p *model.Pipeline, rawPath string, cfg fetcher.GitLabCo
|
||||
absPath := filepath.Join(rootDir, relPath)
|
||||
label := "local " + rawPath
|
||||
|
||||
// Guard against path traversal: reject any path that escapes rootDir.
|
||||
rel, err := filepath.Rel(rootDir, absPath)
|
||||
if err != nil || strings.HasPrefix(rel, "..") {
|
||||
return []IncludeWarning{{Label: label, Err: fmt.Errorf("path escapes repository root: %s", rawPath)}}, nil
|
||||
}
|
||||
|
||||
if visited[absPath] {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.k3nny.fr/glint/internal/fetcher"
|
||||
@@ -332,6 +333,32 @@ func TestResolveLocalInclude_WithNestedIncludes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveLocalInclude_PathTraversal(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := &model.Pipeline{Jobs: map[string]model.Job{}, RawJobs: map[string]map[string]any{}}
|
||||
// A path that escapes the repository root via "../.." must produce a warning,
|
||||
// not silently read an arbitrary file.
|
||||
warnings, _ := resolveLocalInclude(p, "../../etc/passwd", fetcher.GitLabConfig{}, dir, map[string]bool{}, 0)
|
||||
if len(warnings) == 0 {
|
||||
t.Fatal("expected warning for path traversal, got none")
|
||||
}
|
||||
if !strings.Contains(warnings[0].Err.Error(), "path escapes") {
|
||||
t.Errorf("unexpected warning: %v", warnings[0])
|
||||
}
|
||||
if len(p.Jobs) != 0 {
|
||||
t.Error("no jobs should be merged when path escapes root")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveLocalInclude_PathTraversalWithLeadingSlash(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := &model.Pipeline{Jobs: map[string]model.Job{}, RawJobs: map[string]map[string]any{}}
|
||||
warnings, _ := resolveLocalInclude(p, "/../../etc/shadow", fetcher.GitLabConfig{}, dir, map[string]bool{}, 0)
|
||||
if len(warnings) == 0 {
|
||||
t.Fatal("expected warning for path traversal via leading slash, got none")
|
||||
}
|
||||
}
|
||||
|
||||
// ── resolveRemoteInclude ──────────────────────────────────────────────────────
|
||||
|
||||
func TestResolveRemoteInclude_Success(t *testing.T) {
|
||||
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
stages: [build]
|
||||
|
||||
include:
|
||||
- remote: http://ci-templates.example.invalid/template.yml
|
||||
|
||||
build-job:
|
||||
stage: build
|
||||
script: echo hello
|
||||
Reference in New Issue
Block a user