diff --git a/.gitignore b/.gitignore index 915635e..79c4810 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.DS_Store .vscode/ .idea/ *.sqlite diff --git a/CHANGELOG.md b/CHANGELOG.md index fcea782..d36c65d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ ## vX.X.X (YYYY-MM-DD) +### Added +- Challenge repository management through the admin API: list, clone (only from the URL prefixes of the new `repositories.sources`, with optional per-source tokens kept out of the clones), update (fetch and reset to the followed branch or tag, naming the local changes it discards; a clone or update the server answers with a credentials prompt fails with "the repository does not exist, or it is private and its source in repositories.sources has no token able to read it" instead of git's askpass message) and remove (refused while instances of its challenges exist) the top-level folders of `challenge_dir`, reloading the challenge index afterwards (an update builds nothing: builds are explicit) +- `GET /admin/challenges` lists every challenge definition, whatever its type, with its full content, its repository's `commit`, its build plan (`build.buildable`, `build.refused`), its declared `files` resolved in the challenge folder then its `files/` subfolder (`{declared, path, size, error}`; Git LFS pointers are errors) and the definitions that could not be read (404 for an unknown `repo`); `GET /admin/challenges/file` serves the files of challenge folders (or their SHA-1), refusing `.git` and paths leading outside the challenge folder. A CTF platform can import challenges without access to the server +- `POST /admin/build` builds challenge images on every Ansible host (BuildKit, Docker Compose), `POST /admin/images` checks or removes them (state of each image per host; `unreachable` or `error` on a host the check could not run on, never left out); settings in the new `build` section. Challenges are named by their definition path (`{path}`, or `{category, name}`) in requests, and by definition path in results (`built`, `failed` with refused builds, `skipped`; `challenges` of an image action) +- Long admin actions run as background operations, one at a time, with their log: `GET /admin/operations`, `GET /admin/operations/{id}`, `POST /admin/operations/{id}/cancel` (409 for a finished operation); an operation is reported finished once the next one can start. A cancelled build or image action stops ansible-playbook (SIGTERM, which stops its workers; 15 s later, every local process of the run is killed, on Linux), then what it started on the hosts (processes marked with the run's `GALVANIZE_RUN_ID`, build folder), within 55 s, before the operation ends and the next one can start; a cancelled run is reported cancelled even when ansible-playbook exited 0, and a panic in a build fails that build only +- The Docker image includes git + +### Changed +- A Compose service with a `build` section but no `image` is deployed as `galvanize/---:latest`, the name the build gives it: such services could not be deployed before (the build context does not exist on the host) +- Hidden folders of `challenge_dir` (`.github`, temporary clones...) are no longer indexed: a challenge in a folder whose name starts with `.` disappears from the index +- A challenge deployed from `deploy_parameters.image` without a Dockerfile in its folder is taken to use an image from a registry: building it does nothing (ctfd-management's `challenges.sh` failed its build) +- Every JWT must have an expiry (`exp`); repository, build, image, challenge-file and operation endpoints also need the `manage` scope +- `deploy_parameters.compose_file`, and an auto-detected Compose file, must stay inside the challenge folder (symlinks included), also next to an inline `compose_definition`; otherwise the definition is skipped +- `build.protected_images` defaults no longer include `ctfd/ctfd`: list the CTF platform's images in the setting +- A challenge definition JSON cannot encode (`.nan`, keys that are not strings once converted) is skipped instead of breaking `GET /admin/challenges` + +### Fixed +- Ansible's SSH control socket was shared by all the hosts of a run (`%%h` reaches ssh as a literal `%h`), so with several hosts a task could run on the wrong one +- A config file changed in several writes (`cp` truncates it first) could be reloaded half written, leaving Galvanize with an empty config until a restart: the change is now applied once the file has not changed for 500 ms, and a reloaded config without `challenge_dir` or `ansible_dir` is refused (the current one is kept) + ## v0.7.5 (2026-11-11) ### Added diff --git a/README.md b/README.md index 3fb76bd..0f299b3 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,56 @@ The API is documented in `galvanize-instancer/api/openapi.yaml`. Main endpoints: All endpoints except `/health` require a JWT bearer token. Tokens are generated automatically by the Zync plugin. +Admin endpoints (role `admin`) also manage the challenges themselves, see [Challenge repositories](#challenge-repositories). Every token must carry an expiry (`exp`). + +## Challenge repositories + +Galvanize owns its challenge folder (`challenge_dir`). Each top-level folder of it is a repository: a git clone made through the API, or a folder copied there by hand. The admin API lets any client (Zync, a script, curl) manage them without access to the server. + +These endpoints need an admin token whose `scope` claim is `manage`. The CTF platform's server puts it in the tokens it uses for its own calls; the admin tokens a dashboard hands to browsers must not have it, so that they can manage instances but not clone repositories, run builds on the hosts or read challenge files. + +| Endpoint | What it does | +|---|---| +| `GET /admin/repos` | Repositories with their git state (remote, branch or tag, commit, local changes), and the allowed clone sources | +| `POST /admin/repos` | Clone `{url, name?, ref?, force?}`. The URL must be inside one of `repositories.sources` (cloning is disabled without any). `force` replaces an existing folder once the new clone succeeded | +| `POST /admin/repos/{name}/pull` | Fetch the branch or tag the repository follows and reset the folder to it (local changes are discarded). Images are not rebuilt: build them with `/admin/build` | +| `DELETE /admin/repos/{name}` | Delete the folder. Refused while instances of its challenges exist | +| `GET /admin/challenges[?repo=]` | Every challenge definition, whatever its type, with its full content, its repository's `commit`, its declared `files` and what building it means (`build`); definitions that could not be read are listed in `skipped` | +| `GET /admin/challenges/file?path=[&checksum=true]` | A file of a challenge folder (or its SHA-1 and size). Paths into `.git`, or leading outside the challenge folder, are refused | +| `POST /admin/build` | Build images `{repo?, challenges?, no_cache?}` on every Ansible host. The result lists the definition paths `built`, `failed` (refused builds included) and `skipped` (nothing to build) | +| `POST /admin/images` | `{action: status\|remove, repo?, challenges?}`: which images exist on each host, or remove the built ones (pulled images, images another challenge folder uses and platform images are never removed; refused while instances use them). The result maps each image to its state per host (`images`: `present`, `absent`, `removed`, `failed` when the removal failed, or `unreachable`/`error` on a host that did not answer or where the check failed) and each definition path to its images (`challenges`) | +| `GET /admin/operations[/{id}?offset=]` | Clones, pulls, removals, builds and image actions run in the background, one at a time: their status, result and log (from line `offset`) | +| `POST /admin/operations/{id}/cancel` | Cancel a running operation | + +After a clone, pull or removal, the challenge index is reloaded. + +Challenges are named by their definition file, relative to `challenge_dir` (`path` in the listing): `challenges` of a build or image request is a list of `{path}` (or `{category, name}`), and results use these paths. + +**Declared files.** Each entry of a definition's `files` list is looked up in the challenge folder, then in its `files/` subfolder. The listing gives, for each one, `{declared, path, size}` (`path` to download with `/admin/challenges/file`), or an `error`: not found, absolute path, path leaving the challenge folder (symlinks included) or going through `.git`, or a Git LFS pointer (the repository was cloned without `git-lfs`). The listing does not hash files: ask `checksum=true` for the files whose SHA-1 you need. + +**Commit.** `commit` is the repository's current commit: a client comparing it before and after a long task knows whether the repository changed in between (e.g. a pull). + +**Sources.** A `url_prefix` is a URL ending with `/` (`https://github.com/your-org/`). A clone URL is allowed when it has the same scheme, host and port and its path continues the prefix's folders: `https://github.com/your-org-evil/x`, `https://github.com.evil.tld/your-org/x` and `https://github.com/your-org/../other/x` are refused, and so are URLs with credentials, a query, percent-encoding or `.`/`..` segments. Schemes: `https`, `http`, `ssh`, `git` and `file` (`git://` and `http://` are unauthenticated and unencrypted: keep them for a lab network). + +**Credentials.** For a private repository, set `token` on its `https` source in `config.yaml`. Git receives it through its environment for each command, as a header scoped to the source's URL (an LFS server named by a repository's `.lfsconfig` does not get it, and redirects are not followed); it never appears in a URL, a command line, the API or the clone's `.git/config`. Clients cannot pass credentials: a URL holding some is refused. Git runs without hooks or fsmonitor. + +**Builds** run where the instances run: Galvanize sends the challenge folder (without `.git`, and without symlinks leading outside it) to every Ansible host and runs Docker there, so builds use BuildKit and Compose and a deployment finds its images locally (the playbooks deploy with `pull: missing`): + +- a challenge deployed from one image (`http`, `tcp`...) is built from the first `Dockerfile*` of its folder (`Dockerfile` preferred), tagged `deploy_parameters.image`. Without a Dockerfile, the image is taken to come from a registry (pulled at deployment) and there is nothing to build; +- a `custom_compose` challenge has its services with a `build` section built, from its Compose file when there is one (`deploy_parameters.compose_file`, else `compose.yaml`, `compose.yml`, `docker-compose.yaml` or `docker-compose.yml`; it must stay inside the challenge folder, symlinks included), even with an inline `compose_definition`, which usually references the images the file builds; otherwise from the inline definition. When both exist, a service must have the same image in both, or the build is refused. A built service without `image` is tagged `galvanize/---:latest` (the hash of the exact names keeps two challenges apart even when their names give the same slug), and the index gives it the same name for deployments. + +What a repository may build is limited, since anyone who can push to it decides what runs on the hosts: + +- a `build` section may only use `context`, `dockerfile`, `dockerfile_inline`, `args`, `target`, `labels`, `shm_size`, `no_cache`, `pull` and `platforms`; contexts and Dockerfiles are relative paths inside the challenge folder (no host network, secrets, SSH agent, extra contexts, host caches or extra tags); +- image, service and Dockerfile names must be plain names; +- a challenge may not build an image another challenge folder deploys, builds or builds `FROM` (challenges of one folder share theirs), nor a platform image (`build.protected_images`; by default Galvanize's images, Traefik, Redis, MariaDB, MySQL and PostgreSQL: list your CTF platform's images there too, the list replaces the defaults). A local image of that name would replace the real one for everyone: deployments use `pull: missing`. + +The listing shows refused builds with `build.refused` and the reason, and `build.buildable` tells whether building the challenge builds anything (it is deployable and its plan is `image` or `compose`). A build request may name challenges with nothing to build or refused: they come back as `skipped` or `failed`. Values sent to the build playbooks are marked unsafe for Ansible, so a name holding `{{ ... }}` is never rendered. + +The build and image playbooks are part of the binary (they do not need to be in `ansible_dir`). + +**Trust.** Cloning a repository means trusting everyone who can push to it: its challenges' Dockerfiles run on every Ansible host, and their deployment parameters reach the deployment playbooks. Allow only repositories whose writers you trust as much as the hosts' administrators, and keep Galvanize's API off the Internet when you can (only the CTF platform's server needs it for these endpoints). + ## Challenge Definitions Example challenge files (one per playbook type): diff --git a/config.example.yaml b/config.example.yaml index 892cbc7..917c16f 100755 --- a/config.example.yaml +++ b/config.example.yaml @@ -31,6 +31,24 @@ instancer: cpus: "1" # CPU limit per container (e.g. "0.5", "1", "2") memory: "512M" # Memory limit per container (e.g. "256M", "512M", "1G") pids_limit: 256 # Max number of PIDs per container (fork bomb protection) + repositories: # Challenge repositories managed through the admin API (/admin/repos) + # Clones are allowed only from URLs inside one of these prefixes (same + # scheme, host and port, path below the prefix's folder; the prefix must + # end with "/"). With no source, cloning is disabled (repositories already + # in challenge_dir can still be listed, updated and removed). + sources: + - url_prefix: "https://github.com/your-org/" + # token: "" # optional, https only, for private repositories (read-only token); never written to the clone + # username: "x-access-token" # HTTP user sent with the token (default: x-access-token) + git_timeout: "10m" # Time limit of one git command (default: 10m) + build: # Image builds (/admin/build), run with Docker on every Ansible host + concurrency: 2 # Challenges built at the same time (default: 2) + timeout: "30m" # Time limit of one challenge build (default: 30m) + # Images challenges may never build (repository, any tag; or a prefix + # ending with "/"). Unset: traefik, mariadb, mysql, redis, postgres and + # ghcr.io/28pollux28/. Setting it replaces the defaults: list them with + # your CTF platform's images. + # protected_images: ["traefik", "mariadb", "mysql", "redis", "postgres", "ghcr.io/28pollux28/", "ctfd/ctfd"] extra_deployment_parameters: # Additional parameters for deployment (added to vars in Ansible) # Name of the external Docker network Traefik watches on the target host(s). # Required for http challenges and for http exposures in compose challenges. diff --git a/galvanize-instancer/Dockerfile b/galvanize-instancer/Dockerfile index 5303961..1cdc85a 100755 --- a/galvanize-instancer/Dockerfile +++ b/galvanize-instancer/Dockerfile @@ -16,9 +16,11 @@ LABEL authors="28Pollux28" RUN useradd -ms /bin/bash galvanize -# Install curl to allow health checks, ansible, and tini for zombie process reaping -RUN apt-get update && apt-get install -y curl pipx ssh-client tini \ +# Install curl to allow health checks, ansible, tini for zombie process +# reaping, and git with Git LFS for the challenge repositories (admin API) +RUN apt-get update && apt-get install -y curl git git-lfs pipx ssh-client tini \ && rm -rf /var/lib/apt/lists/* \ + && git lfs install --system --skip-repo \ && pipx ensurepath --global \ && pipx install --include-deps --global ansible \ && ansible-galaxy collection install community.docker -p /usr/share/ansible/collections diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index 0d86b6f..19cb8f0 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -393,6 +393,400 @@ paths: schema: $ref: '#/components/schemas/Error' + /admin/repos: + get: + summary: List challenge repositories (admin only) + description: >- + Like every repository, build, image, challenge-file and operation endpoint, + this needs an admin token whose scope claim is "manage" (issued by the CTF + platform's server for its own calls, never handed to browsers). + Every top-level folder of challenge_dir, with its git state, and the URL prefixes clones are allowed from. + operationId: listRepositories + security: + - bearerAuth: [ ] + responses: + '200': + description: Repositories + content: + application/json: + schema: + $ref: '#/components/schemas/RepositoryList' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + summary: Clone a challenge repository (admin only) + description: Starts an operation that clones the repository into challenge_dir, then reloads the challenge index. The URL must start with one of repositories.sources. + operationId: cloneRepository + security: + - bearerAuth: [ ] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CloneRepositoryRequest' + responses: + '202': + description: Operation started + content: + application/json: + schema: + $ref: '#/components/schemas/Operation' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required, or URL not allowed + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '409': + description: Another operation is running, or the repository exists + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /admin/repos/{name}/pull: + post: + summary: Update a challenge repository (admin only) + description: Starts an operation that fetches the branch or tag the repository follows and resets the folder to it (local changes are discarded), then reloads the challenge index. It builds no image (see /admin/build). + operationId: pullRepository + security: + - bearerAuth: [ ] + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '202': + description: Operation started + content: + application/json: + schema: + $ref: '#/components/schemas/Operation' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '404': + description: Repository not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '409': + description: Another operation is running + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /admin/repos/{name}: + delete: + summary: Remove a challenge repository (admin only) + description: Starts an operation that deletes the repository folder, then reloads the challenge index. Refused while instances of its challenges exist. + operationId: removeRepository + security: + - bearerAuth: [ ] + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '202': + description: Operation started + content: + application/json: + schema: + $ref: '#/components/schemas/Operation' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '404': + description: Repository not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '409': + description: Another operation is running, or instances of its challenges exist + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /admin/challenges: + get: + summary: List challenge definitions (admin only) + description: Every challenge definition file of the challenge index, whatever its type, with its full content (flags included), the files it declares, its repository's commit and what building it means. + operationId: listChallengeDefinitions + security: + - bearerAuth: [ ] + parameters: + - name: repo + in: query + required: false + description: Only the challenges of this repository + schema: + type: string + responses: + '200': + description: Challenge definitions + content: + application/json: + schema: + $ref: '#/components/schemas/ChallengeDefinitionList' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '404': + description: Repository not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /admin/challenges/file: + get: + summary: Download a file of a challenge (admin only) + description: A file inside the folder of a challenge of the index (e.g. the path of a declared file, see ChallengeFile). Paths into .git folders, or leading outside the challenge folder, are refused. + operationId: getChallengeFile + security: + - bearerAuth: [ ] + parameters: + - name: path + in: query + required: true + description: Path relative to challenge_dir + schema: + type: string + - name: checksum + in: query + required: false + description: Return the file's SHA-1 and size (JSON) instead of its content + schema: + type: boolean + responses: + '200': + description: File content, or its checksum + content: + application/octet-stream: + schema: + type: string + format: binary + application/json: + schema: + $ref: '#/components/schemas/FileChecksum' + '400': + description: Invalid path + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '404': + description: File not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /admin/build: + post: + summary: Build challenge images (admin only) + description: >- + Starts an operation that builds the challenges' images with Docker on every Ansible host. + Its result lists the definition paths (relative to challenge_dir) built, failed (refused + builds included) and skipped (nothing to build). + operationId: buildChallenges + security: + - bearerAuth: [ ] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BuildRequest' + responses: + '202': + description: Operation started + content: + application/json: + schema: + $ref: '#/components/schemas/Operation' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '409': + description: Another operation is running + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /admin/images: + post: + summary: Check or remove challenge images (admin only) + description: >- + Starts an operation that checks (status) or removes (remove) the challenges' images on every + Ansible host. Pulled images are never removed. Its result maps each image to its state per + host (images), and each definition path to its images (challenges). States: present or + absent (status); removed, absent or failed (remove: the image is still there); unreachable + (the host did not answer) or error (the task failed on the host) for every image of a host + the check did not run on. + operationId: manageImages + security: + - bearerAuth: [ ] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ImagesRequest' + responses: + '202': + description: Operation started + content: + application/json: + schema: + $ref: '#/components/schemas/Operation' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '409': + description: Another operation is running + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /admin/operations: + get: + summary: List recent operations (admin only) + description: The most recent repository, build and image operations, without their log. + operationId: listOperations + security: + - bearerAuth: [ ] + responses: + '200': + description: Operations, the most recent first + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Operation' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + + /admin/operations/{id}: + get: + summary: Get an operation and its log (admin only) + operationId: getOperation + security: + - bearerAuth: [ ] + parameters: + - name: id + in: path + required: true + schema: + type: string + - name: offset + in: query + required: false + description: Return the log lines from this index on + schema: + type: integer + responses: + '200': + description: The operation + content: + application/json: + schema: + $ref: '#/components/schemas/Operation' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '404': + description: Operation not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /admin/operations/{id}/cancel: + post: + summary: Cancel a running operation (admin only) + operationId: cancelOperation + security: + - bearerAuth: [ ] + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + '202': + description: Cancellation requested + '401': + description: Unauthorized + '403': + description: Forbidden - Admin token with the "manage" scope required + '404': + description: Operation not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '409': + description: The operation already finished + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + components: securitySchemes: bearerAuth: @@ -597,6 +991,292 @@ components: - indexed - skipped + Repository: + type: object + properties: + name: + type: string + is_git: + type: boolean + remote: + type: string + description: Remote URL, without credentials + branch: + type: string + description: Current branch, empty when HEAD is detached (tag) + ref: + type: string + description: Branch or tag the repository follows on update + commit: + type: string + commit_message: + type: string + commit_time: + type: string + format: date-time + dirty: + type: boolean + description: Tracked files differ from the commit + challenges: + type: integer + description: Challenge definitions in the folder + error: + type: string + required: + - name + - is_git + - challenges + + RepositoryList: + type: object + properties: + repositories: + type: array + items: + $ref: '#/components/schemas/Repository' + clone_sources: + type: array + description: URL prefixes clones are allowed from (empty means cloning is disabled) + items: + type: string + required: + - repositories + - clone_sources + + CloneRepositoryRequest: + type: object + properties: + url: + type: string + name: + type: string + description: Folder name (default from the URL) + ref: + type: string + description: Branch or tag (default branch of the remote) + force: + type: boolean + description: Replace an existing folder of that name + required: + - url + + ChallengeRef: + type: object + description: A deployable challenge, by definition file (path) or by category and name + properties: + path: + type: string + description: Definition file, relative to challenge_dir (as ChallengeDefinition.path) + category: + type: string + name: + type: string + + BuildRequest: + type: object + description: The challenges to work on, by repository or by name (both may be given; neither means every challenge) + properties: + repo: + type: string + challenges: + type: array + items: + $ref: '#/components/schemas/ChallengeRef' + no_cache: + type: boolean + + ImagesRequest: + type: object + properties: + action: + type: string + enum: [ status, remove ] + repo: + type: string + challenges: + type: array + items: + $ref: '#/components/schemas/ChallengeRef' + required: + - action + + BuildPlan: + type: object + properties: + kind: + type: string + enum: [ image, compose, none ] + reason: + type: string + description: Why there is nothing to build, or why the build is refused + refused: + type: boolean + description: >- + There is something to build, but the challenge may not build it (unsafe + build section, invalid name, image used by another challenge folder or + by the platform, compose file and deployment disagreeing on an image) + images: + type: array + items: + type: string + buildable: + type: boolean + description: A build of this challenge builds something (it is deployable, and kind is image or compose) + required: + - kind + - images + - buildable + + ChallengeFile: + type: object + description: >- + A file of the definition's files list, looked up in the challenge folder, then in its files/ + subfolder. Absolute paths, paths leaving the challenge folder (symlinks included) or going + through .git, and Git LFS pointers are errors. + properties: + declared: + type: string + description: The path as written in the definition + path: + type: string + description: The file found, relative to challenge_dir (to download with /admin/challenges/file) + size: + type: integer + format: int64 + error: + type: string + description: Why the file cannot be served + required: + - declared + + ChallengeDefinition: + type: object + properties: + category: + type: string + name: + type: string + type: + type: string + playbook_name: + type: string + repository: + type: string + description: Repository folder, empty for a challenge directly in challenge_dir + path: + type: string + description: Definition file, relative to challenge_dir + dir: + type: string + description: Challenge folder, relative to challenge_dir + deployable: + type: boolean + description: The challenge can be deployed (type zync, in the deployment index) + build: + $ref: '#/components/schemas/BuildPlan' + files: + type: array + items: + $ref: '#/components/schemas/ChallengeFile' + commit: + type: string + description: Current commit of the repository (abbreviated), when it is a git clone + definition: + type: object + additionalProperties: true + description: The whole definition file as parsed + required: + - category + - name + - type + - repository + - path + - dir + - deployable + - build + - files + - definition + + ChallengeDefinitionList: + type: object + properties: + challenges: + type: array + items: + $ref: '#/components/schemas/ChallengeDefinition' + skipped: + type: array + items: + $ref: '#/components/schemas/SkippedChallenge' + required: + - challenges + - skipped + + OperationLine: + type: object + properties: + time: + type: string + format: date-time + level: + type: string + enum: [ debug, info, success, warning, error ] + message: + type: string + required: + - time + - level + - message + + Operation: + type: object + properties: + id: + type: string + kind: + type: string + enum: [ clone, pull, remove, build, images ] + target: + type: string + status: + type: string + enum: [ running, success, warning, failed, cancelled ] + created_at: + type: string + format: date-time + finished_at: + type: string + format: date-time + result: + type: object + additionalProperties: true + lines: + type: array + items: + $ref: '#/components/schemas/OperationLine' + line_count: + type: integer + required: + - id + - kind + - target + - status + - created_at + - lines + - line_count + + FileChecksum: + type: object + properties: + sha1: + type: string + size: + type: integer + format: int64 + required: + - sha1 + - size + SkippedChallenge: type: object properties: diff --git a/galvanize-instancer/cmd/root.go b/galvanize-instancer/cmd/root.go index cdfe11c..119975b 100755 --- a/galvanize-instancer/cmd/root.go +++ b/galvanize-instancer/cmd/root.go @@ -25,9 +25,14 @@ func SetVersion(version string) { var cfgFile string +// The changes of the config file are applied once it has not changed for +// reloadDelay: a copy writes it in several steps, and only the last one +// must be read. +const reloadDelay = 500 * time.Millisecond + var ( - lastReload time.Time - reloadMu sync.Mutex + reloadTimer *time.Timer + reloadMu sync.Mutex ) func Execute() { @@ -52,7 +57,7 @@ func initConfig() { viper.SetConfigFile(cfgFile) viper.SetConfigType("yaml") - setConfigDefaults() + setConfigDefaults(viper.GetViper()) if err := viper.ReadInConfig(); err != nil { zap.S().Fatalf("Error reading config file: %v", err) @@ -69,24 +74,35 @@ func initConfig() { } // setConfigDefaults sets the defaults of the settings a config may omit. -func setConfigDefaults() { - viper.SetDefault("instancer.deployment_ttl", "1h") - viper.SetDefault("instancer.deployment_ttl_extension", "30m") - viper.SetDefault("instancer.deployment_max_extensions", 3) - viper.SetDefault("instancer.deployment_extension_window", "30m") +func setConfigDefaults(v *viper.Viper) { + v.SetDefault("instancer.deployment_ttl", "1h") + v.SetDefault("instancer.deployment_ttl_extension", "30m") + v.SetDefault("instancer.deployment_max_extensions", 3) + v.SetDefault("instancer.deployment_extension_window", "30m") } func handleConfigChange(filename string) { reloadMu.Lock() defer reloadMu.Unlock() - - if time.Since(lastReload) < 500*time.Millisecond { - return // ignore duplicate events + if reloadTimer != nil { + reloadTimer.Stop() } - lastReload = time.Now() - zap.S().Infof("Config file %s changed", filename) + reloadTimer = time.AfterFunc(reloadDelay, func() { reloadConfig(filename) }) +} - if err := config.Reload(); err != nil { +// reloadConfig reads the config file again, in a viper of its own: the +// global one is read by viper's watcher, possibly in the middle of a write. +func reloadConfig(filename string) { + zap.S().Infof("Config file %s changed", filename) + v := viper.New() + v.SetConfigFile(cfgFile) + v.SetConfigType("yaml") + setConfigDefaults(v) + if err := v.ReadInConfig(); err != nil { + zap.S().Errorf("Error reading the changed config, the current one is kept: %v", err) + return + } + if err := config.Reload(v); err != nil { zap.S().Errorf("Error reloading config: %v", err) return } diff --git a/galvanize-instancer/cmd/root_test.go b/galvanize-instancer/cmd/root_test.go index 8f44cbc..400eed6 100644 --- a/galvanize-instancer/cmd/root_test.go +++ b/galvanize-instancer/cmd/root_test.go @@ -20,7 +20,7 @@ func TestSetConfigDefaults(t *testing.T) { path := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(path, []byte("instancer:\n instancer_host: example.org\n"), 0o600)) - setConfigDefaults() + setConfigDefaults(viper.GetViper()) viper.SetConfigFile(path) require.NoError(t, viper.ReadInConfig()) require.NoError(t, config.Load()) @@ -31,3 +31,34 @@ func TestSetConfigDefaults(t *testing.T) { assert.Equal(t, 30*time.Minute, ic.DeploymentTTLExtension) assert.Equal(t, 30*time.Minute, ic.DeploymentExtensionWindow) } + +// A config file read while it is being written is not applied, and the +// complete file is applied once the writes stop +func TestReloadConfig_IgnoresAPartlyWrittenFile(t *testing.T) { + t.Cleanup(viper.Reset) + viper.Reset() + cfgFile = filepath.Join(t.TempDir(), "config.yaml") + t.Cleanup(func() { cfgFile = "" }) + write := func(content string) { require.NoError(t, os.WriteFile(cfgFile, []byte(content), 0o600)) } + full := func(host string) string { + return "instancer:\n instancer_host: " + host + "\n challenge_dir: /c\n ansible_dir: /a\n" + } + write(full("old.example.org")) + viper.SetConfigFile(cfgFile) + require.NoError(t, viper.ReadInConfig()) + require.NoError(t, config.Load()) + + for _, partial := range []string{"", "instancer:\n instancer_host: new.example.org\n"} { + write(partial) + reloadConfig(cfgFile) + assert.Equal(t, "old.example.org", config.Get().Instancer.InstancerHost, "%q is not applied", partial) + } + + write("") + handleConfigChange(cfgFile) + write(full("new.example.org")) + handleConfigChange(cfgFile) + require.Eventually(t, func() bool { return config.Get().Instancer.InstancerHost == "new.example.org" }, + 5*reloadDelay, 10*time.Millisecond) + assert.Equal(t, time.Hour, config.Get().Instancer.DeploymentTTL, "with the defaults") +} diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index ff50c7f..05d9d6f 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -213,7 +213,9 @@ var serveCmd = &cobra.Command{ workerPool.Stop() } - shutdownCtx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) + // The running operation is cancelled and stopped within + // shutdownTimeout (srv.Wait) + shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) defer cancel() if err := e.Shutdown(shutdownCtx); err != nil { zap.S().Fatalf("Failed to shutdown server: %v", err) @@ -234,6 +236,11 @@ var serveCmd = &cobra.Command{ }, } +// shutdownTimeout bounds the shutdown: stop_grace_period is 1 min in the +// compose files, after which Docker kills Galvanize. Stopping a cancelled +// build or image action takes up to ansible.StopDuration, which must fit. +const shutdownTimeout = 1 * time.Minute + // metricsHandler wraps h with HTTP Basic Auth if a password is configured. // If password is empty the handler is returned as-is (no auth). func metricsHandler(username, password string, h http.Handler) http.Handler { @@ -272,14 +279,16 @@ func configureQueueless(cfg *config.Config, jobQueue *worker.Queue, expirySched return teamDeployer } -// jwtMiddleware requires a valid HS256 token signed with secret on every -// route but /health; handlers then check the claims' role. +// jwtMiddleware requires a valid HS256 token signed with secret, with an +// expiry, on every route but /health; handlers then check the claims' role +// (and scope). A token without exp would stay valid forever. func jwtMiddleware(secret string) echo.MiddlewareFunc { + key := []byte(secret) return echojwt.WithConfig(echojwt.Config{ - NewClaimsFunc: func(c echo.Context) jwt.Claims { - return new(auth.Claims) + ParseTokenFunc: func(c echo.Context, raw string) (interface{}, error) { + return jwt.ParseWithClaims(raw, new(auth.Claims), func(*jwt.Token) (interface{}, error) { return key, nil }, + jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}), jwt.WithExpirationRequired()) }, - SigningKey: []byte(secret), Skipper: func(c echo.Context) bool { return c.Path() == "/health" }, diff --git a/galvanize-instancer/cmd/serve_test.go b/galvanize-instancer/cmd/serve_test.go index 9e66cff..5e7846d 100644 --- a/galvanize-instancer/cmd/serve_test.go +++ b/galvanize-instancer/cmd/serve_test.go @@ -4,6 +4,7 @@ import ( "net/http" "net/http/httptest" "testing" + "time" "github.com/28Pollux28/galvanize/internal/ansible" "github.com/28Pollux28/galvanize/pkg/config" @@ -81,3 +82,11 @@ func TestConfigureQueueless_WithRedis(t *testing.T) { assert.Nil(t, got, "the server keeps its default deployer") assert.Nil(t, sched.DirectTerminationDeployer(), "expiries go to the queue") } + +func TestShutdownLeavesTimeToStopTheRuns(t *testing.T) { + // Stopping a cancelled build or image action (ansible-playbook, then the + // stop playbook on the hosts) must end before Docker kills Galvanize + // (stop_grace_period: 1m), or the hosts are not cleaned + assert.Less(t, ansible.StopDuration(), shutdownTimeout) + assert.LessOrEqual(t, shutdownTimeout, time.Minute, "the compose files' stop_grace_period") +} diff --git a/galvanize-instancer/cmd/version_test.go b/galvanize-instancer/cmd/version_test.go index 462d1d7..63d563a 100644 --- a/galvanize-instancer/cmd/version_test.go +++ b/galvanize-instancer/cmd/version_test.go @@ -27,7 +27,10 @@ func newAPI(version string) *echo.Echo { func signed(t *testing.T, method jwt.SigningMethod, key interface{}, role string, expires time.Time) string { t.Helper() - claims := &auth.Claims{Role: role, TeamID: "team1", RegisteredClaims: jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(expires)}} + claims := &auth.Claims{Role: role, TeamID: "team1"} + if !expires.IsZero() { + claims.ExpiresAt = jwt.NewNumericDate(expires) + } token, err := jwt.NewWithClaims(method, claims).SignedString(key) require.NoError(t, err) return token @@ -59,6 +62,7 @@ func TestVersion_OnlyForAdmins(t *testing.T) { "wrong key": {signed(t, jwt.SigningMethodHS256, []byte("another-secret"), "admin", hour), http.StatusUnauthorized}, "unsigned (none)": {signed(t, jwt.SigningMethodNone, jwt.UnsafeAllowNoneSignatureType, "admin", hour), http.StatusUnauthorized}, "expired admin": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", time.Now().Add(-time.Minute)), http.StatusUnauthorized}, + "admin, no exp": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", time.Time{}), http.StatusUnauthorized}, "player": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "player", hour), http.StatusForbidden}, "no role": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "", hour), http.StatusForbidden}, } { diff --git a/galvanize-instancer/go.mod b/galvanize-instancer/go.mod index 7a1e281..8b54b6f 100755 --- a/galvanize-instancer/go.mod +++ b/galvanize-instancer/go.mod @@ -11,6 +11,7 @@ require ( github.com/labstack/echo-contrib v0.17.4 github.com/labstack/echo-jwt/v4 v4.4.0 github.com/labstack/echo/v4 v4.15.0 + github.com/oapi-codegen/runtime v1.1.2 github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 github.com/prometheus/client_golang v1.23.2 github.com/redis/go-redis/v9 v9.17.3 @@ -24,6 +25,7 @@ require ( ) require ( + github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect github.com/apenella/go-common-utils/data v0.0.0-20220913191136-86daaa87e7df // indirect github.com/apenella/go-common-utils/error v0.0.0-20220913191136-86daaa87e7df // indirect github.com/beorn7/perks v1.0.1 // indirect diff --git a/galvanize-instancer/go.sum b/galvanize-instancer/go.sum index 50dda45..dea94a4 100755 --- a/galvanize-instancer/go.sum +++ b/galvanize-instancer/go.sum @@ -1,3 +1,6 @@ +github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= +github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= +github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= github.com/apenella/go-ansible/v2 v2.4.1 h1:bepwxCNIVg3185dKmb60jhNhgvVWvVpICCnGHEF9MQc= github.com/apenella/go-ansible/v2 v2.4.1/go.mod h1:C9u9Srpd/PEjv+r4lLYDFc1s9ebK8rBY/DWmnZ/ohXo= github.com/apenella/go-common-utils/data v0.0.0-20220913191136-86daaa87e7df h1:sEikY2P+NZK/7VZUwIsnXIGElhsuFDSxh1bZYwHxdcI= @@ -6,6 +9,7 @@ github.com/apenella/go-common-utils/error v0.0.0-20220913191136-86daaa87e7df h1: github.com/apenella/go-common-utils/error v0.0.0-20220913191136-86daaa87e7df/go.mod h1:+3dyIlHX350xJIUIffwMLswZXU+N2FwDE05VuKqxYdw= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= @@ -81,6 +85,7 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -115,6 +120,8 @@ github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/oapi-codegen/oapi-codegen/v2 v2.5.1 h1:5vHNY1uuPBRBWqB2Dp0G7YB03phxLQZupZTIZaeorjc= github.com/oapi-codegen/oapi-codegen/v2 v2.5.1/go.mod h1:ro0npU1BWkcGpCgGD9QwPp44l5OIZ94tB3eabnT7DjQ= +github.com/oapi-codegen/runtime v1.1.2 h1:P2+CubHq8fO4Q6fV1tqDBZHCwpVpvPg7oKiYzQgXIyI= +github.com/oapi-codegen/runtime v1.1.2/go.mod h1:SK9X900oXmPWilYR5/WKPzt3Kqxn/uS/+lbpREv+eCg= github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY= github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw= github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c= @@ -178,9 +185,11 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= +github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= diff --git a/galvanize-instancer/internal/ansible/playbook.go b/galvanize-instancer/internal/ansible/playbook.go index d09bc7e..8ad1f09 100644 --- a/galvanize-instancer/internal/ansible/playbook.go +++ b/galvanize-instancer/internal/ansible/playbook.go @@ -119,9 +119,7 @@ func PreparePlaybook(conf *config.Config, tag string, challenge *challenge.Chall // SSH args with unique control path per playbook run to prevent shared socket issues // Add connection timeout (30s) and ServerAliveInterval to detect dead connections - uniqueID := generateRandomID() - sshArgs := "-o ControlMaster=auto -o ControlPersist=30s -o ControlPath=/tmp/ansible-ssh-%%h-%%p-%%r-" + uniqueID + - " -o ConnectTimeout=30 -o ServerAliveInterval=10 -o ServerAliveCountMax=3" + sshArgs := SSHArgs(generateRandomID()) defaultExecutor := execute.NewDefaultExecute( execute.WithCmd(pbCmd), diff --git a/galvanize-instancer/internal/ansible/process.go b/galvanize-instancer/internal/ansible/process.go new file mode 100644 index 0000000..0636e5b --- /dev/null +++ b/galvanize-instancer/internal/ansible/process.go @@ -0,0 +1,175 @@ +package ansible + +import ( + "bytes" + "context" + "fmt" + "os" + "os/exec" + "strconv" + "sync" + "syscall" + "time" + + "github.com/apenella/go-ansible/v2/pkg/execute" + goexec "github.com/apenella/go-ansible/v2/pkg/execute/exec" + "go.uber.org/zap" +) + +// Stopping ansible-playbook (utility playbooks: builds and image actions). +// +// go-ansible starts ansible-playbook with exec.CommandContext and reads its +// output until EOF before waiting for it. Ansible runs each task in a worker +// process that leads its own session, so neither a SIGKILL to +// ansible-playbook nor a signal to its process group reaches the workers: +// they, and the ssh connections they hold, went on after a cancellation. +// ansible-playbook stops its workers itself when it gets SIGTERM, so a +// cancelled context sends it SIGTERM. If the run has not ended after +// stopGrace (ansible-playbook ignores SIGTERM, or a worker it left keeps +// its output open, and go-ansible waiting), every local process of the run +// is killed: ansible-playbook and what it started, found by the runMarkerVar +// variable in their environment (as stopScript finds a run's commands on +// the hosts; Linux only, elsewhere ansible-playbook alone is killed). +// Execute returns once ansible-playbook has exited and its output is +// closed. Processes of the run still there then get SIGTERM. + +// stopGrace is how long a cancelled ansible-playbook has to stop after +// SIGTERM. +var stopGrace = 15 * time.Second + +// runMarkerVar marks the local processes of one ansible-playbook run: it is +// set, to a value unique to the run, in the environment of ansible-playbook, +// and the processes it starts inherit it. +const runMarkerVar = "GALVANIZE_ANSIBLE_RUN" + +// processExecutable starts ansible-playbook bound to ctx (set by +// cancellableExecutor before each run). +type processExecutable struct { + ctx context.Context + marker string + + mu sync.Mutex + kill *time.Timer // kills the run's processes stopGrace after the cancellation + ended bool +} + +var _ execute.Executabler = (*processExecutable)(nil) + +// withProcessExecutable makes def start ansible-playbook with a new +// processExecutable, and marks the run's processes. +func withProcessExecutable(def *execute.DefaultExecute) *processExecutable { + exe := &processExecutable{marker: generateRandomID() + generateRandomID()} + def.Exec = exe + def.AddEnvVar(runMarkerVar, exe.marker) + return exe +} + +func (p *processExecutable) Command(name string, arg ...string) goexec.Cmder { + return p.CommandContext(context.Background(), name, arg...) +} + +// CommandContext ignores the context go-ansible passes, which is never +// cancelled (see cancellableExecutor), and uses p.ctx. +func (p *processExecutable) CommandContext(_ context.Context, name string, arg ...string) goexec.Cmder { + ctx := p.ctx + if ctx == nil { + ctx = context.Background() + } + cmd := exec.CommandContext(ctx, name, arg...) + cmd.Cancel = func() error { + _ = cmd.Process.Signal(syscall.SIGTERM) + p.mu.Lock() + if !p.ended && p.marker != "" { + grace, marker := stopGrace, p.marker + p.kill = time.AfterFunc(grace, func() { + if n := signalMarked(marker, syscall.SIGKILL); n > 0 { + zap.S().Warnf("ansible-playbook did not stop %v after SIGTERM: %d process(es) of the run killed", grace, n) + } + }) + } + p.mu.Unlock() + // Not nil: Wait then reports how ansible-playbook exited (nil or an + // *exec.ExitError), never ctx.Err(). go-ansible takes any other + // error of Wait for an *exec.ExitError, and panicked when + // ansible-playbook exited 0 after the cancellation. + return os.ErrProcessDone + } + // SIGKILL to ansible-playbook where signalMarked finds nothing + cmd.WaitDelay = stopGrace + return cmd +} + +// end is called when Execute returns: the run's processes still there get +// SIGTERM, and the pending kill is dropped. +func (p *processExecutable) end() { + p.mu.Lock() + p.ended = true + if p.kill != nil { + p.kill.Stop() + } + p.mu.Unlock() + if p.marker != "" { + signalMarked(p.marker, syscall.SIGTERM) + } +} + +// signalMarked sends sig to the local processes whose environment has +// runMarkerVar=marker, and returns how many it signalled. It reads /proc: +// elsewhere than on Linux it finds none. +func signalMarked(marker string, sig syscall.Signal) int { + entries, err := os.ReadDir("/proc") + if err != nil { + return 0 + } + want := []byte(runMarkerVar + "=" + marker) + n := 0 + for _, e := range entries { + pid, err := strconv.Atoi(e.Name()) + if err != nil || pid == os.Getpid() { + continue + } + env, err := os.ReadFile("/proc/" + e.Name() + "/environ") + if err != nil { + continue + } + for _, v := range bytes.Split(env, []byte{0}) { + if bytes.Equal(v, want) { + if syscall.Kill(pid, sig) == nil { + n++ + } + break + } + } + } + return n +} + +// cancellableExecutor runs a go-ansible executor built with exe. go-ansible +// stops reading the output and returns as soon as the context it gets is +// cancelled, without waiting for the process: it gets a context that is +// never cancelled, and the process, started by exe with the real one, is +// stopped as described above. Execute returns when the process has exited. +type cancellableExecutor struct { + inner execute.Executor + exe *processExecutable +} + +func (c cancellableExecutor) Execute(ctx context.Context) error { + c.exe.ctx = ctx + err := c.run(ctx) + c.exe.end() + return err +} + +// run turns a panic of go-ansible into an error, as safeCall does for the +// operations: the runs happen in goroutines of their own, where a panic +// would stop Galvanize. +func (c cancellableExecutor) run(ctx context.Context) (err error) { + defer func() { + if r := recover(); r != nil { + zap.S().Errorf("ansible-playbook run panicked: %v", r) + err = fmt.Errorf("internal error running ansible-playbook: %v", r) + } + }() + return c.inner.Execute(context.WithoutCancel(ctx)) +} diff --git a/galvanize-instancer/internal/ansible/utility.go b/galvanize-instancer/internal/ansible/utility.go new file mode 100644 index 0000000..a2e8b20 --- /dev/null +++ b/galvanize-instancer/internal/ansible/utility.go @@ -0,0 +1,328 @@ +package ansible + +import ( + "bytes" + "context" + "embed" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/apenella/go-ansible/v2/pkg/execute" + "github.com/apenella/go-ansible/v2/pkg/execute/configuration" + jsonresults "github.com/apenella/go-ansible/v2/pkg/execute/result/json" + "github.com/apenella/go-ansible/v2/pkg/playbook" +) + +// Galvanize's own playbooks (image builds and maintenance). Unlike the +// deployment playbooks of ansible_dir, which operators adapt, they are part +// of the binary. +// +//go:embed utility_playbooks/*.yaml +var utilityPlaybooks embed.FS + +// Utility playbook names. +const ( + PlaybookBuild = "build" + PlaybookImages = "images" + // PlaybookStop is run by Run itself after a cancelled or timed out run + PlaybookStop = "stop" +) + +// stopTimeout bounds the stop playbook run after a cancelled or timed out +// run, and stopTaskTimeout its task (stopScript waits 20 s for the +// processes to exit). With stopGrace, they bound how long stopping a run +// takes (StopDuration). +const ( + stopTimeout = 40 * time.Second + stopTaskTimeout = 30 * time.Second +) + +// StopDuration is the longest a cancelled run takes to stop: ansible-playbook +// (stopGrace), then the stop playbook. A shutdown must leave that much time. +func StopDuration() time.Duration { return stopGrace + stopTimeout } + +// stopScript stops what one run of a utility playbook left on a host. +// Stopping ansible-playbook does not stop the commands it started there +// (ssh does not signal them when the connection closes): a cancelled build +// went on and tagged its images. The playbooks set GALVANIZE_RUN_ID on +// their tasks and the processes they start inherit it, so the processes +// with the run's ID in their environment are terminated (killed after 20 +// s), and the run's build directory, which its own cleanup task did not +// remove, is removed. $1 is the run ID. +const stopScript = `id=$1 +case $id in ''|*[!0-9a-f]*) echo "invalid run ID" >&2; exit 2 ;; esac +marked() { + for env in /proc/[0-9]*/environ; do + if tr '\0' '\n' < "$env" 2>/dev/null | grep -qx "GALVANIZE_RUN_ID=$id"; then + pid=${env#/proc/} + echo "${pid%/environ}" + fi + done +} +pids=$(marked) +if [ -n "$pids" ]; then + echo "stopping" $pids + kill -TERM $pids 2>/dev/null +fi +n=0 +while [ -n "$pids" ] && [ $n -lt 20 ]; do + sleep 1 + n=$((n + 1)) + pids=$(marked) +done +if [ -n "$pids" ]; then + echo "killing" $pids + kill -KILL $pids 2>/dev/null +fi +rm -rf "${TMPDIR:-/tmp}/galvanize-build-$id-"* +` + +// HostResult is the outcome of one task on one host. +type HostResult struct { + Host string + Task string + Failed bool + Unreachable bool + Skipped bool + Stdout []string + Stderr []string + Msg string +} + +// UtilityRunner runs a Galvanize utility playbook on every Ansible host. +type UtilityRunner interface { + // Run returns the per-host results of every task, and an error when the + // run failed (results are still returned when Ansible produced them). + // When ctx is cancelled or times out, Run returns once the run is + // stopped, on the hosts too. + Run(ctx context.Context, conf *config.Config, name string, extraVars map[string]interface{}, taskTimeout time.Duration) ([]HostResult, error) +} + +// AnsibleUtilityRunner is the production UtilityRunner. +type AnsibleUtilityRunner struct{} + +var _ UtilityRunner = AnsibleUtilityRunner{} + +func (AnsibleUtilityRunner) Run(ctx context.Context, conf *config.Config, name string, extraVars map[string]interface{}, taskTimeout time.Duration) ([]HostResult, error) { + runID := generateRandomID() + results, err := runUtility(ctx, conf, name, runID, extraVars, taskTimeout) + // A run that returned no error ended: nothing of it is left to stop + if err == nil || ctx.Err() == nil || name == PlaybookStop { + return results, err + } + if stopErr := stopRun(ctx, conf, runID); stopErr != nil { + return results, fmt.Errorf("%w; stopping it on the hosts failed, its commands may still run there: %v", err, stopErr) + } + return results, err +} + +// stopRun runs the stop playbook for the run runID, which was cancelled or +// timed out (ctx is its context), within stopTimeout. The error names the +// hosts where it failed. +func stopRun(ctx context.Context, conf *config.Config, runID string) error { + stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), stopTimeout) + defer cancel() + stopResults, stopErr := runUtility(stopCtx, conf, PlaybookStop, generateRandomID(), map[string]interface{}{ + "stop_script": stopScript, + "stop_run_id": runID, + }, stopTaskTimeout) + if stopErr == nil { + return nil + } + var hosts []string + for _, r := range stopResults { + if r.Failed || r.Unreachable { + hosts = append(hosts, r.Host) + } + } + if len(hosts) > 0 { + return fmt.Errorf("%w (%s)", stopErr, strings.Join(hosts, ", ")) + } + return stopErr +} + +// runUtility runs one utility playbook. runID marks the run: Ansible's ssh +// control sockets, and GALVANIZE_RUN_ID on the hosts. +func runUtility(ctx context.Context, conf *config.Config, name, runID string, extraVars map[string]interface{}, taskTimeout time.Duration) ([]HostResult, error) { + content, err := utilityPlaybooks.ReadFile("utility_playbooks/" + name + ".yaml") + if err != nil { + return nil, fmt.Errorf("unknown utility playbook %q", name) + } + dir, err := os.MkdirTemp("", "galvanize-playbook-") + if err != nil { + return nil, err + } + defer func() { _ = os.RemoveAll(dir) }() + path := filepath.Join(dir, name+".yaml") + if err := os.WriteFile(path, content, 0o600); err != nil { + return nil, err + } + + vars := map[string]interface{}{ + "ansible_python_interpreter": "/usr/bin/python3", + "deprecation_warnings": "False", + } + for k, v := range extraVars { + vars[k] = Unsafe(v) + } + vars["galvanize_run_id"] = runID + opts := &playbook.AnsiblePlaybookOptions{ + ExtraVars: vars, + Inventory: conf.Instancer.Ansible.Inventory, + Connection: "ssh", + PrivateKey: conf.Instancer.Ansible.PrivateKey, + User: conf.Instancer.Ansible.User, + } + cmd := playbook.NewAnsiblePlaybookCmd(playbook.WithPlaybooks(path), playbook.WithPlaybookOptions(opts)) + + out := bytes.NewBuffer(make([]byte, 0, 64*1024)) + // Raw JSON output (no line transformers), as the deployments read it. + // TMPDIR: what a stopped ansible-playbook leaves in the temporary + // directory (Python's multiprocessing directories) goes with dir. + exec := execute.NewDefaultExecute( + execute.WithCmd(cmd), + execute.WithWrite(out), + execute.WithEnvVars(map[string]string{"ANSIBLE_SSH_ARGS": SSHArgs(runID), "TMPDIR": dir}), + ) + exe := withProcessExecutable(exec) + exec.Quiet() + exec.WithOutput(jsonresults.NewJSONStdoutCallbackResults()) + seconds := int(taskTimeout.Seconds()) + if seconds <= 0 { + seconds = 300 + } + runner := configuration.NewAnsibleWithConfigurationSettingsExecute( + exec, + configuration.WithAnsibleStdoutCallback("json"), + configuration.WithoutAnsibleDeprecationWarnings(), + configuration.WithAnsiblePipelining(), + configuration.WithoutAnsibleHostKeyChecking(), + configuration.WithAnsibleForks(10), + configuration.WithAnsibleTimeout(120), + configuration.WithAnsibleTaskTimeout(seconds), + ) + runErr := cancellableExecutor{inner: runner, exe: exe}.Execute(ctx) + results, parseErr := ParseHostResults(out.Bytes()) + // Cancelled, even when ansible-playbook exited 0 after the cancellation + if ctx.Err() != nil { + return results, fmt.Errorf("cancelled or timed out: %w", ctx.Err()) + } + if runErr != nil { + if parseErr != nil { + return nil, fmt.Errorf("ansible-playbook failed (%s) and its output could not be read: %v", lastLine(runErr.Error()), parseErr) + } + // The per-host results say what failed + return results, fmt.Errorf("ansible-playbook failed: %s", lastLine(runErr.Error())) + } + if parseErr != nil { + return nil, parseErr + } + return results, nil +} + +// Unsafe marks every string of v as unsafe for Ansible: the values come from +// challenge repositories (image and service names, folder names...), and +// Ansible renders Jinja in extra vars, so "{{ lookup('pipe', ...) }}" in an +// image name would run a command in Galvanize. Ansible reads +// {"__ansible_unsafe": s} in JSON extra vars as the string s, never +// rendered. +func Unsafe(v interface{}) interface{} { + switch t := v.(type) { + case string: + return map[string]interface{}{"__ansible_unsafe": t} + case []string: + out := make([]interface{}, len(t)) + for i, s := range t { + out[i] = Unsafe(s) + } + return out + case []interface{}: + out := make([]interface{}, len(t)) + for i, e := range t { + out[i] = Unsafe(e) + } + return out + case map[string]interface{}: + out := make(map[string]interface{}, len(t)) + for k, e := range t { + out[k] = Unsafe(e) + } + return out + } + return v +} + +// SSHArgs are the ssh options of one ansible-playbook run. The ControlPath +// has %C (a hash of the host, port and user) so that each host gets its own +// master connection: ANSIBLE_SSH_ARGS reaches ssh unformatted, so "%%h" +// would be a literal "%h" and every host would share the first host's +// socket, running the other hosts' tasks on it. id keeps runs apart. +func SSHArgs(id string) string { + return "-o ControlMaster=auto -o ControlPersist=30s -o ControlPath=/tmp/ansible-ssh-%C-" + id + + " -o ConnectTimeout=30 -o ServerAliveInterval=10 -o ServerAliveCountMax=3" +} + +// ParseHostResults reads the per-host task results of Ansible's json +// stdout callback. +func ParseHostResults(data []byte) ([]HostResult, error) { + var root struct { + Plays []struct { + Tasks []struct { + Task struct { + Name string `json:"name"` + } `json:"task"` + Hosts map[string]struct { + Failed bool `json:"failed"` + Unreachable bool `json:"unreachable"` + Skipped bool `json:"skipped"` + StdoutLines []string `json:"stdout_lines"` + StderrLines []string `json:"stderr_lines"` + Msg json.RawMessage `json:"msg"` + } `json:"hosts"` + } `json:"tasks"` + } `json:"plays"` + } + // Warnings may come before the JSON document, which starts a line + if i := bytes.Index(data, []byte("\n{")); i >= 0 && !bytes.HasPrefix(bytes.TrimSpace(data), []byte("{")) { + data = data[i+1:] + } + if len(bytes.TrimSpace(data)) == 0 { + return nil, fmt.Errorf("no output from ansible-playbook") + } + if err := json.Unmarshal(data, &root); err != nil { + return nil, fmt.Errorf("cannot parse Ansible results: %w", err) + } + var out []HostResult + for _, play := range root.Plays { + for _, task := range play.Tasks { + for host, r := range task.Hosts { + out = append(out, HostResult{ + Host: host, Task: task.Task.Name, Failed: r.Failed, Unreachable: r.Unreachable, + Skipped: r.Skipped, Stdout: r.StdoutLines, Stderr: r.StderrLines, Msg: rawMsg(r.Msg), + }) + } + } + } + return out, nil +} + +func lastLine(s string) string { + lines := strings.Split(strings.TrimSpace(s), "\n") + return strings.TrimSpace(lines[len(lines)-1]) +} + +func rawMsg(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var s string + if json.Unmarshal(raw, &s) == nil { + return s + } + return strings.TrimSpace(string(raw)) +} diff --git a/galvanize-instancer/internal/ansible/utility_playbooks/build.yaml b/galvanize-instancer/internal/ansible/utility_playbooks/build.yaml new file mode 100644 index 0000000..4e0375e --- /dev/null +++ b/galvanize-instancer/internal/ansible/utility_playbooks/build.yaml @@ -0,0 +1,33 @@ +--- +# Internal playbook of Galvanize (embedded in the binary): builds one +# challenge's images on every host. Galvanize sends the challenge folder as +# an archive and the docker build / docker compose build command line. +# GALVANIZE_RUN_ID marks the processes of the run, and the build directory +# has it in its name: a cancelled run is stopped on the hosts by the stop +# playbook. +- hosts: all + gather_facts: false + environment: + GALVANIZE_RUN_ID: "{{ galvanize_run_id }}" + tasks: + - name: Create build directory + ansible.builtin.tempfile: + state: directory + prefix: "galvanize-build-{{ galvanize_run_id }}-" + register: galvanize_build_dir + + - block: + - name: Upload build context + ansible.builtin.unarchive: + src: "{{ build_archive }}" + dest: "{{ galvanize_build_dir.path }}" + + - name: Build + ansible.builtin.command: + argv: "{{ build_argv }}" + chdir: "{{ galvanize_build_dir.path }}/{{ build_workdir }}" + always: + - name: Remove build directory + ansible.builtin.file: + path: "{{ galvanize_build_dir.path }}" + state: absent diff --git a/galvanize-instancer/internal/ansible/utility_playbooks/images.yaml b/galvanize-instancer/internal/ansible/utility_playbooks/images.yaml new file mode 100644 index 0000000..e978db2 --- /dev/null +++ b/galvanize-instancer/internal/ansible/utility_playbooks/images.yaml @@ -0,0 +1,14 @@ +--- +# Internal playbook of Galvanize (embedded in the binary): checks or removes +# challenge images on every host. The shell script is Galvanize's; image +# names are passed as separate arguments, never inside the script. +# GALVANIZE_RUN_ID marks the processes of the run (see the stop playbook). +- hosts: all + gather_facts: false + environment: + GALVANIZE_RUN_ID: "{{ galvanize_run_id }}" + tasks: + - name: Images + ansible.builtin.command: + argv: "{{ ['sh', '-c', images_script, 'sh'] + images }}" + changed_when: false diff --git a/galvanize-instancer/internal/ansible/utility_playbooks/stop.yaml b/galvanize-instancer/internal/ansible/utility_playbooks/stop.yaml new file mode 100644 index 0000000..9ea2809 --- /dev/null +++ b/galvanize-instancer/internal/ansible/utility_playbooks/stop.yaml @@ -0,0 +1,11 @@ +--- +# Internal playbook of Galvanize (embedded in the binary): stops on every +# host what a cancelled or timed out run of another utility playbook left +# running there (see stopScript). Unlike the other playbooks, it does not +# set GALVANIZE_RUN_ID. +- hosts: all + gather_facts: false + tasks: + - name: Stop run + ansible.builtin.command: + argv: ["sh", "-c", "{{ stop_script }}", "sh", "{{ stop_run_id }}"] diff --git a/galvanize-instancer/internal/ansible/utility_test.go b/galvanize-instancer/internal/ansible/utility_test.go new file mode 100644 index 0000000..5a9e7ac --- /dev/null +++ b/galvanize-instancer/internal/ansible/utility_test.go @@ -0,0 +1,309 @@ +package ansible + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/28Pollux28/galvanize/pkg/config" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseHostResults(t *testing.T) { + out := []byte(`[WARNING]: a warning {with braces} before the JSON +{"plays":[{"tasks":[ + {"task":{"name":"Build"},"hosts":{ + "10.0.0.1":{"changed":true,"stdout_lines":["ok"],"stderr_lines":["#1 DONE"]}, + "10.0.0.2":{"failed":true,"msg":"non-zero return code","stderr_lines":["boom"]}}}, + {"task":{"name":"Remove build directory"},"hosts":{"10.0.0.3":{"unreachable":true,"msg":["a","b"]}}} +]}]}`) + res, err := ParseHostResults(out) + require.NoError(t, err) + require.Len(t, res, 3) + byHost := map[string]HostResult{} + for _, r := range res { + byHost[r.Host] = r + } + assert.Equal(t, []string{"#1 DONE"}, byHost["10.0.0.1"].Stderr) + assert.True(t, byHost["10.0.0.2"].Failed) + assert.Equal(t, "non-zero return code", byHost["10.0.0.2"].Msg) + assert.True(t, byHost["10.0.0.3"].Unreachable) + assert.Equal(t, `["a","b"]`, byHost["10.0.0.3"].Msg) + + _, err = ParseHostResults(nil) + assert.Error(t, err) +} + +func TestUtilityPlaybooksAreEmbedded(t *testing.T) { + for _, name := range []string{PlaybookBuild, PlaybookImages, PlaybookStop} { + data, err := utilityPlaybooks.ReadFile("utility_playbooks/" + name + ".yaml") + require.NoError(t, err) + assert.Contains(t, string(data), "hosts: all") + } +} + +// fakeAnsible puts an ansible-playbook on PATH that prints output and exits +// with code, and records its arguments. +func fakeAnsible(t *testing.T, output string, code int) string { + t.Helper() + dir := t.TempDir() + out := filepath.Join(dir, "output.json") + require.NoError(t, os.WriteFile(out, []byte(output), 0o644)) + args := filepath.Join(dir, "args") + script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > " + args + "\ncat " + out + "\nexit " + string(rune('0'+code)) + "\n" + require.NoError(t, os.WriteFile(filepath.Join(dir, "ansible-playbook"), []byte(script), 0o755)) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + return args +} + +const buildOutput = `{"plays":[{"tasks":[{"task":{"name":"Build"},"hosts":{"h1":{"failed":true,"msg":"non-zero return code","stderr_lines":["#5 ERROR: boom"]}}}]}]}` + +func TestRun_ReadsTheRawJSONOutput(t *testing.T) { + // Regression: line transformers prefixed every line and broke the JSON + args := fakeAnsible(t, buildOutput, 2) + conf := &config.Config{Instancer: config.InstancerConfig{Ansible: config.AnsibleConfig{Inventory: "h1,", User: "u"}}} + res, err := AnsibleUtilityRunner{}.Run(context.Background(), conf, PlaybookBuild, map[string]interface{}{"build_argv": []string{"docker", "build", "."}}, time.Minute) + require.Error(t, err) + assert.NotContains(t, err.Error(), "ANSIBLE_SSH_ARGS", "short error, not the whole command") + require.Len(t, res, 1) + assert.True(t, res[0].Failed) + assert.Equal(t, []string{"#5 ERROR: boom"}, res[0].Stderr) + + recorded, _ := os.ReadFile(args) + // Values from the repositories are never rendered as Jinja + assert.Contains(t, string(recorded), `"build_argv":[{"__ansible_unsafe":"docker"},{"__ansible_unsafe":"build"},{"__ansible_unsafe":"."}]`) + assert.Contains(t, string(recorded), `"ansible_python_interpreter":"/usr/bin/python3"`, "Galvanize's own variables stay plain") + assert.Contains(t, string(recorded), "h1,") +} + +func TestSSHArgs_OneMasterPerHost(t *testing.T) { + args := SSHArgs("abcd") + assert.Contains(t, args, "ControlPath=/tmp/ansible-ssh-%C-abcd") + assert.NotContains(t, args, "%%", "ssh reads %% as a literal %: every host would share one socket") +} + +func TestUnsafe(t *testing.T) { + in := map[string]interface{}{ + "s": "{{ lookup('pipe', 'id') }}", + "list": []string{"a"}, + "any": []interface{}{"b", 1, map[string]interface{}{"c": "d"}}, + "n": 3, + } + assert.Equal(t, map[string]interface{}{ + "s": map[string]interface{}{"__ansible_unsafe": "{{ lookup('pipe', 'id') }}"}, + "list": []interface{}{map[string]interface{}{"__ansible_unsafe": "a"}}, + "any": []interface{}{map[string]interface{}{"__ansible_unsafe": "b"}, 1, + map[string]interface{}{"c": map[string]interface{}{"__ansible_unsafe": "d"}}}, + "n": 3, + }, Unsafe(in)) +} + +func TestRun_Success(t *testing.T) { + fakeAnsible(t, strings.Replace(buildOutput, `"failed":true,`, "", 1), 0) + conf := &config.Config{Instancer: config.InstancerConfig{Ansible: config.AnsibleConfig{Inventory: "h1,"}}} + res, err := AnsibleUtilityRunner{}.Run(context.Background(), conf, PlaybookImages, nil, 0) + require.NoError(t, err) + require.Len(t, res, 1) + assert.False(t, res[0].Failed) +} + +// slowAnsible puts an ansible-playbook on PATH that runs until it is +// stopped, running onTerm on SIGTERM, and answers the stop playbook with +// stopOutput and stopCode. It records its arguments and what happened in +// dir. +func slowAnsible(t *testing.T, onTerm, stopOutput string, stopCode int) string { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "stop.json"), []byte(stopOutput), 0o644)) + script := `#!/bin/sh +d=` + dir + ` +case "$*" in +*stop.yaml*) printf '%s\n' "$@" > $d/stop-args; cat $d/stop.json; exit ` + string(rune('0'+stopCode)) + ` ;; +esac +printf '%s\n' "$@" > $d/run-args +` + onTerm + ` +echo started >> $d/events +sleep 30 >/dev/null 2>&1 & +child=$! +wait $child +` + require.NoError(t, os.WriteFile(filepath.Join(dir, "ansible-playbook"), []byte(script), 0o755)) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + return dir +} + +// cancelWhenStarted cancels the context once the fake ansible-playbook runs. +func cancelWhenStarted(t *testing.T, dir string) context.Context { + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + go func() { + for i := 0; i < 500; i++ { + if data, _ := os.ReadFile(filepath.Join(dir, "events")); strings.Contains(string(data), "started") { + break + } + time.Sleep(10 * time.Millisecond) + } + cancel() + }() + return ctx +} + +const stopOK = `{"plays":[{"tasks":[{"task":{"name":"Stop run"},"hosts":{"h1":{"changed":true}}}]}]}` + +func TestRun_CancelStopsTheRunEverywhere(t *testing.T) { + // Regression: cancelling SIGKILLed ansible-playbook only, its workers + // and the build on the hosts went on, and Run returned at once + dir := slowAnsible(t, `trap 'echo term >> $d/events; kill $child; sleep 0.3; echo exited >> $d/events; exit 1' TERM`, stopOK, 0) + conf := &config.Config{Instancer: config.InstancerConfig{Ansible: config.AnsibleConfig{Inventory: "h1,"}}} + _, err := AnsibleUtilityRunner{}.Run(cancelWhenStarted(t, dir), conf, PlaybookBuild, nil, time.Minute) + require.Error(t, err) + assert.Contains(t, err.Error(), "cancelled") + assert.NotContains(t, err.Error(), "stopping it on the hosts failed") + + events, _ := os.ReadFile(filepath.Join(dir, "events")) + assert.Equal(t, "started\nterm\nexited\n", string(events), "SIGTERM, and Run waits until ansible-playbook exits") + + // The stop playbook ran for this run + runArgs, _ := os.ReadFile(filepath.Join(dir, "run-args")) + m := regexp.MustCompile(`"galvanize_run_id":"([0-9a-f]+)"`).FindStringSubmatch(string(runArgs)) + require.NotNil(t, m, string(runArgs)) + stopArgs, err := os.ReadFile(filepath.Join(dir, "stop-args")) + require.NoError(t, err, "the stop playbook did not run") + assert.Contains(t, string(stopArgs), `"stop_run_id":{"__ansible_unsafe":"`+m[1]+`"}`) + assert.NotContains(t, string(stopArgs), `"galvanize_run_id":"`+m[1]+`"`, "the stop run has its own ID") +} + +func TestRun_StopFailureIsReported(t *testing.T) { + dir := slowAnsible(t, `trap 'kill $child; exit 1' TERM`, + `{"plays":[{"tasks":[{"task":{"name":"Stop run"},"hosts":{"h1":{"unreachable":true,"msg":"no route"}}}]}]}`, 4) + conf := &config.Config{Instancer: config.InstancerConfig{Ansible: config.AnsibleConfig{Inventory: "h1,"}}} + _, err := AnsibleUtilityRunner{}.Run(cancelWhenStarted(t, dir), conf, PlaybookImages, nil, 0) + require.Error(t, err) + assert.Contains(t, err.Error(), "cancelled") + assert.Contains(t, err.Error(), "stopping it on the hosts failed") + assert.Contains(t, err.Error(), "(h1)") +} + +func TestRun_KillsTheRunOfAnAnsiblePlaybookThatIgnoresSIGTERM(t *testing.T) { + // Regression: when ansible-playbook ignored SIGTERM, it was SIGKILLed + // after stopGrace, but its workers (each leading its own session) went + // on with its output open, and Run waited for them, the operation lock + // held. The processes of the run are killed with it. + if _, err := os.Stat("/proc/self/environ"); err != nil { + t.Skip("needs /proc") + } + if _, err := exec.LookPath("setsid"); err != nil { + t.Skip("needs setsid") + } + old := stopGrace + stopGrace = 200 * time.Millisecond + t.Cleanup(func() { stopGrace = old }) + dir := slowAnsible(t, `trap '' TERM +setsid sh -c 'echo $$ > '$d'/worker; exec sleep 30' &`, stopOK, 0) + conf := &config.Config{Instancer: config.InstancerConfig{Ansible: config.AnsibleConfig{Inventory: "h1,"}}} + start := time.Now() + _, err := AnsibleUtilityRunner{}.Run(cancelWhenStarted(t, dir), conf, PlaybookBuild, nil, time.Minute) + require.Error(t, err) + assert.Contains(t, err.Error(), "cancelled") + assert.Less(t, time.Since(start), 10*time.Second, "not after the worker's 30 s") + data, err := os.ReadFile(filepath.Join(dir, "worker")) + require.NoError(t, err) + pid, err := strconv.Atoi(strings.TrimSpace(string(data))) + require.NoError(t, err) + // Killed: gone, or a zombie until init reaps it + assert.Eventually(t, func() bool { + stat, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + return err != nil || strings.Contains(string(stat), ") Z ") + }, 5*time.Second, 50*time.Millisecond, "the worker was not killed") +} + +func TestRun_AnsiblePlaybookExiting0OnSIGTERM(t *testing.T) { + // Regression: Wait then returned the context's error, which go-ansible + // takes for an *exec.ExitError: a panic that stopped Galvanize (a build + // runs in a goroutine of its own) + dir := slowAnsible(t, `trap 'kill $child; exit 0' TERM`, stopOK, 0) + conf := &config.Config{Instancer: config.InstancerConfig{Ansible: config.AnsibleConfig{Inventory: "h1,"}}} + _, err := AnsibleUtilityRunner{}.Run(cancelWhenStarted(t, dir), conf, PlaybookBuild, nil, time.Minute) + require.Error(t, err) + assert.NotContains(t, err.Error(), "internal error", "no panic (recovered by cancellableExecutor)") + assert.Contains(t, err.Error(), "cancelled", "a cancelled utility run is reported cancelled") +} + +func TestRun_CancelledAfterAnsiblePlaybookExited0(t *testing.T) { + // ansible-playbook printed its results and exited 0, a process it left + // keeps its output open, and the context is cancelled meanwhile. + // Regression: a panic (see above); then, once ansible-playbook was done, + // "%!w()" when stopping the run on the hosts failed. + dir := t.TempDir() + script := "#!/bin/sh\ncase \"$*\" in *stop.yaml*) echo '{\"plays\":[{\"tasks\":[{\"task\":{\"name\":\"Stop run\"},\"hosts\":{\"h1\":{\"unreachable\":true}}}]}]}'; exit 4;; esac\n" + + "echo '" + stopOK + "'\n(sleep 1) &\nexit 0\n" + require.NoError(t, os.WriteFile(filepath.Join(dir, "ansible-playbook"), []byte(script), 0o755)) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { time.Sleep(300 * time.Millisecond); cancel() }() + conf := &config.Config{Instancer: config.InstancerConfig{Ansible: config.AnsibleConfig{Inventory: "h1,"}}} + _, err := AnsibleUtilityRunner{}.Run(ctx, conf, PlaybookImages, nil, 0) + require.Error(t, err) + assert.Contains(t, err.Error(), "cancelled or timed out") + assert.Contains(t, err.Error(), "stopping it on the hosts failed") + assert.NotContains(t, err.Error(), "%!") +} + +type panickingExecutor struct{} + +func (panickingExecutor) Execute(context.Context) error { panic("interface conversion") } + +func TestCancellableExecutor_RecoversPanics(t *testing.T) { + err := cancellableExecutor{inner: panickingExecutor{}, exe: &processExecutable{}}.Execute(context.Background()) + require.Error(t, err) + assert.Contains(t, err.Error(), "internal error running ansible-playbook: interface conversion") +} + +func TestStopScript(t *testing.T) { + if _, err := os.Stat("/proc/self/environ"); err != nil { + t.Skip("needs /proc") + } + tmp := t.TempDir() + start := func(id string) *exec.Cmd { + cmd := exec.Command("sleep", "30") + cmd.Env = append(os.Environ(), "GALVANIZE_RUN_ID="+id) + require.NoError(t, cmd.Start()) + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }) + return cmd + } + ours, other := start("abcd1234"), start("abcd12345") + exited := make(chan struct{}) + go func() { _ = ours.Wait(); close(exited) }() + buildDir := filepath.Join(tmp, "galvanize-build-abcd1234-x1") + otherDir := filepath.Join(tmp, "galvanize-build-ffff0000-x2") + require.NoError(t, os.MkdirAll(filepath.Join(buildDir, "ctx"), 0o755)) + require.NoError(t, os.MkdirAll(otherDir, 0o755)) + + stop := exec.Command("sh", "-c", stopScript, "sh", "abcd1234") + stop.Env = append(os.Environ(), "TMPDIR="+tmp) + out, err := stop.CombinedOutput() + require.NoError(t, err, string(out)) + select { + case <-exited: + case <-time.After(5 * time.Second): + t.Fatal("the run's process was not stopped") + } + assert.NoError(t, other.Process.Signal(syscall.Signal(0)), "another run's process is left alone") + assert.NoDirExists(t, buildDir) + assert.DirExists(t, otherDir) + + out, err = exec.Command("sh", "-c", stopScript, "sh", "x; rm -rf /").CombinedOutput() + assert.Error(t, err) + assert.Contains(t, string(out), "invalid run ID") +} diff --git a/galvanize-instancer/internal/auth/claims.go b/galvanize-instancer/internal/auth/claims.go index 8b1d906..713942f 100644 --- a/galvanize-instancer/internal/auth/claims.go +++ b/galvanize-instancer/internal/auth/claims.go @@ -7,12 +7,20 @@ import ( "github.com/labstack/echo/v4" ) +// ScopeManage is the scope an admin token needs for the repository, build, +// image and challenge-file endpoints. The CTF platform's server puts it in +// the tokens it uses itself, never in the ones it hands to browsers: the +// dashboard's admin token can then manage instances but not clone +// repositories, run builds on the hosts or read challenge files. +const ScopeManage = "manage" + // Claims matches the JWT structure type Claims struct { TeamID string `json:"team_id"` ChallengeName string `json:"challenge_name"` Category string `json:"category"` Role string `json:"role"` + Scope string `json:"scope,omitempty"` jwt.RegisteredClaims } diff --git a/galvanize-instancer/internal/build/archive.go b/galvanize-instancer/internal/build/archive.go new file mode 100644 index 0000000..38e6731 --- /dev/null +++ b/galvanize-instancer/internal/build/archive.go @@ -0,0 +1,108 @@ +package build + +import ( + "archive/tar" + "compress/gzip" + "io" + "os" + "path/filepath" + + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/internal/operation" + "github.com/28Pollux28/galvanize/internal/pathutil" +) + +// writeArchive packs the challenge folder (without .git, and without +// symlinks leading outside it) into a temporary tar.gz, plus the build +// compose file. Returns the archive path and the folder to build in, +// relative to the archive root. +func writeArchive(c *challenge.Challenge, plan Plan, log operation.Logger) (string, string, error) { + f, err := os.CreateTemp("", "galvanize-build-*.tar.gz") + if err != nil { + return "", "", err + } + gz := gzip.NewWriter(f) + tw := tar.NewWriter(gz) + // On failure the archive is incomplete anyway: errors closing or + // removing it change nothing + fail := func(err error) (string, string, error) { + _ = tw.Close() + _ = gz.Close() + _ = f.Close() + _ = os.Remove(f.Name()) + return "", "", err + } + + walkErr := filepath.Walk(c.Dir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(c.Dir, path) + if err != nil { + return err + } + if info.IsDir() && info.Name() == ".git" { + return filepath.SkipDir + } + name := filepath.ToSlash(filepath.Join("ctx", rel)) + link := "" + if info.Mode()&os.ModeSymlink != 0 { + if _, err := pathutil.Resolve(c.Dir, path); err != nil { + log.Warnf("[%s] Skipped symlink leading outside the challenge folder: %s", Label(c), rel) + return nil + } + if link, err = os.Readlink(path); err != nil { + return err + } + } + hdr, err := tar.FileInfoHeader(info, link) + if err != nil { + return err + } + hdr.Name = name + hdr.Uid, hdr.Gid, hdr.Uname, hdr.Gname = 0, 0, "", "" + if err := tw.WriteHeader(hdr); err != nil { + return err + } + if !info.Mode().IsRegular() { + return nil + } + src, err := os.Open(path) + if err != nil { + return err + } + defer func() { _ = src.Close() }() + _, err = io.Copy(tw, src) + return err + }) + if walkErr != nil { + return fail(walkErr) + } + + workdir := "ctx" + if plan.Kind == KindCompose { + rel, err := filepath.Rel(c.Dir, plan.composeDir) + if err != nil { + return fail(err) + } + workdir = filepath.ToSlash(filepath.Join("ctx", rel)) + hdr := &tar.Header{Name: workdir + "/" + buildComposeName, Mode: 0o644, Size: int64(len(plan.composeDoc)), Typeflag: tar.TypeReg} + if err := tw.WriteHeader(hdr); err != nil { + return fail(err) + } + if _, err := tw.Write(plan.composeDoc); err != nil { + return fail(err) + } + } + if err := tw.Close(); err != nil { + return fail(err) + } + if err := gz.Close(); err != nil { + return fail(err) + } + if err := f.Close(); err != nil { + _ = os.Remove(f.Name()) + return "", "", err + } + return f.Name(), workdir, nil +} diff --git a/galvanize-instancer/internal/build/build.go b/galvanize-instancer/internal/build/build.go new file mode 100644 index 0000000..3b14112 --- /dev/null +++ b/galvanize-instancer/internal/build/build.go @@ -0,0 +1,202 @@ +// Package build builds challenge images where they run: on every Ansible +// host, with that host's Docker, so that deployments find them locally (the +// playbooks deploy with pull: missing). +// +// A challenge deployed from one image (http, tcp...) is built from the +// Dockerfile of its folder, tagged deploy_parameters.image. A compose +// challenge (custom_compose) has the services with a build section built, +// each tagged with its image, or challenge.BuiltImageTag when it has none +// (the same name the index gives it for deployments). +// +// plan.go works out what to build, policy.go what a challenge may build, +// archive.go what is sent to the hosts, images.go checks and removes images. +package build + +import ( + "context" + "os" + "sort" + "strings" + "sync" + + "github.com/28Pollux28/galvanize/internal/ansible" + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/internal/operation" + "github.com/28Pollux28/galvanize/pkg/config" + "go.uber.org/zap" +) + +// Builder runs builds and image maintenance on the Ansible hosts. +type Builder struct { + Runner ansible.UtilityRunner +} + +// failedLines is how much of a failed build's output is logged. +const failedLines = 60 + +// Result is what a Build did with each challenge, every list sorted by +// definition file. +type Result struct { + Built []*challenge.Challenge + Failed []*challenge.Challenge // refused builds included + Skipped []*challenge.Challenge // nothing to build +} + +// Build builds the challenges, up to build.concurrency at a time. cat is the +// whole catalog, to check which images each challenge may build. +func (b *Builder) Build(ctx context.Context, conf *config.Config, challs []*challenge.Challenge, cat *Catalog, noCache bool, log operation.Logger) Result { + var mu sync.Mutex + res := Result{Built: []*challenge.Challenge{}, Failed: []*challenge.Challenge{}, Skipped: []*challenge.Challenge{}} + sem := make(chan struct{}, conf.Instancer.Build.ConcurrencyOrDefault()) + var wg sync.WaitGroup + protected := ProtectedImages(conf) + for _, c := range challs { + plan := cat.PlanIn(c, protected) + if plan.Refused { + log.Errorf("[%s] Not built, %s", Label(c), plan.Reason) + res.Failed = append(res.Failed, c) + continue + } + if plan.Kind == KindNone { + log.Debugf("[%s] Nothing to build: %s", Label(c), plan.Reason) + res.Skipped = append(res.Skipped, c) + continue + } + wg.Add(1) + go func(c *challenge.Challenge, plan Plan) { + defer wg.Done() + select { + case sem <- struct{}{}: + case <-ctx.Done(): + mu.Lock() + res.Failed = append(res.Failed, c) + mu.Unlock() + return + } + defer func() { <-sem }() + ok := b.safeBuildOne(ctx, conf, c, plan, noCache, log) + mu.Lock() + if ok { + res.Built = append(res.Built, c) + } else { + res.Failed = append(res.Failed, c) + } + mu.Unlock() + }(c, plan) + } + wg.Wait() + for _, list := range [][]*challenge.Challenge{res.Built, res.Failed, res.Skipped} { + sort.Slice(list, func(i, j int) bool { return list[i].File < list[j].File }) + } + return res +} + +// safeBuildOne turns a panic of buildOne into a failed build: it runs in a +// goroutine of its own, out of reach of the operation's safeCall. +func (b *Builder) safeBuildOne(ctx context.Context, conf *config.Config, c *challenge.Challenge, plan Plan, noCache bool, log operation.Logger) (ok bool) { + defer func() { + if r := recover(); r != nil { + zap.S().Errorf("Build of %s panicked: %v", Label(c), r) + log.Errorf("[%s] Build failed: internal error: %v", Label(c), r) + ok = false + } + }() + return b.buildOne(ctx, conf, c, plan, noCache, log) +} + +func (b *Builder) buildOne(ctx context.Context, conf *config.Config, c *challenge.Challenge, plan Plan, noCache bool, log operation.Logger) bool { + key := Label(c) + archive, workdir, err := writeArchive(c, plan, log) + if err != nil { + log.Errorf("[%s] Cannot prepare the build: %v", key, err) + return false + } + defer func() { _ = os.Remove(archive) }() + + argv := BuildArgv(c, plan, noCache) + log.Infof("[%s] Building %s", key, strings.Join(plan.Images, ", ")) + ctx, cancel := context.WithTimeout(ctx, conf.Instancer.Build.TimeoutOrDefault()) + defer cancel() + results, err := b.Runner.Run(ctx, conf, ansible.PlaybookBuild, map[string]interface{}{ + "build_archive": archive, + "build_workdir": workdir, + "build_argv": argv, + }, conf.Instancer.Build.TimeoutOrDefault()) + + hosts, seen := map[string]bool{}, map[string]bool{} + ok, hostFailed := err == nil, false + for _, r := range results { + seen[r.Host] = true + if r.Failed || r.Unreachable { + ok, hostFailed = false, true + log.Errorf("[%s] %s failed on %s: %s", key, r.Task, r.Host, firstNonEmpty(r.Msg, "see the output below")) + for _, line := range tail(append(append([]string{}, r.Stdout...), r.Stderr...), failedLines) { + log.Infof("[%s] %s", key, line) + } + } else if r.Task == "Build" && !r.Skipped { + hosts[r.Host] = true + } + } + // Without a failed host to explain it (a cancelled or timed out build + // has no results), the error is the only explanation + if err != nil && !hostFailed { + log.Errorf("[%s] Build failed: %v", key, err) + } + if ok { + // Every host must have run the build: a host without its result + // would deploy an old image, or none + for h := range seen { + if !hosts[h] { + log.Errorf("[%s] The build did not run on %s", key, h) + ok = false + } + } + if len(hosts) == 0 { + log.Errorf("[%s] The build ran on no host", key) + ok = false + } + } + if !ok { + return false + } + names := make([]string, 0, len(hosts)) + for h := range hosts { + names = append(names, h) + } + sort.Strings(names) + log.Successf("[%s] Built %s on %s", key, strings.Join(plan.Images, ", "), strings.Join(names, ", ")) + return true +} + +// BuildArgv is the build command run in the challenge folder on each host. +func BuildArgv(c *challenge.Challenge, plan Plan, noCache bool) []string { + if plan.Kind == KindImage { + argv := []string{"docker", "build", "--progress=plain"} + if noCache { + argv = append(argv, "--no-cache") + } + return append(argv, "-t", plan.Images[0], "-f", plan.Dockerfile, ".") + } + project := "galvanize-build-" + challenge.BuildSlug(c.Category, c.Name) + argv := []string{"docker", "compose", "--progress", "plain", "-f", buildComposeName, "-p", project, "build"} + if noCache { + argv = append(argv, "--no-cache") + } + return append(argv, plan.Services...) +} + +func tail(lines []string, n int) []string { + if len(lines) > n { + return lines[len(lines)-n:] + } + return lines +} + +func firstNonEmpty(values ...string) string { + for _, v := range values { + if strings.TrimSpace(v) != "" { + return v + } + } + return "" +} diff --git a/galvanize-instancer/internal/build/build_test.go b/galvanize-instancer/internal/build/build_test.go new file mode 100644 index 0000000..82e8459 --- /dev/null +++ b/galvanize-instancer/internal/build/build_test.go @@ -0,0 +1,386 @@ +package build + +import ( + "archive/tar" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/28Pollux28/galvanize/internal/ansible" + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/pkg/config" + yaml "github.com/oasdiff/yaml3" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func init() { zap.ReplaceGlobals(zap.NewNop()) } + +type memLog struct { + mu sync.Mutex + lines []string +} + +func (l *memLog) add(level, f string, a ...interface{}) { + l.mu.Lock() + defer l.mu.Unlock() + l.lines = append(l.lines, level+" "+fmt.Sprintf(f, a...)) +} +func (l *memLog) Debugf(f string, a ...interface{}) { l.add("debug", f, a...) } +func (l *memLog) Infof(f string, a ...interface{}) { l.add("info", f, a...) } +func (l *memLog) Successf(f string, a ...interface{}) { l.add("success", f, a...) } +func (l *memLog) Warnf(f string, a ...interface{}) { l.add("warning", f, a...) } +func (l *memLog) Errorf(f string, a ...interface{}) { l.add("error", f, a...) } +func (l *memLog) text() string { + l.mu.Lock() + defer l.mu.Unlock() + return strings.Join(l.lines, "\n") +} + +// load writes files under a challenge folder and indexes it like Galvanize. +func load(t *testing.T, files map[string]string) *challenge.Challenge { + t.Helper() + base := t.TempDir() + dir := filepath.Join(base, "repo", "web", "chall") + for name, content := range files { + p := filepath.Join(dir, name) + require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o755)) + require.NoError(t, os.WriteFile(p, []byte(content), 0o644)) + } + idx, err := challenge.NewChallengeIndex(base) + require.NoError(t, err) + require.Empty(t, idx.Skipped()) + cat := idx.Catalog() + require.Len(t, cat, 1) + return cat[0] +} + +const httpChall = "name: Web App\ncategory: Web\ntype: zync\nplaybook_name: http\ndeploy_parameters:\n image: webapp\n" + +func TestPlan_ImageWithDockerfile(t *testing.T) { + c := load(t, map[string]string{"challenge.yml": httpChall, "Dockerfile": "FROM busybox\n"}) + p := PlanFor(c) + assert.Equal(t, KindImage, p.Kind) + assert.Equal(t, []string{"webapp"}, p.Images) + assert.Equal(t, []string{"docker", "build", "--progress=plain", "-t", "webapp", "-f", "Dockerfile", "."}, BuildArgv(c, p, false)) + assert.Contains(t, BuildArgv(c, p, true), "--no-cache") +} + +func TestPlan_PulledImageHasNothingToBuild(t *testing.T) { + // e.g. an image published to a registry, without Dockerfile + c := load(t, map[string]string{"challenge.yml": httpChall}) + p := PlanFor(c) + assert.Equal(t, KindNone, p.Kind) + assert.Contains(t, p.Reason, "pulled") +} + +func TestPlan_HTTPChallengeIgnoresASiblingComposeFile(t *testing.T) { + // PolyPwnCTF "Nexus Labs 1": http playbook, compose file next to it + c := load(t, map[string]string{"challenge.yml": httpChall, "Dockerfile": "FROM busybox\n", + "docker-compose.yaml": "services:\n app:\n build: .\n"}) + assert.Equal(t, KindImage, PlanFor(c).Kind) +} + +func TestPlan_ComposeFileServicesWithBuild(t *testing.T) { + c := load(t, map[string]string{ + "challenge.yml": "name: Lab\ncategory: Web\ntype: zync\n", + "compose.yml": "services:\n web:\n build: ./web\n api:\n build:\n context: ./api\n image: lab-api:1.2\n" + + " db:\n image: mariadb:11\n", + }) + p := PlanFor(c) + require.Equal(t, KindCompose, p.Kind) + assert.Equal(t, []string{"api", "web"}, p.Services) + assert.Equal(t, []string{"lab-api:1.2", challenge.BuiltImageTag("Web", "Lab", "web")}, p.Images) + + var doc map[string]map[string]map[string]interface{} + require.NoError(t, yaml.Unmarshal(p.composeDoc, &doc)) + assert.NotContains(t, doc["services"], "db", "only built services") + assert.Equal(t, challenge.BuiltImageTag("Web", "Lab", "web"), doc["services"]["web"]["image"]) + + argv := BuildArgv(c, p, false) + assert.Equal(t, []string{"docker", "compose", "--progress", "plain", "-f", buildComposeName, "-p", "galvanize-build-" + challenge.BuildSlug("Web", "Lab"), "build", "api", "web"}, argv) + + // The deployment uses the same image name for the untagged service + def := c.DeployParameters["compose_definition"].(string) + assert.Contains(t, def, challenge.BuiltImageTag("Web", "Lab", "web")) + assert.Contains(t, def, "lab-api:1.2") +} + +func TestPlan_InlineDefinitionBuildsFromTheComposeFile(t *testing.T) { + // PolyPwnCTF "Vault13": inline compose_definition with prebuilt images, + // docker-compose.yml with the build sections next to it + c := load(t, map[string]string{ + "challenge.yml": "name: Vault\ncategory: Web\ntype: zync\nplaybook_name: custom_compose\ndeploy_parameters:\n" + + " compose_definition: |\n services:\n haproxy:\n image: vault-haproxy:latest\n", + "docker-compose.yml": "services:\n haproxy:\n build: ./haproxy\n image: vault-haproxy:latest\n", + }) + p := PlanFor(c) + require.Equal(t, KindCompose, p.Kind) + assert.Equal(t, []string{"vault-haproxy:latest"}, p.Images) +} + +func TestPlan_InlineMappingWithoutBuilds(t *testing.T) { + // PolyPwnCTF "CatLab 1": every image comes from a registry + c := load(t, map[string]string{ + "challenge.yml": "name: Cat\ncategory: Web\ntype: zync\nplaybook_name: custom_compose\ndeploy_parameters:\n" + + " compose_definition:\n services:\n web:\n image: ghcr.io/org/cat:latest\n", + }) + p := PlanFor(c) + assert.Equal(t, KindNone, p.Kind) + assert.Equal(t, []string{"ghcr.io/org/cat:latest"}, p.Images) +} + +func TestPlan_SameNamesInTwoCategoriesDoNotCollide(t *testing.T) { + assert.NotEqual(t, challenge.BuiltImageTag("Web", "login", "app"), challenge.BuiltImageTag("Pwn", "login", "app")) +} + +func readArchive(t *testing.T, path string) map[string]string { + t.Helper() + f, err := os.Open(path) + require.NoError(t, err) + defer func() { _ = f.Close() }() + gz, err := gzip.NewReader(f) + require.NoError(t, err) + tr := tar.NewReader(gz) + out := map[string]string{} + for { + hdr, err := tr.Next() + if errors.Is(err, io.EOF) { + break + } + require.NoError(t, err) + data, _ := io.ReadAll(tr) + out[hdr.Name] = string(data) + if hdr.Typeflag == tar.TypeSymlink { + out[hdr.Name] = "-> " + hdr.Linkname + } + } + return out +} + +func TestArchive_ContentAndRefusals(t *testing.T) { + c := load(t, map[string]string{ + "challenge.yml": "name: Lab\ncategory: Web\ntype: zync\n", + "compose.yml": "services:\n web:\n build: .\n", + "Dockerfile": "FROM busybox\n", + ".git/config": "[core]\n", + "src/app.py": "print(1)\n", + }) + outside := filepath.Join(t.TempDir(), "secret") + require.NoError(t, os.WriteFile(outside, []byte("secret"), 0o644)) + require.NoError(t, os.Symlink(outside, filepath.Join(c.Dir, "escape"))) + require.NoError(t, os.Symlink("src/app.py", filepath.Join(c.Dir, "inside"))) + + log := &memLog{} + plan := PlanFor(c) + path, workdir, err := writeArchive(c, plan, log) + require.NoError(t, err) + defer func() { _ = os.Remove(path) }() + files := readArchive(t, path) + + assert.Equal(t, "ctx", workdir) + assert.Contains(t, files, "ctx/Dockerfile") + assert.Equal(t, "print(1)\n", files["ctx/src/app.py"]) + assert.Contains(t, files, "ctx/"+buildComposeName) + assert.Equal(t, "-> src/app.py", files["ctx/inside"]) + assert.NotContains(t, files, "ctx/escape", "symlink leading outside skipped") + for name := range files { + assert.NotContains(t, name, ".git/", "no .git") + } + assert.Contains(t, log.text(), "Skipped symlink") +} + +// fakeRunner records the runs and answers with canned results. +type fakeRunner struct { + mu sync.Mutex + calls []map[string]interface{} + active int32 + maxSeen int32 + delay time.Duration + respond func(vars map[string]interface{}) ([]ansible.HostResult, error) + archives []map[string]string + t *testing.T +} + +func (f *fakeRunner) Run(ctx context.Context, conf *config.Config, name string, vars map[string]interface{}, _ time.Duration) ([]ansible.HostResult, error) { + n := atomic.AddInt32(&f.active, 1) + for { + m := atomic.LoadInt32(&f.maxSeen) + if n <= m || atomic.CompareAndSwapInt32(&f.maxSeen, m, n) { + break + } + } + defer atomic.AddInt32(&f.active, -1) + time.Sleep(f.delay) + f.mu.Lock() + call := map[string]interface{}{"playbook": name} + for k, v := range vars { + call[k] = v + } + f.calls = append(f.calls, call) + if a, ok := vars["build_archive"].(string); ok && f.t != nil { + f.archives = append(f.archives, readArchive(f.t, a)) + } + f.mu.Unlock() + return f.respond(vars) +} + +func ok(hosts ...string) func(map[string]interface{}) ([]ansible.HostResult, error) { + return func(map[string]interface{}) ([]ansible.HostResult, error) { + var out []ansible.HostResult + for _, h := range hosts { + out = append(out, ansible.HostResult{Host: h, Task: "Build"}) + } + return out, nil + } +} + +func confWith(concurrency int) *config.Config { + return &config.Config{Instancer: config.InstancerConfig{Build: config.BuildConfig{Concurrency: concurrency}}} +} + +func TestBuild_SuccessFailureAndSkip(t *testing.T) { + good := load(t, map[string]string{"challenge.yml": httpChall, "Dockerfile": "FROM busybox\n"}) + bad := load(t, map[string]string{"challenge.yml": strings.Replace(httpChall, "Web App", "Broken", 1), "Dockerfile": "FROM busybox\n"}) + pulled := load(t, map[string]string{"challenge.yml": strings.Replace(httpChall, "Web App", "Pulled", 1)}) + + runner := &fakeRunner{t: t} + calls := int32(0) + runner.respond = func(vars map[string]interface{}) ([]ansible.HostResult, error) { + if atomic.AddInt32(&calls, 1) == 1 { + return []ansible.HostResult{{Host: "10.0.0.1", Task: "Build"}, {Host: "10.0.0.2", Task: "Build"}}, nil + } + return []ansible.HostResult{{Host: "10.0.0.1", Task: "Build", Failed: true, Msg: "non-zero return code", + Stderr: []string{"#5 ERROR: process did not complete successfully"}}}, errors.New("exit 2") + } + log := &memLog{} + b := &Builder{Runner: runner} + res := b.Build(context.Background(), confWith(1), []*challenge.Challenge{good, bad, pulled}, nil, false, log) + + assert.Len(t, res.Built, 1) + assert.Len(t, res.Failed, 1) + assert.Equal(t, []*challenge.Challenge{pulled}, res.Skipped) + assert.Contains(t, log.text(), "on 10.0.0.1, 10.0.0.2") + assert.Contains(t, log.text(), "#5 ERROR", "the failed build's output is logged") + require.Len(t, runner.archives, 2) + for _, a := range runner.archives { + assert.Contains(t, a, "ctx/Dockerfile") + } +} + +func TestBuild_ErrorWithoutHostResultIsLogged(t *testing.T) { + // Regression: a cancelled build (no results) only logged "Cancelled", + // not why, nor that stopping it on the hosts failed + c := load(t, map[string]string{"challenge.yml": httpChall, "Dockerfile": "FROM busybox\n"}) + runner := &fakeRunner{respond: func(map[string]interface{}) ([]ansible.HostResult, error) { + return nil, errors.New("cancelled or timed out: context canceled; stopping it on the hosts failed") + }} + log := &memLog{} + res := (&Builder{Runner: runner}).Build(context.Background(), confWith(1), []*challenge.Challenge{c}, nil, false, log) + assert.Len(t, res.Failed, 1) + assert.Contains(t, log.text(), "Build failed: cancelled or timed out: context canceled; stopping it on the hosts failed") +} + +func TestBuild_PanicFailsTheBuild(t *testing.T) { + // Regression: a panic in a build goroutine (out of reach of the + // operation's recover) stopped Galvanize + c := load(t, map[string]string{"challenge.yml": httpChall, "Dockerfile": "FROM busybox\n"}) + runner := &fakeRunner{respond: func(map[string]interface{}) ([]ansible.HostResult, error) { panic("boom") }} + log := &memLog{} + res := (&Builder{Runner: runner}).Build(context.Background(), confWith(1), []*challenge.Challenge{c}, nil, false, log) + assert.Len(t, res.Failed, 1) + assert.Contains(t, log.text(), "Build failed: internal error: boom") +} + +func TestBuild_RespectsConcurrency(t *testing.T) { + var challs []*challenge.Challenge + for i := 0; i < 5; i++ { + challs = append(challs, load(t, map[string]string{"challenge.yml": strings.Replace(httpChall, "Web App", fmt.Sprintf("App %d", i), 1), "Dockerfile": "FROM x\n"})) + } + runner := &fakeRunner{delay: 30 * time.Millisecond, respond: ok("h")} + res := (&Builder{Runner: runner}).Build(context.Background(), confWith(2), challs, nil, false, &memLog{}) + assert.Len(t, res.Built, 5) + assert.LessOrEqual(t, atomic.LoadInt32(&runner.maxSeen), int32(2)) + assert.Equal(t, int32(2), atomic.LoadInt32(&runner.maxSeen)) +} + +func TestImages_StatusAndRemove(t *testing.T) { + built := load(t, map[string]string{"challenge.yml": httpChall, "Dockerfile": "FROM x\n"}) + pulled := load(t, map[string]string{"challenge.yml": strings.Replace(strings.Replace(httpChall, "Web App", "Pulled", 1), "webapp", "ghcr.io/org/p:1", 1)}) + + runner := &fakeRunner{respond: func(vars map[string]interface{}) ([]ansible.HostResult, error) { + images := vars["images"].([]string) + var lines []string + for _, i := range images { + if i == "webapp" { + lines = append(lines, "present "+i) + } else { + lines = append(lines, "absent "+i) + } + } + return []ansible.HostResult{{Host: "h1", Task: "Images", Stdout: lines}}, nil + }} + b := &Builder{Runner: runner} + res, err := b.Images(context.Background(), confWith(1), []*challenge.Challenge{built, pulled}, nil, ImagesStatus, &memLog{}) + require.NoError(t, err) + assert.Equal(t, map[string]string{"h1": "present"}, res.States["webapp"]) + assert.Equal(t, map[string]string{"h1": "absent"}, res.States["ghcr.io/org/p:1"], "status covers pulled images") + assert.Equal(t, []string{"webapp"}, res.Challenges[built]) + + runner.calls = nil + _, err = b.Images(context.Background(), confWith(1), []*challenge.Challenge{built, pulled}, nil, ImagesRemove, &memLog{}) + require.NoError(t, err) + got := runner.calls[0]["images"].([]string) + sort.Strings(got) + assert.Equal(t, []string{"webapp"}, got, "pulled images are never removed") + assert.Contains(t, runner.calls[0]["images_script"], "docker image rm") + + _, err = b.Images(context.Background(), confWith(1), nil, nil, "explode", &memLog{}) + assert.Error(t, err) +} + +func TestImages_HostsTheScriptDidNotRunOn(t *testing.T) { + built := load(t, map[string]string{"challenge.yml": httpChall, "Dockerfile": "FROM x\n"}) + runner := &fakeRunner{respond: func(map[string]interface{}) ([]ansible.HostResult, error) { + return []ansible.HostResult{ + {Host: "h1", Task: "Images", Stdout: []string{"present webapp"}}, + {Host: "h2", Task: "Images", Unreachable: true, Msg: "ssh: connect to host h2: timed out"}, + {Host: "h3", Task: "Images", Failed: true, Msg: "docker: not found"}, + }, errors.New("exit 4") + }} + log := &memLog{} + res, err := (&Builder{Runner: runner}).Images(context.Background(), confWith(1), []*challenge.Challenge{built}, nil, ImagesStatus, log) + require.NoError(t, err, "results came back: the hosts that answered are reported") + assert.Equal(t, map[string]string{"h1": "present", "h2": StateUnreachable, "h3": StateError}, res.States["webapp"]) + assert.Contains(t, log.text(), "timed out") +} + +func TestPlan_ComposeFileIsTheOneTheIndexFound(t *testing.T) { + // The build reads the Compose file the index checked, and never looks + // for another one + inline := "name: Vault\ncategory: Web\ntype: zync\nplaybook_name: custom_compose\ndeploy_parameters:\n" + + " compose_file: build/compose.yml\n compose_definition: |\n services:\n app:\n image: vault-app\n" + c := load(t, map[string]string{ + "challenge.yml": inline, + "build/compose.yml": "services:\n app:\n build: ../src\n image: vault-app\n", + "src/Dockerfile": "FROM busybox\n", + }) + p := PlanFor(c) + require.Equal(t, KindCompose, p.Kind, p.Reason) + assert.Equal(t, filepath.Join(c.Dir, "build"), p.composeDir) + + pulled := load(t, map[string]string{"challenge.yml": strings.Replace(inline, " compose_file: build/compose.yml\n", "", 1)}) + require.NoError(t, os.WriteFile(filepath.Join(pulled.Dir, "compose.yml"), []byte("services:\n app:\n build: .\n"), 0o644)) + assert.Equal(t, KindNone, PlanFor(pulled).Kind, "a file added after indexing is not read") +} diff --git a/galvanize-instancer/internal/build/images.go b/galvanize-instancer/internal/build/images.go new file mode 100644 index 0000000..241a455 --- /dev/null +++ b/galvanize-instancer/internal/build/images.go @@ -0,0 +1,125 @@ +package build + +import ( + "context" + "fmt" + "strings" + + "github.com/28Pollux28/galvanize/internal/ansible" + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/internal/operation" + "github.com/28Pollux28/galvanize/pkg/config" +) + +// Image actions. +const ( + ImagesStatus = "status" + ImagesRemove = "remove" +) + +const statusScript = `for i in "$@"; do if docker image inspect "$i" >/dev/null 2>&1; then echo "present $i"; else echo "absent $i"; fi; done` +const removeScript = `for i in "$@"; do if ! docker image inspect "$i" >/dev/null 2>&1; then echo "absent $i"; elif docker image rm "$i" >/dev/null 2>&1; then echo "removed $i"; else echo "failed $i"; fi; done` + +// States of an image on a host the script could not run on: the host did +// not answer, or the task failed there (e.g. no Docker). +const ( + StateUnreachable = "unreachable" + StateError = "error" +) + +// ImagesResult is the state of the images of an Images run. +type ImagesResult struct { + // States maps each image to its state on each host: present or absent + // (status), removed, absent or failed (remove: the image is still + // there), or StateUnreachable / StateError for every image on a host + // the script did not run on. + States map[string]map[string]string + // Challenges maps each challenge to the images checked or removed. + Challenges map[*challenge.Challenge][]string +} + +// Images checks (status) or removes (remove) the challenges' images on +// every host. Only images the challenge may build are removed (see +// Catalog.PlanIn): never a pulled image, one another challenge uses, or a +// platform image. +func (b *Builder) Images(ctx context.Context, conf *config.Config, challs []*challenge.Challenge, cat *Catalog, action string, log operation.Logger) (*ImagesResult, error) { + script := statusScript + if action == ImagesRemove { + script = removeScript + } else if action != ImagesStatus { + return nil, fmt.Errorf("unknown image action %q", action) + } + out := &ImagesResult{States: map[string]map[string]string{}, Challenges: map[*challenge.Challenge][]string{}} + var images []string + seen := map[string]bool{} + protected := ProtectedImages(conf) + for _, c := range challs { + plan := cat.Plan(c) + if action == ImagesRemove { + plan = cat.PlanIn(c, protected) + if plan.Refused { + log.Warnf("[%s] Images not removed, %s", Label(c), plan.Reason) + continue + } + if plan.Kind == KindNone { + // Pulled images are not Galvanize's to remove + continue + } + } + for _, img := range plan.Images { + out.Challenges[c] = append(out.Challenges[c], img) + if !seen[img] { + seen[img] = true + images = append(images, img) + } + } + } + if len(images) == 0 { + log.Infof("No image to %s", map[string]string{ImagesStatus: "check", ImagesRemove: "remove"}[action]) + return out, nil + } + results, err := b.Runner.Run(ctx, conf, ansible.PlaybookImages, map[string]interface{}{ + "images_script": script, + "images": images, + }, 0) + set := func(image, host, state string) { + if out.States[image] == nil { + out.States[image] = map[string]string{} + } + out.States[image][host] = state + } + for _, r := range results { + if r.Failed || r.Unreachable { + state := StateError + if r.Unreachable { + state = StateUnreachable + } + log.Errorf("%s failed on %s (%s): %s", r.Task, r.Host, state, r.Msg) + for _, img := range images { + set(img, r.Host, state) + } + continue + } + for _, line := range r.Stdout { + state, image, found := strings.Cut(strings.TrimSpace(line), " ") + if !found { + continue + } + set(image, r.Host, state) + switch state { + case "removed": + log.Successf("Removed %s on %s", image, r.Host) + case "failed": + log.Warnf("Could not remove %s on %s (used by a container?)", image, r.Host) + case "absent": + log.Debugf("%s is not on %s", image, r.Host) + case "present": + log.Debugf("%s is on %s", image, r.Host) + } + } + } + if err != nil && len(results) == 0 { + return nil, err + } + return out, nil +} diff --git a/galvanize-instancer/internal/build/plan.go b/galvanize-instancer/internal/build/plan.go new file mode 100644 index 0000000..a84c4a7 --- /dev/null +++ b/galvanize-instancer/internal/build/plan.go @@ -0,0 +1,220 @@ +package build + +import ( + "fmt" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/28Pollux28/galvanize/internal/challenge" + yaml "github.com/oasdiff/yaml3" +) + +// Kinds of build plan. +const ( + KindImage = "image" // docker build of one Dockerfile + KindCompose = "compose" // docker compose build of the services with a build section + KindNone = "none" // nothing to build: images are pulled +) + +// buildComposeName is the Compose file Galvanize writes next to the +// challenge's own one in the build archive: only the services to build, with +// their build section and image name. +const buildComposeName = ".galvanize-build.compose.yaml" + +// Plan says what building a challenge means. +type Plan struct { + Kind string + Reason string // why there is nothing to build (KindNone) + Images []string // images the build produces + // Refused: there is something to build, but the challenge may not build + // it (see policy.go); Reason says why. Kind is KindNone. + Refused bool + // KindImage + Dockerfile string + // KindCompose + Services []string + composeDir string // folder of the compose file, inside the challenge folder + composeDoc []byte // the generated build compose file +} + +// Label names a challenge in logs. +func Label(c *challenge.Challenge) string { return c.Category + "/" + c.Name } + +// PlanFor works out how to build c. +func PlanFor(c *challenge.Challenge) Plan { + if c.PlaybookName == "custom_compose" { + return planCompose(c) + } + image, _ := c.DeployParameters["image"].(string) + image = strings.TrimSpace(image) + if image == "" { + return Plan{Kind: KindNone, Reason: "no deploy_parameters.image"} + } + if !ValidImageRef(image) { + return refused("deploy_parameters.image %q is not a valid image name", image) + } + dockerfile := findDockerfile(c.Dir) + if dockerfile == "" { + return Plan{Kind: KindNone, Reason: "no Dockerfile in the challenge folder: the image is pulled", Images: []string{image}} + } + if !fileRe.MatchString(dockerfile) { + return refused("Dockerfile name %q: use letters, digits, '.', '_' and '-' only", dockerfile) + } + return Plan{Kind: KindImage, Images: []string{image}, Dockerfile: dockerfile} +} + +func refused(format string, args ...interface{}) Plan { + return Plan{Kind: KindNone, Refused: true, Reason: "refused: " + fmt.Sprintf(format, args...)} +} + +// isDockerfile reports whether a file name is a Dockerfile (Dockerfile, +// dockerfile, Dockerfile.prod...). +func isDockerfile(name string) bool { + return strings.HasPrefix(strings.ToLower(name), "dockerfile") +} + +func findDockerfile(dir string) string { + entries, err := os.ReadDir(dir) + if err != nil { + return "" + } + var names []string + for _, e := range entries { + if !e.IsDir() && isDockerfile(e.Name()) { + names = append(names, e.Name()) + } + } + sort.Strings(names) + if len(names) == 0 { + return "" + } + // Prefer the plain name when several Dockerfiles exist + for _, n := range names { + if n == "Dockerfile" || n == "dockerfile" { + return n + } + } + return names[0] +} + +// composeSource returns the compose document to build from, and the folder +// its relative build contexts are relative to. The challenge's Compose file +// (found and checked by the index) wins over an inline definition: inline +// definitions usually reference prebuilt images, while the file next to them +// has the build sections. +func composeSource(c *challenge.Challenge) ([]byte, string, error) { + if c.ComposeFile != "" { + data, err := os.ReadFile(c.ComposeFile) + if err != nil { + return nil, "", err + } + return data, filepath.Dir(c.ComposeFile), nil + } + switch def := c.DeployParameters["compose_definition"].(type) { + case string: + return []byte(def), c.Dir, nil + case map[string]interface{}: + data, err := yaml.Marshal(def) + return data, c.Dir, err + } + return nil, "", fmt.Errorf("no compose definition") +} + +func planCompose(c *challenge.Challenge) Plan { + data, dir, err := composeSource(c) + if err != nil { + return Plan{Kind: KindNone, Reason: err.Error()} + } + var doc map[string]interface{} + if err := yaml.Unmarshal(data, &doc); err != nil { + return Plan{Kind: KindNone, Reason: fmt.Sprintf("invalid compose definition: %v", err)} + } + services, _ := doc["services"].(map[string]interface{}) + buildServices := map[string]interface{}{} + plan := Plan{Kind: KindCompose, composeDir: dir} + names := make([]string, 0, len(services)) + for name := range services { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + svc, ok := services[name].(map[string]interface{}) + if !ok { + continue + } + raw, hasBuild := svc["build"] + if !hasBuild { + continue + } + if !serviceRe.MatchString(name) { + return refused("service name %q: use letters, digits, '.', '_' and '-' only", name) + } + b, err := sanitizeBuild(raw, c.Dir, dir) + if err != nil { + return refused("service %s: %v", name, err) + } + image, _ := svc["image"].(string) + image = strings.TrimSpace(image) + if image == "" { + image = challenge.BuiltImageTag(c.Category, c.Name, name) + } + if !ValidImageRef(image) { + return refused("service %s: %q is not a valid image name", name, image) + } + if deployed, ok := deployedImage(c, name); ok && NormalizeImage(deployed) != NormalizeImage(image) { + return refused("service %s: %s builds %s but the deployment (deploy_parameters.compose_definition) runs %s", + name, filepath.Base(c.ComposeFile), image, deployed) + } + buildServices[name] = map[string]interface{}{"build": b, "image": image} + plan.Services = append(plan.Services, name) + plan.Images = append(plan.Images, image) + } + if len(plan.Services) == 0 { + return Plan{Kind: KindNone, Reason: "no compose service has a build section: images are pulled", Images: pulledImages(services)} + } + out, err := yaml.Marshal(map[string]interface{}{"services": buildServices}) + if err != nil { + return Plan{Kind: KindNone, Reason: err.Error()} + } + plan.composeDoc = out + return plan +} + +// deployedImage returns the image service runs in the deployment when the +// build reads another compose document than the deployment does (the +// Compose file next to an inline compose_definition). +func deployedImage(c *challenge.Challenge, service string) (string, bool) { + if c.ComposeFile == "" || !c.ComposeInline { + return "", false + } + def, ok := c.DeployParameters["compose_definition"].(string) + if !ok { + return "", false + } + var doc map[string]interface{} + if yaml.Unmarshal([]byte(def), &doc) != nil { + return "", false + } + services, _ := doc["services"].(map[string]interface{}) + svc, ok := services[service].(map[string]interface{}) + if !ok { + return "", false + } + image, _ := svc["image"].(string) + return strings.TrimSpace(image), true +} + +func pulledImages(services map[string]interface{}) []string { + var images []string + for _, raw := range services { + if svc, ok := raw.(map[string]interface{}); ok { + if image, _ := svc["image"].(string); image != "" && ValidImageRef(strings.TrimSpace(image)) { + images = append(images, image) + } + } + } + sort.Strings(images) + return images +} diff --git a/galvanize-instancer/internal/build/policy.go b/galvanize-instancer/internal/build/policy.go new file mode 100644 index 0000000..3d8e87f --- /dev/null +++ b/galvanize-instancer/internal/build/policy.go @@ -0,0 +1,358 @@ +package build + +import ( + "bufio" + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/internal/pathutil" + "github.com/28Pollux28/galvanize/pkg/config" + yaml "github.com/oasdiff/yaml3" +) + +// What a challenge repository may build. Its content comes from whoever can +// push to it, and a build runs on every Ansible host, so: +// - names (images, services, Dockerfiles) must be plain names, never +// options or template expressions; +// - a compose build section may only use keys that read the build context +// (no host paths, host network, secrets, SSH agent or extra tags); +// - a challenge may not tag an image that another challenge folder uses +// (deploys, builds, or builds FROM), nor one of the platform's images: +// the deployments run with pull: missing, so a local tag of that name +// would replace the real image for everyone using it. + +const label = `[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?` + +var ( + // Docker image reference: [domain[:port]/]path[:tag][@digest] + // (the first component is a registry only with a dot, a port or as + // localhost; otherwise it is a lowercase path component) + imageRefRe = regexp.MustCompile(`^(?:(?:localhost|` + label + `(?:\.` + label + `)+)(?::[0-9]+)?/|` + label + `:[0-9]+/)?` + + `[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*` + + `(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?(?:@sha256:[a-f0-9]{64})?$`) + serviceRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$`) + fileRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) + fromRe = regexp.MustCompile(`(?i)^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?`) +) + +// DefaultProtectedImages are used when build.protected_images is not set: +// Galvanize's own images and the services it runs with, and the usual +// databases. The platform in front of Galvanize lists its own images in +// build.protected_images. +var DefaultProtectedImages = []string{ + "traefik", "mariadb", "mysql", "redis", "postgres", + "ghcr.io/28pollux28/", +} + +// ValidImageRef reports whether s is a plain image reference. +func ValidImageRef(s string) bool { return len(s) <= 255 && imageRefRe.MatchString(s) } + +// NormalizeImage returns the canonical form of an image reference: without +// the default registry and library namespace, with ":latest" when it has no +// tag or digest ("nginx" and "docker.io/library/nginx:latest" are the same). +func NormalizeImage(ref string) string { + ref = strings.TrimSpace(ref) + for _, p := range []string{"docker.io/", "index.docker.io/", "registry-1.docker.io/"} { + if strings.HasPrefix(strings.ToLower(ref), p) { + ref = ref[len(p):] + break + } + } + ref = strings.TrimPrefix(ref, "library/") + last := ref[strings.LastIndex(ref, "/")+1:] + if !strings.Contains(last, ":") && !strings.Contains(ref, "@") { + ref += ":latest" + } + return ref +} + +// repository is a normalized reference without its tag and digest. +func repository(normalized string) string { + if i := strings.Index(normalized, "@"); i >= 0 { + normalized = normalized[:i] + } + if i := strings.LastIndex(normalized, ":"); i > strings.LastIndex(normalized, "/") { + normalized = normalized[:i] + } + return normalized +} + +// Protected reports whether image matches an entry of protected: an image +// repository (any tag), or a prefix when the entry ends with "/". +func Protected(image string, protected []string) bool { + repo := repository(NormalizeImage(image)) + for _, p := range protected { + p = strings.TrimSpace(p) + if p == "" { + continue + } + if strings.HasSuffix(p, "/") { + if strings.HasPrefix(repo, strings.TrimPrefix(p, "docker.io/")) { + return true + } + continue + } + if repo == repository(NormalizeImage(p)) { + return true + } + } + return false +} + +// ProtectedImages returns build.protected_images, or the defaults. +func ProtectedImages(conf *config.Config) []string { + if conf != nil && conf.Instancer.Build.ProtectedImages != nil { + return conf.Instancer.Build.ProtectedImages + } + return DefaultProtectedImages +} + +// ImageUsers maps each image (normalized) used by the catalog to the +// challenge folders using it. +type ImageUsers map[string]map[string]bool + +// Catalog is what planning builds needs from every challenge definition: +// each one's plan, and the images each challenge folder deploys, builds and +// builds from. Making it reads every compose file and Dockerfile, so it is +// made once per challenge index (see NewCatalog), and never changed. +type Catalog struct { + challenges []*challenge.Challenge + plans map[*challenge.Challenge]Plan + users ImageUsers +} + +// NewCatalog plans every challenge of catalog and indexes their images. +func NewCatalog(catalog []*challenge.Challenge) *Catalog { + cat := &Catalog{ + challenges: append([]*challenge.Challenge(nil), catalog...), + plans: make(map[*challenge.Challenge]Plan, len(catalog)), + users: ImageUsers{}, + } + add := func(image, dir string) { + if strings.TrimSpace(image) == "" { + return + } + n := NormalizeImage(image) + if cat.users[n] == nil { + cat.users[n] = map[string]bool{} + } + cat.users[n][dir] = true + } + seenDirs := map[string]bool{} + for _, c := range catalog { + dir := filepath.Clean(c.Dir) + plan := PlanFor(c) + cat.plans[c] = plan + for _, img := range plan.Images { + add(img, dir) + } + if image, ok := c.DeployParameters["image"].(string); ok { + add(image, dir) + } + if def, ok := c.DeployParameters["compose_definition"].(string); ok { + for _, img := range composeImages(def) { + add(img, dir) + } + } + if !seenDirs[dir] { + seenDirs[dir] = true + for _, img := range baseImages(dir) { + add(img, dir) + } + } + } + return cat +} + +// Of reports whether cat was made from these challenges: the index makes +// new Challenge values each time it is rebuilt. +func (cat *Catalog) Of(catalog []*challenge.Challenge) bool { + if cat == nil || len(cat.challenges) != len(catalog) { + return false + } + for i, c := range catalog { + if cat.challenges[i] != c { + return false + } + } + return true +} + +// Plan is PlanFor(c), computed once for the challenges of the catalog. +func (cat *Catalog) Plan(c *challenge.Challenge) Plan { + if cat != nil { + if plan, ok := cat.plans[c]; ok { + return plan + } + } + return PlanFor(c) +} + +// PlanIn is Plan, refused (KindNone, Refused set) when the challenge may not +// build its images: see checkOwnership. +func (cat *Catalog) PlanIn(c *challenge.Challenge, protected []string) Plan { + plan := cat.Plan(c) + if plan.Kind == KindNone { + return plan + } + var users ImageUsers + if cat != nil { + users = cat.users + } + if problem := checkOwnership(c, plan, users, protected); problem != "" { + return Plan{Kind: KindNone, Refused: true, Reason: "refused: " + problem, Images: plan.Images} + } + return plan +} + +// composeImages lists the images of a compose document's services. +func composeImages(def string) []string { + var doc map[string]interface{} + if err := yaml.Unmarshal([]byte(def), &doc); err != nil { + return nil + } + services, _ := doc["services"].(map[string]interface{}) + return pulledImages(services) +} + +// baseImages lists the FROM images of the Dockerfiles in dir (stages of the +// same Dockerfile and references built from build arguments left out). +func baseImages(dir string) []string { + var out []string + _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() { + if path != dir && (strings.HasPrefix(d.Name(), ".") || d.Name() == "node_modules") { + return filepath.SkipDir + } + return nil + } + if !isDockerfile(d.Name()) || !d.Type().IsRegular() { + return nil + } + f, err := os.Open(path) + if err != nil { + return nil + } + defer func() { _ = f.Close() }() + stages := map[string]bool{} + scanner := bufio.NewScanner(f) + for scanner.Scan() { + m := fromRe.FindStringSubmatch(scanner.Text()) + if m == nil { + continue + } + ref := m[1] + if !stages[strings.ToLower(ref)] && !strings.Contains(ref, "$") && strings.ToLower(ref) != "scratch" { + out = append(out, ref) + } + if m[2] != "" { + stages[strings.ToLower(m[2])] = true + } + } + return nil + }) + return out +} + +// checkOwnership returns why c may not build plan's images, or "". +func checkOwnership(c *challenge.Challenge, plan Plan, users ImageUsers, protected []string) string { + dir := filepath.Clean(c.Dir) + var problems []string + for _, img := range plan.Images { + if Protected(img, protected) { + problems = append(problems, fmt.Sprintf("%s is a platform image (build.protected_images)", img)) + continue + } + var others []string + for d := range users[NormalizeImage(img)] { + if d != dir { + others = append(others, d) + } + } + if len(others) > 0 { + sort.Strings(others) + problems = append(problems, fmt.Sprintf("%s is also used by %s", img, strings.Join(others, ", "))) + } + } + return strings.Join(problems, "; ") +} + +// buildKeys are the compose build keys a challenge may use. Left out on +// purpose: network (host network), additional_contexts, secrets, ssh, +// cache_from/cache_to (host paths), extra_hosts, tags (more image names), +// entitlements, privileged, isolation. +var buildKeys = map[string]bool{ + "context": true, "dockerfile": true, "dockerfile_inline": true, "args": true, + "target": true, "labels": true, "shm_size": true, "no_cache": true, "pull": true, + "platforms": true, +} + +// sanitizeBuild checks a compose build section. Contexts and Dockerfiles must +// be relative paths inside the challenge folder (composeDir being the folder +// of the compose file, which the paths are relative to). +func sanitizeBuild(raw interface{}, challDir, composeDir string) (map[string]interface{}, error) { + var b map[string]interface{} + switch v := raw.(type) { + case string: + b = map[string]interface{}{"context": v} + case map[string]interface{}: + b = map[string]interface{}{} + for k, val := range v { + if !buildKeys[k] { + return nil, fmt.Errorf("build.%s is not allowed", k) + } + b[k] = val + } + case nil: + b = map[string]interface{}{} + default: + return nil, fmt.Errorf("build must be a path or a mapping") + } + ctx := "." + if v, ok := b["context"]; ok { + s, ok := v.(string) + if !ok || strings.TrimSpace(s) == "" { + return nil, fmt.Errorf("build.context must be a path") + } + ctx = s + } + ctxDir, err := insideDir(challDir, composeDir, ctx, "build.context") + if err != nil { + return nil, err + } + if v, ok := b["dockerfile"]; ok { + s, ok := v.(string) + if !ok || strings.TrimSpace(s) == "" { + return nil, fmt.Errorf("build.dockerfile must be a path") + } + if _, err := insideDir(challDir, ctxDir, s, "build.dockerfile"); err != nil { + return nil, err + } + } + return b, nil +} + +// insideDir resolves rel against from and checks it stays inside root. +func insideDir(root, from, rel, what string) (string, error) { + lower := strings.ToLower(rel) + if strings.Contains(rel, "://") || strings.HasPrefix(lower, "git@") || strings.HasPrefix(lower, "github.com/") { + return "", fmt.Errorf("%s %q: remote contexts are not allowed", what, rel) + } + if filepath.IsAbs(rel) || strings.HasPrefix(rel, "~") || strings.Contains(rel, "\\") { + return "", fmt.Errorf("%s %q must be a relative path", what, rel) + } + p := filepath.Join(from, filepath.FromSlash(rel)) + if !pathutil.Inside(root, p) { + return "", fmt.Errorf("%s %q leaves the challenge folder", what, rel) + } + return p, nil +} diff --git a/galvanize-instancer/internal/build/policy_test.go b/galvanize-instancer/internal/build/policy_test.go new file mode 100644 index 0000000..a17ee17 --- /dev/null +++ b/galvanize-instancer/internal/build/policy_test.go @@ -0,0 +1,145 @@ +package build + +import ( + "context" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/28Pollux28/galvanize/internal/ansible" + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const composeChall = "name: Lab\ncategory: Web\ntype: zync\n" + +func TestPlan_RefusesUnsafeComposeBuildSections(t *testing.T) { + for name, build := range map[string]string{ + "host network": " context: .\n network: host\n", + "secrets": " context: .\n secrets: [token]\n", + "ssh agent": " context: .\n ssh: [default]\n", + "extra contexts": " context: .\n additional_contexts:\n etc: /etc\n", + "extra tags": " context: .\n tags: [traefik:v3.7]\n", + "host cache": " context: .\n cache_from: [\"type=local,src=/root\"]\n", + "absolute context": " context: /etc\n", + "parent context": " context: ../other\n", + "remote context": " context: https://github.com/org/repo.git\n", + "git context": " context: git@github.com:org/repo.git\n", + "absolute dockerfile": " context: .\n dockerfile: /etc/Dockerfile\n", + "parent dockerfile": " context: .\n dockerfile: ../../Dockerfile\n", + } { + t.Run(name, func(t *testing.T) { + c := load(t, map[string]string{"challenge.yml": composeChall, "compose.yml": "services:\n web:\n build:\n" + build}) + p := PlanFor(c) + assert.True(t, p.Refused, p.Reason) + assert.Equal(t, KindNone, p.Kind) + }) + } + + c := load(t, map[string]string{"challenge.yml": composeChall, "compose.yml": "services:\n web:\n build:\n context: ./app\n dockerfile: Dockerfile.prod\n args:\n FLAG: x\n target: run\n"}) + p := PlanFor(c) + assert.Equal(t, KindCompose, p.Kind, p.Reason) +} + +func TestPlan_RefusesNamesThatAreNotPlainNames(t *testing.T) { + for _, image := range []string{"{{ lookup('pipe', 'id') }}", "--privileged", "UPPER/case", "a b", "x:" + strings.Repeat("t", 200)} { + c := load(t, map[string]string{"challenge.yml": strings.Replace(httpChall, "webapp", strconv.Quote(image), 1), "Dockerfile": "FROM x\n"}) + assert.True(t, PlanFor(c).Refused, image) + } + c := load(t, map[string]string{"challenge.yml": composeChall, "compose.yml": "services:\n \"-x\":\n build: .\n"}) + assert.True(t, PlanFor(c).Refused, "service name starting with a dash") + + for _, ok := range []string{"webapp", "nssha-1", "rabb-it-hol:latest", "ghcr.io/polycyber/polypwn2026/up:latest", "localhost:5000/a/b:1.0", "a@sha256:" + strings.Repeat("0", 64)} { + assert.True(t, ValidImageRef(ok), ok) + } +} + +func TestPlan_ComposeFileMustBuildWhatTheInlineDefinitionDeploys(t *testing.T) { + inline := composeChall + "deploy_parameters:\n compose_definition: |\n services:\n web:\n image: lab-web:2\n" + c := load(t, map[string]string{"challenge.yml": inline, "compose.yml": "services:\n web:\n build: .\n image: lab-web:1\n"}) + c.PlaybookName = "custom_compose" + p := PlanFor(c) + require.True(t, p.Refused) + assert.Contains(t, p.Reason, "builds lab-web:1 but the deployment") + + same := composeChall + "deploy_parameters:\n compose_definition: |\n services:\n web:\n image: lab-web\n" + c = load(t, map[string]string{"challenge.yml": same, "compose.yml": "services:\n web:\n build: .\n image: lab-web:latest\n"}) + c.PlaybookName = "custom_compose" + assert.Equal(t, KindCompose, PlanFor(c).Kind, "lab-web and lab-web:latest are the same image") +} + +func TestNormalizeAndProtected(t *testing.T) { + assert.Equal(t, "nginx:latest", NormalizeImage("docker.io/library/nginx")) + assert.Equal(t, "nginx:alpine", NormalizeImage("nginx:alpine")) + assert.Equal(t, "localhost:5000/a:latest", NormalizeImage("localhost:5000/a")) + assert.True(t, Protected("traefik:v3.7", DefaultProtectedImages)) + assert.True(t, Protected("docker.io/library/mariadb", DefaultProtectedImages)) + assert.True(t, Protected("ghcr.io/28pollux28/galvanize:0.7.5", DefaultProtectedImages)) + assert.False(t, Protected("traefik-chall:1", DefaultProtectedImages)) + assert.False(t, Protected("polypwn/redis-lab", DefaultProtectedImages)) +} + +// catalogOf indexes several challenge folders under one challenge_dir. +func catalogOf(t *testing.T, folders map[string]map[string]string) []*challenge.Challenge { + t.Helper() + base := t.TempDir() + for dir, files := range folders { + for name, content := range files { + p := filepath.Join(base, dir, name) + require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o755)) + require.NoError(t, os.WriteFile(p, []byte(content), 0o644)) + } + } + idx, err := challenge.NewChallengeIndex(base) + require.NoError(t, err) + return idx.Catalog() +} + +func TestPlanIn_ImagesOfOtherChallengeFolders(t *testing.T) { + chall := func(name, image string) string { + return "name: " + name + "\ncategory: Web\ntype: zync\nplaybook_name: http\ndeploy_parameters:\n image: " + image + "\n" + } + catalog := catalogOf(t, map[string]map[string]string{ + "a/web/one": {"challenge.yml": chall("One", "shared:1"), "Dockerfile": "FROM x\n"}, + "a/web/two": {"challenge.yml": chall("Two", "shared:1"), "Dockerfile": "FROM x\n"}, + "b/web/base": {"challenge.yml": chall("Base", "python:3.12-slim"), "Dockerfile": "FROM x\n"}, + "b/web/app": {"challenge.yml": chall("App", "app:1"), "Dockerfile": "FROM python:3.12-slim AS build\nFROM build\nFROM ${BASE}\n"}, + "c/web/multi": {"challenge-1.yml": chall("M1", "multi:1"), "challenge-2.yml": chall("M2", "multi:1"), "Dockerfile": "FROM x\n"}, + }) + byName := map[string]*challenge.Challenge{} + for _, c := range catalog { + byName[c.Name] = c + } + cat := NewCatalog(catalog) + for _, name := range []string{"One", "Two"} { + p := cat.PlanIn(byName[name], nil) + assert.True(t, p.Refused, name) + assert.Contains(t, p.Reason, "shared:1 is also used by") + } + p := cat.PlanIn(byName["Base"], nil) + assert.True(t, p.Refused, "builds an image another challenge builds FROM") + assert.Equal(t, KindImage, cat.PlanIn(byName["App"], nil).Kind, "stage names and build args are not images") + assert.Equal(t, KindImage, cat.PlanIn(byName["M1"], nil).Kind, "challenges of one folder share their image") + assert.True(t, cat.PlanIn(byName["App"], []string{"app"}).Refused, "protected image") +} + +func TestBuild_EveryHostMustBuild(t *testing.T) { + c := load(t, map[string]string{"challenge.yml": httpChall, "Dockerfile": "FROM x\n"}) + runner := &fakeRunner{respond: func(map[string]interface{}) ([]ansible.HostResult, error) { + return []ansible.HostResult{ + {Host: "h1", Task: "Create build directory"}, {Host: "h1", Task: "Build"}, + {Host: "h2", Task: "Create build directory"}, // h2 never ran the build + }, nil + }} + log := &memLog{} + res := (&Builder{Runner: runner}).Build(context.Background(), confWith(1), []*challenge.Challenge{c}, nil, false, log) + assert.Equal(t, []*challenge.Challenge{c}, res.Failed) + assert.Contains(t, log.text(), "did not run on h2") + + runner.respond = func(map[string]interface{}) ([]ansible.HostResult, error) { return nil, nil } + res = (&Builder{Runner: runner}).Build(context.Background(), confWith(1), []*challenge.Challenge{c}, nil, false, log) + assert.Equal(t, []*challenge.Challenge{c}, res.Failed, "no host at all") +} diff --git a/galvanize-instancer/internal/challenge/catalog_test.go b/galvanize-instancer/internal/challenge/catalog_test.go new file mode 100644 index 0000000..4fe014a --- /dev/null +++ b/galvanize-instancer/internal/challenge/catalog_test.go @@ -0,0 +1,143 @@ +package challenge + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCatalog_ListsEveryTypeWithTheRawDefinition(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "repo/misc/intro", "name: Intro\ncategory: Misc\ntype: standard\nflags: [\"F{x}\"]\nhints:\n - {content: h, cost: 5}\n") + writeChallenge(t, dir, "repo/web/app", "name: App\ncategory: Web\ntype: zync\ndeploy_parameters:\n image: app\n") + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Len(t, idx.GetAll(), 1, "only zync challenges are deployable") + cat := idx.Catalog() + require.Len(t, cat, 2) + assert.Equal(t, "Intro", cat[0].Name, "sorted by path") + assert.Equal(t, []interface{}{"F{x}"}, cat[0].Definition["flags"]) + hints := cat[0].Definition["hints"].([]interface{}) + assert.Equal(t, 5, hints[0].(map[string]interface{})["cost"]) + assert.Equal(t, filepath.Join(dir, "repo/misc/intro/challenge.yml"), cat[0].File) +} + +func TestCatalog_DefinitionIsNotChangedByDeploymentDefaults(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "repo/web/app", "name: App\ncategory: Web\ntype: zync\nplaybook_name: tcp\ndeploy_parameters:\n image: app\n port: 22\n") + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + c := idx.Catalog()[0] + assert.Contains(t, c.DeployParameters, "published_ports", "deployment defaults applied") + assert.NotContains(t, c.Definition["deploy_parameters"], "published_ports", "raw definition untouched") +} + +func TestBuildIndex_SkipsHiddenFolders(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, ".galvanize-tmp/x/web/app", "name: Tmp\ncategory: Web\ntype: zync\n") + writeChallenge(t, dir, "repo/.github/app", "name: Gh\ncategory: Web\ntype: zync\n") + writeChallenge(t, dir, "repo/web/app", "name: App\ncategory: Web\ntype: zync\n") + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + require.Len(t, idx.Catalog(), 1) + assert.Equal(t, "App", idx.Catalog()[0].Name) +} + +func TestBuildIndex_TagsBuiltServicesWithoutImage(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "repo/web/lab", "name: My Lab\ncategory: Web\ntype: zync\n") + require.NoError(t, os.WriteFile(filepath.Join(dir, "repo/web/lab/compose.yml"), + []byte("services:\n web:\n build: .\n db:\n image: mariadb:11\n api:\n build: ./api\n image: lab-api:2\n"), 0o644)) + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + c, err := idx.Get("Web", "My Lab") + require.NoError(t, err) + def := c.DeployParameters["compose_definition"].(string) + assert.Contains(t, def, "image: "+BuiltImageTag("Web", "My Lab", "web")) + assert.Contains(t, def, "image: lab-api:2", "explicit image kept") + assert.Contains(t, def, "image: mariadb:11") + assert.Equal(t, filepath.Join(dir, "repo/web/lab/compose.yml"), c.ComposeFile) +} + +func TestImageSlug(t *testing.T) { + assert.Equal(t, "la-fondatrice-1", ImageSlug("La Fondatrice 1")) + assert.Equal(t, "rabb-it-h-o-l", ImageSlug("Rabb-IT H.O.L")) + assert.Regexp(t, `^galvanize/web-a-b-svc-[0-9a-f]{10}:latest$`, BuiltImageTag("Web", "A b!", "svc")) + // Names sharing a slug get different tags + assert.NotEqual(t, BuiltImageTag("web", "a-b", "svc"), BuiltImageTag("web-a", "b", "svc")) + assert.NotEqual(t, BuiltImageTag("Web", "app", "svc"), BuiltImageTag("web", "app", "svc")) + assert.NotEqual(t, BuiltImageTag("Web", "défi", "svc"), BuiltImageTag("Web", "défo", "svc")) + assert.Regexp(t, `^galvanize/x-x-x-[0-9a-f]{10}:latest$`, BuiltImageTag("密码", "挑战", "服务")) +} + +func TestBuildIndex_ComposeFileStaysInTheChallengeFolder(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "host-compose.yml"), []byte("services:\n x:\n image: a\n"), 0o644)) + writeChallenge(t, dir, "repo/web/a", "name: A\ncategory: Web\ntype: zync\ndeploy_parameters:\n compose_file: ../../../host-compose.yml\n") + writeChallenge(t, dir, "repo/web/b", "name: B\ncategory: Web\ntype: zync\ndeploy_parameters:\n compose_file: /etc/hosts\n") + require.NoError(t, os.Symlink(filepath.Join(dir, "host-compose.yml"), filepath.Join(dir, "repo/web/c-link.yml"))) + writeChallenge(t, dir, "repo/web/c", "name: C\ncategory: Web\ntype: zync\ndeploy_parameters:\n compose_file: ../c-link.yml\n") + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Empty(t, idx.GetAll()) + require.Len(t, idx.Skipped(), 3) + for _, sk := range idx.Skipped() { + assert.Contains(t, sk.Reason, "inside the challenge folder", sk.Path) + } +} + +func TestBuildIndex_UntaggedJinjaComposeIsKept(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "repo/web/j", "name: J\ncategory: Web\ntype: zync\nplaybook_name: custom_compose\ndeploy_parameters:\n compose_definition: |\n services:\n web:\n image: {{ image }}\n") + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + c, err := idx.Get("Web", "J") + require.NoError(t, err) + assert.Contains(t, c.DeployParameters["compose_definition"], "{{ image }}", "deployed as written") +} + +func TestBuildIndex_ComposeFileNextToAnInlineDefinition(t *testing.T) { + dir := t.TempDir() + inline := "name: %s\ncategory: Web\ntype: zync\nplaybook_name: custom_compose\ndeploy_parameters:\n" + + " compose_definition: |\n services:\n web:\n image: w\n" + require.NoError(t, os.WriteFile(filepath.Join(dir, "host-compose.yml"), []byte("services:\n x:\n build: .\n"), 0o644)) + // Explicit compose_file: checked even though the inline definition is deployed + writeChallenge(t, dir, "repo/web/a", fmt.Sprintf(inline, "A")+" compose_file: ../../../host-compose.yml\n") + writeChallenge(t, dir, "repo/web/b", fmt.Sprintf(inline, "B")+" compose_file: build/compose.yml\n") + writeFile(t, dir, "repo/web/b/build", "compose.yml", "services:\n web:\n build: .\n image: w\n") + // A standard name, as a symlink leading outside + writeChallenge(t, dir, "repo/web/c", fmt.Sprintf(inline, "C")) + require.NoError(t, os.Symlink(filepath.Join(dir, "host-compose.yml"), filepath.Join(dir, "repo/web/c/compose.yml"))) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + require.Len(t, idx.Skipped(), 2) + for _, sk := range idx.Skipped() { + assert.Contains(t, sk.Reason, "inside the challenge folder", sk.Path) + } + b, err := idx.Get("Web", "B") + require.NoError(t, err) + assert.True(t, b.ComposeInline) + assert.Equal(t, filepath.Join(dir, "repo/web/b/build/compose.yml"), b.ComposeFile, "read to build") + assert.Contains(t, b.DeployParameters["compose_definition"], "image: w", "the inline definition is deployed") + assert.NotContains(t, b.DeployParameters, "compose_file") +} + +func TestFiles_LookedUpInTheFolderThenFiles(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "r/misc/a", "name: A\ncategory: Misc\ntype: standard\nfiles: [x.txt, ./files/y.txt, 3, \"\"]\n") + writeFile(t, dir, "r/misc/a/files", "x.txt", "x") + writeFile(t, dir, "r/misc/a/files", "y.txt", "yy") + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + files := idx.Catalog()[0].Files() + require.Len(t, files, 3) + assert.Equal(t, File{Declared: "x.txt", Path: filepath.Join(dir, "r/misc/a/files/x.txt"), Size: 1}, files[0]) + assert.Equal(t, filepath.Join(dir, "r/misc/a/files/y.txt"), files[1].Path) + assert.Equal(t, File{Declared: "3", Error: "not a file path"}, files[2]) +} diff --git a/galvanize-instancer/internal/challenge/challenge.go b/galvanize-instancer/internal/challenge/challenge.go index 0e65de4..54eb420 100644 --- a/galvanize-instancer/internal/challenge/challenge.go +++ b/galvanize-instancer/internal/challenge/challenge.go @@ -1,6 +1,9 @@ package challenge import ( + "crypto/sha256" + "encoding/hex" + "errors" "fmt" "io/fs" "os" @@ -8,6 +11,7 @@ import ( "strings" "sync" + "github.com/28Pollux28/galvanize/internal/pathutil" "github.com/28Pollux28/galvanize/pkg/config" yaml "github.com/oasdiff/yaml3" "go.uber.org/zap" @@ -127,6 +131,10 @@ type ChallengeIndexer interface { BuildIndex(baseDir string) error // Skipped lists the challenge files the last BuildIndex left out. Skipped() []SkippedChallenge + // Catalog lists every challenge definition the last BuildIndex read, + // whatever its type (Get and GetAll only know deployable zync + // challenges), sorted by file path. + Catalog() []*Challenge } // SkippedChallenge is a challenge file left out of the index, and why. @@ -141,6 +149,7 @@ var _ ChallengeIndexer = (*ChallengeIndex)(nil) type ChallengeIndex struct { mu sync.RWMutex challs map[string]*Challenge + catalog []*Challenge skipped []SkippedChallenge } @@ -155,6 +164,21 @@ type Challenge struct { ResourceLimits config.ResourceLimits `yaml:"-"` Dir string `yaml:"-"` DeployParameters map[string]interface{} `yaml:"deploy_parameters"` + // File is the challenge definition file the challenge was read from. + File string `yaml:"-"` + // ComposeFile is the Compose file of the challenge folder (explicit + // compose_file, else a standard name), checked to be inside it: the one + // compose_definition was loaded from or, next to an inline + // compose_definition (ComposeInline), the one images are built from. + // Empty when there is none. + ComposeFile string `yaml:"-"` + // ComposeInline: compose_definition is written in the definition file, + // and deployed instead of ComposeFile. + ComposeInline bool `yaml:"-"` + // Definition is the whole definition file, as parsed, for clients that + // need more than the deployment fields (e.g. a CTF platform importing + // flags and descriptions). Never modified by Galvanize. + Definition map[string]interface{} `yaml:"-"` } // InstanceKey is the name deployments of this challenge are stored and @@ -192,6 +216,7 @@ func NewChallengeIndex(baseDir string) (*ChallengeIndex, error) { func (idx *ChallengeIndex) BuildIndex(baseDir string) error { challs := make(map[string]*Challenge) paths := make(map[string]string) + var catalog []*Challenge var skipped []SkippedChallenge skip := func(path, reason string) { skipped = append(skipped, SkippedChallenge{Path: path, Reason: reason}) @@ -210,7 +235,9 @@ func (idx *ChallengeIndex) BuildIndex(baseDir string) error { return nil } if d.IsDir() { - if d.Name() == ".git" || d.Name() == "node_modules" || d.Name() == "example" { + // Hidden folders are skipped too: they hold tooling (.git, + // .github) and the temporary clones of the repository manager + if path != baseDir && (strings.HasPrefix(d.Name(), ".") || d.Name() == "node_modules" || d.Name() == "example") { return filepath.SkipDir } return nil @@ -225,6 +252,7 @@ func (idx *ChallengeIndex) BuildIndex(baseDir string) error { // files and one bad file must not hide its siblings. return nil } + catalog = append(catalog, chall) if chall.Type != "zync" { return nil } @@ -244,11 +272,20 @@ func (idx *ChallengeIndex) BuildIndex(baseDir string) error { idx.mu.Lock() idx.challs = challs + idx.catalog = catalog idx.skipped = skipped idx.mu.Unlock() return nil } +// Catalog returns every challenge definition read by the last successful +// BuildIndex, in file path order (WalkDir's lexical order). +func (idx *ChallengeIndex) Catalog() []*Challenge { + idx.mu.RLock() + defer idx.mu.RUnlock() + return append([]*Challenge(nil), idx.catalog...) +} + // Skipped returns the challenge files the last successful BuildIndex left out. func (idx *ChallengeIndex) Skipped() []SkippedChallenge { idx.mu.RLock() @@ -306,6 +343,18 @@ func parseChallenge(challengeFilePath string) (*Challenge, error) { if err != nil { return nil, fmt.Errorf("failed to parse challenge file: %w", err) } + var definition interface{} + if err := yaml.Unmarshal(data, &definition); err != nil { + return nil, fmt.Errorf("failed to parse challenge file: %w", err) + } + normalized, err := jsonSafe(definition, "") + if err != nil { + return nil, fmt.Errorf("challenge file cannot be served as JSON: %w", err) + } + if m, ok := normalized.(map[string]interface{}); ok { + challenge.Definition = m + } + challenge.File = challengeFilePath if challenge.Name == "" { return nil, fmt.Errorf("missing name in challenge file") } @@ -358,6 +407,9 @@ func parseChallenge(challengeFilePath string) (*Challenge, error) { if err := loadComposeDefinition(&challenge); err != nil { return nil, err } + if err := tagBuiltServices(&challenge); err != nil { + return nil, err + } if err := validateExposures(&challenge); err != nil { return nil, err @@ -371,23 +423,25 @@ func parseChallenge(challengeFilePath string) (*Challenge, error) { // embedding the whole document as a multiline string under // deploy_parameters.compose_definition. // -// Resolution order: -// 1. An inline deploy_parameters.compose_definition always wins. -// 2. An explicit deploy_parameters.compose_file (path relative to the -// challenge directory). -// 3. Auto-detected standard Compose file names in the challenge directory. +// The Compose file is an explicit deploy_parameters.compose_file (path +// relative to the challenge directory), else the first standard Compose file +// name found in the challenge directory. It must stay inside the challenge +// folder, symlinks included. An inline deploy_parameters.compose_definition +// wins over it for the deployment (the file is then only read to build). // // When a file is loaded, its contents are placed in compose_definition so the // existing custom_compose playbook consumes it unchanged, and playbook_name // defaults to "custom_compose" if the author did not set one. func loadComposeDefinition(c *Challenge) error { - if def, ok := c.DeployParameters["compose_definition"].(string); ok && strings.TrimSpace(def) != "" { - return nil - } - var composePath string if explicit := toStringField(c.DeployParameters, "compose_file"); explicit != "" { - composePath = filepath.Join(c.Dir, explicit) + if filepath.IsAbs(explicit) || strings.HasPrefix(explicit, "/") { + return fmt.Errorf("compose_file %q for challenge %q: must be a path inside the challenge folder", explicit, c.Name) + } + composePath = filepath.Join(c.Dir, filepath.FromSlash(explicit)) + if err := insideChallengeDir(c.Dir, composePath); err != nil { + return fmt.Errorf("compose_file %q for challenge %q: %w", explicit, c.Name, err) + } if _, err := os.Stat(composePath); err != nil { return fmt.Errorf("compose_file %q for challenge %q not found: %w", explicit, c.Name, err) } @@ -396,12 +450,20 @@ func loadComposeDefinition(c *Challenge) error { for _, name := range composeFileNames { candidate := filepath.Join(c.Dir, name) if _, err := os.Stat(candidate); err == nil { + if err := insideChallengeDir(c.Dir, candidate); err != nil { + return fmt.Errorf("%s for challenge %q: %w", name, c.Name, err) + } composePath = candidate break } } } + c.ComposeFile = composePath + if def, ok := c.DeployParameters["compose_definition"].(string); ok && strings.TrimSpace(def) != "" { + c.ComposeInline = true + return nil + } if composePath == "" { return nil } @@ -428,6 +490,23 @@ func loadComposeDefinition(c *Challenge) error { return nil } +// insideChallengeDir checks that path, symlinks resolved, is inside dir: +// a challenge reads no file of another challenge or of the host. +func insideChallengeDir(dir, path string) error { + outside := fmt.Errorf("must be inside the challenge folder") + if !pathutil.Inside(dir, path) { + return outside + } + _, err := pathutil.Resolve(dir, path) + switch { + case errors.Is(err, pathutil.ErrOutside): + return outside + case err != nil && !errors.Is(err, fs.ErrNotExist): + return err + } + return nil // missing: reported by the caller +} + // validateExposures checks the optional expose block: entries must be // well-formed and reference services that exist in the compose definition. // It runs after the compose definition has been resolved so authors get clear @@ -459,3 +538,93 @@ func validateExposures(c *Challenge) error { } return nil } + +// BuiltImageTag is the image a Compose service with a build section but no +// image is tagged with: Galvanize builds it under that name on the Ansible +// hosts and deploys it from there. The readable part is made of slugs, which +// several names share ("web/a-b" and "web-a/b", "Web" and "web", non-ASCII +// names); the hash of the exact names makes the tag unique to one service of +// one challenge. +func BuiltImageTag(category, challengeName, service string) string { + return "galvanize/" + BuildSlug(category, challengeName, service) + ":latest" +} + +// BuildSlug joins the slugs of parts and a hash of their exact values, for +// image and Compose project names unique to these parts. +func BuildSlug(parts ...string) string { + h := sha256.New() + slugs := make([]string, 0, len(parts)+1) + for _, p := range parts { + h.Write([]byte(p)) + h.Write([]byte{0}) + slug := ImageSlug(p) + if len(slug) > 40 { + slug = strings.TrimRight(slug[:40], "-") + } + if slug == "" { + slug = "x" + } + slugs = append(slugs, slug) + } + return strings.Join(slugs, "-") + "-" + hex.EncodeToString(h.Sum(nil))[:10] +} + +// ImageSlug lowercases s and replaces runs of other characters than a-z and +// 0-9 with a dash, for Docker image and project names. Different names can +// share a slug: see BuildSlug for unique names. +func ImageSlug(s string) string { + var b strings.Builder + dash := false + for _, r := range strings.ToLower(s) { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') { + b.WriteRune(r) + dash = false + } else if !dash && b.Len() > 0 { + b.WriteByte('-') + dash = true + } + } + return strings.TrimRight(b.String(), "-") +} + +// tagBuiltServices gives every service of a string compose_definition that +// has a build section and no image the BuiltImageTag name. Without it, the +// deployment could only try to build from a context that does not exist on +// the host, while the build feature builds exactly this name. +func tagBuiltServices(c *Challenge) error { + def, ok := c.DeployParameters["compose_definition"].(string) + if !ok || strings.TrimSpace(def) == "" { + return nil + } + var doc map[string]interface{} + if err := yaml.Unmarshal([]byte(def), &doc); err != nil { + // Not YAML as it stands (e.g. Jinja expressions the playbook renders + // first): deployed as written, nothing to tag + return nil + } + services, _ := doc["services"].(map[string]interface{}) + changed := false + for name, raw := range services { + svc, ok := raw.(map[string]interface{}) + if !ok { + continue + } + if _, hasBuild := svc["build"]; !hasBuild { + continue + } + if image, _ := svc["image"].(string); strings.TrimSpace(image) != "" { + continue + } + svc["image"] = BuiltImageTag(c.Category, c.Name, name) + changed = true + } + if !changed { + return nil + } + out, err := yaml.Marshal(doc) + if err != nil { + return fmt.Errorf("failed to tag built services: %w", err) + } + c.DeployParameters["compose_definition"] = string(out) + return nil +} diff --git a/galvanize-instancer/internal/challenge/files.go b/galvanize-instancer/internal/challenge/files.go new file mode 100644 index 0000000..98dd781 --- /dev/null +++ b/galvanize-instancer/internal/challenge/files.go @@ -0,0 +1,107 @@ +package challenge + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + "path" + "path/filepath" + "strings" + + "github.com/28Pollux28/galvanize/internal/pathutil" +) + +// File is a file a definition declares (its files list), as found in the +// challenge folder. +type File struct { + Declared string + // Path is the file found, inside the challenge folder (symlinks not + // resolved); empty when there is none. + Path string + Size int64 + // Error says why the file cannot be served (Path may still be set). + Error string +} + +// lfsPointer starts the small text files Git LFS leaves in place of the +// real ones when the repository is cloned without git-lfs. +var lfsPointer = []byte("version https://git-lfs.github.com/spec/") + +// Files resolves the definition's files list. Each path is looked up in the +// challenge folder, then in its files/ subfolder. Absolute paths, paths +// leaving the challenge folder (symlinks included) or going through .git +// are refused, and so are Git LFS pointers. +func (c *Challenge) Files() []File { + list, _ := c.Definition["files"].([]interface{}) + out := make([]File, 0, len(list)) + for _, v := range list { + if v == nil || v == "" { + continue + } + declared, ok := v.(string) + if !ok { + out = append(out, File{Declared: fmt.Sprint(v), Error: "not a file path"}) + continue + } + out = append(out, c.resolveFile(declared)) + } + return out +} + +func (c *Challenge) resolveFile(declared string) File { + f := File{Declared: declared} + rel := strings.ReplaceAll(declared, "\\", "/") + if path.IsAbs(rel) { + f.Error = "absolute file paths are not allowed" + return f + } + rel = path.Clean(rel) + if rel == ".." || strings.HasPrefix(rel, "../") { + f.Error = "the path leaves the challenge folder" + return f + } + for _, part := range strings.Split(rel, "/") { + if part == ".git" { + f.Error = "files inside .git are not allowed" + return f + } + } + for _, dir := range []string{c.Dir, filepath.Join(c.Dir, "files")} { + p := filepath.Join(dir, filepath.FromSlash(rel)) + real, err := pathutil.Resolve(c.Dir, p) + if errors.Is(err, pathutil.ErrOutside) { + f.Error = "the path leads outside the challenge folder" + return f + } + if err != nil { + continue + } + st, err := os.Stat(real) + if err != nil || !st.Mode().IsRegular() { + continue + } + f.Path, f.Size = p, st.Size() + if isLFSPointer(real, st.Size()) { + f.Error = "a Git LFS pointer, not the file: Galvanize needs git-lfs to fetch it" + } + return f + } + f.Error = "not found (looked in the challenge folder and its files/ subfolder)" + return f +} + +func isLFSPointer(path string, size int64) bool { + if size > 1024 { + return false + } + file, err := os.Open(path) + if err != nil { + return false + } + defer func() { _ = file.Close() }() + head := make([]byte, len(lfsPointer)) + n, _ := io.ReadFull(file, head) + return bytes.Equal(head[:n], lfsPointer) +} diff --git a/galvanize-instancer/internal/challenge/jsonsafe.go b/galvanize-instancer/internal/challenge/jsonsafe.go new file mode 100644 index 0000000..b3b9efb --- /dev/null +++ b/galvanize-instancer/internal/challenge/jsonsafe.go @@ -0,0 +1,85 @@ +package challenge + +import ( + "fmt" + "math" + "strings" + "time" +) + +// jsonSafe returns v (a parsed YAML document) with only values JSON can +// encode: YAML allows mappings with non-string keys (1: x, true: y, nested +// mappings as keys) and .nan / .inf numbers, which would make encoding the +// whole challenge catalog fail. Scalar keys become strings when that loses +// nothing; anything else is an error naming where it is. +func jsonSafe(v interface{}, at string) (interface{}, error) { + switch t := v.(type) { + case map[string]interface{}: + out := make(map[string]interface{}, len(t)) + for k, val := range t { + n, err := jsonSafe(val, at+"."+k) + if err != nil { + return nil, err + } + out[k] = n + } + return out, nil + case map[interface{}]interface{}: + out := make(map[string]interface{}, len(t)) + for k, val := range t { + var key string + switch kk := k.(type) { + case string: + key = kk + case int, int64, uint64, bool: + key = fmt.Sprint(kk) + case float64: + if math.IsNaN(kk) || math.IsInf(kk, 0) { + return nil, fmt.Errorf("%s: unsupported key %v", where(at), kk) + } + key = fmt.Sprint(kk) + case nil: + key = "null" + default: + return nil, fmt.Errorf("%s: unsupported key of type %T", where(at), k) + } + if _, dup := out[key]; dup { + return nil, fmt.Errorf("%s: key %q appears twice once keys are strings", where(at), key) + } + n, err := jsonSafe(val, at+"."+key) + if err != nil { + return nil, err + } + out[key] = n + } + return out, nil + case []interface{}: + out := make([]interface{}, len(t)) + for i, val := range t { + n, err := jsonSafe(val, fmt.Sprintf("%s[%d]", at, i)) + if err != nil { + return nil, err + } + out[i] = n + } + return out, nil + case float64: + if math.IsNaN(t) || math.IsInf(t, 0) { + return nil, fmt.Errorf("%s: %v is not a JSON number", where(at), t) + } + return t, nil + case nil, string, bool, int, int64, uint64, time.Time: + return t, nil + case []byte: + return string(t), nil + default: + return nil, fmt.Errorf("%s: unsupported value of type %T", where(at), v) + } +} + +func where(at string) string { + if at == "" { + return "the document" + } + return strings.TrimPrefix(at, ".") +} diff --git a/galvanize-instancer/internal/operation/operation.go b/galvanize-instancer/internal/operation/operation.go new file mode 100644 index 0000000..26be4c7 --- /dev/null +++ b/galvanize-instancer/internal/operation/operation.go @@ -0,0 +1,286 @@ +// Package operation runs long admin operations (git clones, image builds) +// in the background and keeps their log, so that API clients can start one +// and follow it. +// +// Only one operation runs at a time: they all work on challenge_dir and on +// the Ansible hosts, and two clones, or a pull and a build of the same +// repository, must not interleave. Operations live in memory; the most +// recent ones are kept after they finish. +package operation + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + "go.uber.org/zap" +) + +// Status of an operation. +const ( + StatusRunning = "running" + StatusSuccess = "success" + StatusWarning = "warning" // finished, but some items failed + StatusFailed = "failed" + // StatusCancelled: stopped by Cancel (or Shutdown) before it finished + StatusCancelled = "cancelled" +) + +// Log levels. +const ( + LevelDebug = "debug" + LevelInfo = "info" + LevelSuccess = "success" + LevelWarning = "warning" + LevelError = "error" +) + +const ( + maxKept = 50 + maxLogLines = 20000 +) + +// ErrBusy is returned by Start while another operation runs. +var ErrBusy = errors.New("another operation is running") + +// Line is one log line. +type Line struct { + Time time.Time `json:"time"` + Level string `json:"level"` + Message string `json:"message"` +} + +// Operation is a background task and its log. +type Operation struct { + mu sync.Mutex + ID string + Kind string + Target string + Status string + CreatedAt time.Time + FinishedAt *time.Time + Result map[string]interface{} + lines []Line + truncated bool + cancel context.CancelFunc +} + +// Logger writes to an operation's log (also what the repository and build +// code log to). +type Logger interface { + Debugf(format string, args ...interface{}) + Infof(format string, args ...interface{}) + Successf(format string, args ...interface{}) + Warnf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) +} + +// Snapshot is a copy of an operation's state, safe to serialise. +type Snapshot struct { + ID string + Kind string + Target string + Status string + CreatedAt time.Time + FinishedAt *time.Time + Result map[string]interface{} + Lines []Line // from the requested offset + LineCount int // total number of lines +} + +func (o *Operation) add(level, format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + o.mu.Lock() + defer o.mu.Unlock() + for _, part := range strings.Split(msg, "\n") { + if len(o.lines) >= maxLogLines { + if !o.truncated { + o.truncated = true + o.lines = append(o.lines, Line{Time: time.Now(), Level: LevelWarning, Message: "Log truncated"}) + } + return + } + o.lines = append(o.lines, Line{Time: time.Now(), Level: level, Message: part}) + } +} + +func (o *Operation) Debugf(f string, a ...interface{}) { o.add(LevelDebug, f, a...) } +func (o *Operation) Infof(f string, a ...interface{}) { o.add(LevelInfo, f, a...) } +func (o *Operation) Successf(f string, a ...interface{}) { o.add(LevelSuccess, f, a...) } +func (o *Operation) Warnf(f string, a ...interface{}) { o.add(LevelWarning, f, a...) } +func (o *Operation) Errorf(f string, a ...interface{}) { o.add(LevelError, f, a...) } + +// Errors counts the error lines written so far. +func (o *Operation) Errors() int { + o.mu.Lock() + defer o.mu.Unlock() + n := 0 + for _, l := range o.lines { + if l.Level == LevelError { + n++ + } + } + return n +} + +// Snapshot copies the operation, with the log lines from offset on. +func (o *Operation) Snapshot(offset int) Snapshot { + o.mu.Lock() + defer o.mu.Unlock() + if offset < 0 || offset > len(o.lines) { + offset = len(o.lines) + } + return Snapshot{ + ID: o.ID, Kind: o.Kind, Target: o.Target, Status: o.Status, + CreatedAt: o.CreatedAt, FinishedAt: o.FinishedAt, Result: o.Result, + Lines: append([]Line(nil), o.lines[offset:]...), LineCount: len(o.lines), + } +} + +// Func is an operation body. The returned result is attached to the +// operation; a non-nil error fails it, error lines in the log make it a +// warning. +type Func func(ctx context.Context, log Logger) (map[string]interface{}, error) + +// Manager starts and keeps operations. +type Manager struct { + mu sync.Mutex + ops []*Operation // oldest first + running *Operation + seq int + wg sync.WaitGroup +} + +func NewManager() *Manager { return &Manager{} } + +// Start runs fn in the background, unless an operation is already running. +func (m *Manager) Start(kind, target string, fn Func) (*Operation, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.running != nil { + return m.running, ErrBusy + } + m.seq++ + ctx, cancel := context.WithCancel(context.Background()) + op := &Operation{ + ID: fmt.Sprintf("%d-%d", time.Now().Unix(), m.seq), + Kind: kind, + Target: target, + Status: StatusRunning, + CreatedAt: time.Now(), + cancel: cancel, + } + m.ops = append(m.ops, op) + if len(m.ops) > maxKept { + m.ops = m.ops[len(m.ops)-maxKept:] + } + m.running = op + m.wg.Add(1) + go m.run(ctx, op, fn) + return op, nil +} + +func (m *Manager) run(ctx context.Context, op *Operation, fn Func) { + defer m.wg.Done() + defer op.cancel() + result, err := safeCall(ctx, op, fn) + status := StatusSuccess + switch { + case errors.Is(ctx.Err(), context.Canceled): + if err != nil { + op.Errorf("%v", err) + } + op.Warnf("Cancelled") + status = StatusCancelled + case err != nil: + op.Errorf("%v", err) + status = StatusFailed + case op.Errors() > 0: + status = StatusWarning + } + // Finished and no longer running at once: a client that saw it finish + // got "another operation is running" when it started the next one + now := time.Now() + m.mu.Lock() + op.mu.Lock() + op.Status, op.FinishedAt, op.Result = status, &now, result + op.mu.Unlock() + if m.running == op { + m.running = nil + } + m.mu.Unlock() + zap.S().Infof("Operation %s (%s %s) finished: %s", op.ID, op.Kind, op.Target, status) +} + +func safeCall(ctx context.Context, op *Operation, fn Func) (result map[string]interface{}, err error) { + defer func() { + if r := recover(); r != nil { + zap.S().Errorf("Operation %s panicked: %v", op.ID, r) + err = fmt.Errorf("internal error: %v", r) + } + }() + return fn(ctx, op) +} + +// Get returns an operation by ID. +func (m *Manager) Get(id string) (*Operation, bool) { + m.mu.Lock() + defer m.mu.Unlock() + for _, op := range m.ops { + if op.ID == id { + return op, true + } + } + return nil, false +} + +// List returns the kept operations, the most recent first. +func (m *Manager) List() []*Operation { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]*Operation, 0, len(m.ops)) + for i := len(m.ops) - 1; i >= 0; i-- { + out = append(out, m.ops[i]) + } + return out +} + +// Cancel asks a running operation to stop (its context is cancelled). +// found is false for an unknown operation, running false for one that +// already finished (nothing is done). +func (m *Manager) Cancel(id string) (found, running bool) { + op, ok := m.Get(id) + if !ok { + return false, false + } + op.mu.Lock() + running = op.Status == StatusRunning + op.mu.Unlock() + if running { + op.cancel() + } + return true, running +} + +// Shutdown cancels the running operation and waits for it, or for ctx. +func (m *Manager) Shutdown(ctx context.Context) error { + m.mu.Lock() + if m.running != nil { + m.running.cancel() + } + m.mu.Unlock() + done := make(chan struct{}) + go func() { + m.wg.Wait() + close(done) + }() + select { + case <-done: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} diff --git a/galvanize-instancer/internal/operation/operation_test.go b/galvanize-instancer/internal/operation/operation_test.go new file mode 100644 index 0000000..6b8f7b6 --- /dev/null +++ b/galvanize-instancer/internal/operation/operation_test.go @@ -0,0 +1,151 @@ +package operation + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func waitDone(t *testing.T, op *Operation) Snapshot { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if snap := op.Snapshot(0); snap.Status != StatusRunning { + return snap + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("operation did not finish") + return Snapshot{} +} + +func TestStart_SuccessKeepsLogAndResult(t *testing.T) { + m := NewManager() + op, err := m.Start("build", "repo", func(ctx context.Context, log Logger) (map[string]interface{}, error) { + log.Infof("one %d", 1) + log.Successf("two\nthree") + return map[string]interface{}{"built": 2}, nil + }) + require.NoError(t, err) + snap := waitDone(t, op) + + assert.Equal(t, StatusSuccess, snap.Status) + assert.Equal(t, 2, snap.Result["built"]) + require.Len(t, snap.Lines, 3, "multi-line messages are split") + assert.Equal(t, "one 1", snap.Lines[0].Message) + assert.Equal(t, LevelSuccess, snap.Lines[2].Level) + assert.NotNil(t, snap.FinishedAt) +} + +func TestStart_ErrorLinesMakeAWarning(t *testing.T) { + m := NewManager() + op, _ := m.Start("build", "x", func(ctx context.Context, log Logger) (map[string]interface{}, error) { + log.Errorf("one build failed") + return nil, nil + }) + assert.Equal(t, StatusWarning, waitDone(t, op).Status) +} + +func TestStart_ReturnedErrorFails(t *testing.T) { + m := NewManager() + op, _ := m.Start("clone", "x", func(ctx context.Context, log Logger) (map[string]interface{}, error) { + return nil, errors.New("git clone failed") + }) + snap := waitDone(t, op) + assert.Equal(t, StatusFailed, snap.Status) + assert.Equal(t, "git clone failed", snap.Lines[len(snap.Lines)-1].Message) +} + +func TestStart_PanicFailsTheOperationOnly(t *testing.T) { + m := NewManager() + op, _ := m.Start("clone", "x", func(ctx context.Context, log Logger) (map[string]interface{}, error) { + panic("boom") + }) + assert.Equal(t, StatusFailed, waitDone(t, op).Status) + // The manager is free again + op2, err := m.Start("clone", "y", func(ctx context.Context, log Logger) (map[string]interface{}, error) { return nil, nil }) + require.NoError(t, err) + waitDone(t, op2) +} + +func TestStart_OneAtATime(t *testing.T) { + m := NewManager() + release := make(chan struct{}) + first, err := m.Start("build", "a", func(ctx context.Context, log Logger) (map[string]interface{}, error) { + <-release + return nil, nil + }) + require.NoError(t, err) + + running, err := m.Start("pull", "b", func(ctx context.Context, log Logger) (map[string]interface{}, error) { return nil, nil }) + assert.ErrorIs(t, err, ErrBusy) + assert.Equal(t, first.ID, running.ID, "the running operation is returned") + + close(release) + waitDone(t, first) + _, err = m.Start("pull", "b", func(ctx context.Context, log Logger) (map[string]interface{}, error) { return nil, nil }) + assert.NoError(t, err) +} + +func TestSnapshot_Offset(t *testing.T) { + m := NewManager() + op, _ := m.Start("build", "x", func(ctx context.Context, log Logger) (map[string]interface{}, error) { + for i := 0; i < 5; i++ { + log.Infof("line %d", i) + } + return nil, nil + }) + waitDone(t, op) + snap := op.Snapshot(3) + assert.Equal(t, 5, snap.LineCount) + require.Len(t, snap.Lines, 2) + assert.Equal(t, "line 3", snap.Lines[0].Message) + assert.Empty(t, op.Snapshot(-1).Lines, "a negative offset returns no lines") + assert.Empty(t, op.Snapshot(99).Lines) +} + +func TestCancel_CancelsTheContext(t *testing.T) { + m := NewManager() + op, _ := m.Start("build", "x", func(ctx context.Context, log Logger) (map[string]interface{}, error) { + <-ctx.Done() + return nil, ctx.Err() + }) + found, running := m.Cancel(op.ID) + assert.True(t, found) + assert.True(t, running) + assert.Equal(t, StatusCancelled, waitDone(t, op).Status) + found, _ = m.Cancel("nope") + assert.False(t, found) + // A finished operation is left as it is + found, running = m.Cancel(op.ID) + assert.True(t, found) + assert.False(t, running) + + // Cancelled even when the body ignores the error it got + op, _ = m.Start("build", "y", func(ctx context.Context, log Logger) (map[string]interface{}, error) { + <-ctx.Done() + return map[string]interface{}{"built": []string{}}, nil + }) + m.Cancel(op.ID) + assert.Equal(t, StatusCancelled, waitDone(t, op).Status) +} + +func TestList_MostRecentFirstAndBounded(t *testing.T) { + m := NewManager() + var last *Operation + for i := 0; i < maxKept+5; i++ { + op, err := m.Start("build", "x", func(ctx context.Context, log Logger) (map[string]interface{}, error) { return nil, nil }) + require.NoError(t, err) + waitDone(t, op) + last = op + } + list := m.List() + assert.Len(t, list, maxKept) + assert.Equal(t, last.ID, list[0].ID) + _, found := m.Get(last.ID) + assert.True(t, found) +} diff --git a/galvanize-instancer/internal/pathutil/pathutil.go b/galvanize-instancer/internal/pathutil/pathutil.go new file mode 100644 index 0000000..7f46f1e --- /dev/null +++ b/galvanize-instancer/internal/pathutil/pathutil.go @@ -0,0 +1,38 @@ +// Package pathutil checks that paths stay inside a folder. +package pathutil + +import ( + "errors" + "path/filepath" + "strings" +) + +// ErrOutside is returned by Resolve for a path leading outside its folder. +var ErrOutside = errors.New("leads outside the folder") + +// Inside reports whether path is dir or below it, lexically: ".." segments +// count, symlinks do not (see Resolve). Both must be absolute, or both +// relative. +func Inside(dir, path string) bool { + rel, err := filepath.Rel(dir, path) + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +// Resolve returns path with its symlinks resolved, when it stays inside dir +// (whose symlinks are resolved too). It fails with ErrOutside when it leads +// outside, or with the error of filepath.EvalSymlinks (fs.ErrNotExist for a +// missing path). +func Resolve(dir, path string) (string, error) { + realDir, err := filepath.EvalSymlinks(dir) + if err != nil { + return "", err + } + real, err := filepath.EvalSymlinks(path) + if err != nil { + return "", err + } + if !Inside(realDir, real) { + return "", ErrOutside + } + return real, nil +} diff --git a/galvanize-instancer/internal/pathutil/pathutil_test.go b/galvanize-instancer/internal/pathutil/pathutil_test.go new file mode 100644 index 0000000..0d4ad35 --- /dev/null +++ b/galvanize-instancer/internal/pathutil/pathutil_test.go @@ -0,0 +1,40 @@ +package pathutil + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestInside(t *testing.T) { + assert.True(t, Inside("/a/b", "/a/b")) + assert.True(t, Inside("/a/b", "/a/b/c/../d")) + assert.True(t, Inside("/a/b", "/a/b/..foo"), "a name starting with .. is inside") + assert.False(t, Inside("/a/b", "/a/b/../c")) + assert.False(t, Inside("/a/b", "/a")) + assert.False(t, Inside("/a/b", "/a/bc")) + assert.False(t, Inside("/a/b", "b"), "absolute and relative") +} + +func TestResolve(t *testing.T) { + root := t.TempDir() + dir := filepath.Join(root, "dir") + require.NoError(t, os.MkdirAll(filepath.Join(dir, "sub"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "sub", "f"), []byte("x"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(root, "secret"), []byte("x"), 0o644)) + require.NoError(t, os.Symlink("sub/f", filepath.Join(dir, "in"))) + require.NoError(t, os.Symlink("../secret", filepath.Join(dir, "out"))) + + real, err := Resolve(dir, filepath.Join(dir, "in")) + require.NoError(t, err) + assert.Equal(t, "f", filepath.Base(real)) + _, err = Resolve(dir, filepath.Join(dir, "out")) + assert.ErrorIs(t, err, ErrOutside) + _, err = Resolve(dir, filepath.Join(dir, "missing")) + assert.True(t, errors.Is(err, fs.ErrNotExist)) +} diff --git a/galvanize-instancer/internal/repo/repo.go b/galvanize-instancer/internal/repo/repo.go new file mode 100644 index 0000000..d1a5266 --- /dev/null +++ b/galvanize-instancer/internal/repo/repo.go @@ -0,0 +1,462 @@ +// Package repo manages the challenge repositories kept in challenge_dir: +// each top-level folder of challenge_dir is a repository (a git clone, or a +// plain folder copied there by hand). +// +// Clones are only allowed from the URL prefixes listed in the configuration +// (repositories.sources). Credentials of a source are given to git through +// its environment for the duration of one command: they never appear in a +// URL, a command line or the clone's .git/config. +package repo + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "net/url" + "os" + "os/exec" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "time" + + "github.com/28Pollux28/galvanize/internal/operation" + "github.com/28Pollux28/galvanize/internal/pathutil" + "github.com/28Pollux28/galvanize/pkg/config" +) + +// tmpDirName holds clones in progress, inside challenge_dir so that the +// final rename stays on one filesystem. The challenge index skips hidden +// folders. +const tmpDirName = ".galvanize-tmp" + +// refConfigKey records, in the clone's git config, the branch or tag it was +// cloned from, so that Pull follows the same ref. +const refConfigKey = "galvanize.ref" + +var ( + nameRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$`) + refRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$`) + + ErrNotFound = errors.New("repository not found") + ErrExists = errors.New("repository already exists") + ErrNotAllowed = errors.New("URL not allowed") + ErrCloneDisabled = errors.New("cloning is disabled: no repositories.sources configured") +) + +// Info describes a repository. +type Info struct { + Name string + IsGit bool + Remote string // without credentials + Branch string // empty when HEAD is detached + Ref string // branch or tag followed by Pull + Commit string + CommitMessage string + CommitTime *time.Time + Dirty bool + Error string +} + +// Manager works on the repositories of one challenge_dir. +type Manager struct { + BaseDir string + Config config.RepositoriesConfig + // Git is the git executable (default "git"). + Git string +} + +func (m *Manager) git() string { + if m.Git != "" { + return m.Git + } + return "git" +} + +// ValidName reports whether name can be a repository folder. +func ValidName(name string) bool { return nameRe.MatchString(name) && !strings.Contains(name, "..") } + +// Path returns the folder of an existing repository. +func (m *Manager) Path(name string) (string, error) { + if !ValidName(name) { + return "", fmt.Errorf("invalid repository name %q", name) + } + p := filepath.Join(m.BaseDir, name) + st, err := os.Stat(p) + if err != nil || !st.IsDir() { + return "", ErrNotFound + } + return p, nil +} + +// RepoOf returns the repository holding path (a path inside BaseDir), or "" +// when path is not inside a repository folder. +func (m *Manager) RepoOf(path string) string { + base, err1 := filepath.Abs(m.BaseDir) + abs, err2 := filepath.Abs(path) + if err1 != nil || err2 != nil { + return "" + } + rel, err := filepath.Rel(base, abs) + if err != nil || rel == "." || !pathutil.Inside(base, abs) { + return "" + } + first := strings.SplitN(filepath.ToSlash(rel), "/", 2)[0] + if !ValidName(first) { + return "" + } + return first +} + +// List returns every repository, sorted by name. +func (m *Manager) List(ctx context.Context) ([]Info, error) { + entries, err := os.ReadDir(m.BaseDir) + if err != nil { + return nil, err + } + var out []Info + for _, e := range entries { + if !e.IsDir() || !ValidName(e.Name()) { + continue + } + out = append(out, m.Describe(ctx, e.Name())) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +// Describe returns the git state of a repository folder. +func (m *Manager) Describe(ctx context.Context, name string) Info { + info := Info{Name: name} + dir := filepath.Join(m.BaseDir, name) + if _, err := os.Stat(filepath.Join(dir, ".git")); err != nil { + return info + } + info.IsGit = true + if out, err := m.run(ctx, dir, nil, "remote", "get-url", "origin"); err == nil { + info.Remote = MaskURL(strings.TrimSpace(out)) + } + if out, err := m.run(ctx, dir, nil, "symbolic-ref", "--quiet", "--short", "HEAD"); err == nil { + info.Branch = strings.TrimSpace(out) + } + if out, err := m.run(ctx, dir, nil, "config", "--get", refConfigKey); err == nil { + info.Ref = strings.TrimSpace(out) + } else { + info.Ref = info.Branch + } + out, err := m.run(ctx, dir, nil, "log", "-1", "--format=%h%x00%ct%x00%s") + if err != nil { + info.Error = firstLine(err.Error()) + return info + } + parts := strings.SplitN(strings.TrimSpace(out), "\x00", 3) + if len(parts) == 3 { + info.Commit = parts[0] + if ts, err := strconv.ParseInt(parts[1], 10, 64); err == nil { + t := time.Unix(ts, 0).UTC() + info.CommitTime = &t + } + info.CommitMessage = parts[2] + } + if out, err := m.run(ctx, dir, nil, "status", "--porcelain", "--untracked-files=no"); err == nil { + info.Dirty = strings.TrimSpace(out) != "" + } + return info +} + +// Commit returns the HEAD commit of a repository (abbreviated, as Describe +// gives it), "" when it is not a git clone. +func (m *Manager) Commit(ctx context.Context, name string) string { + dir := filepath.Join(m.BaseDir, name) + if _, err := os.Stat(filepath.Join(dir, ".git")); err != nil { + return "" + } + out, err := m.run(ctx, dir, nil, "log", "-1", "--format=%h") + if err != nil { + return "" + } + return strings.TrimSpace(out) +} + +// source returns the configured source allowing rawURL (see +// config.RepositorySource.Allows: scheme, host, port and path folders are +// compared, never the raw string). +func (m *Manager) source(rawURL string) (*config.RepositorySource, error) { + if len(m.Config.Sources) == 0 { + return nil, ErrCloneDisabled + } + if err := config.CheckRepositoryURL(rawURL); err != nil { + return nil, fmt.Errorf("%w: %v", ErrNotAllowed, err) + } + if src := m.Config.SourceFor(rawURL); src != nil { + return src, nil + } + return nil, fmt.Errorf("%w: %s is not inside an allowed source", ErrNotAllowed, rawURL) +} + +// NameFromURL derives a folder name from a repository URL. +func NameFromURL(rawURL string) string { + name := strings.TrimSuffix(strings.TrimRight(rawURL, "/"), ".git") + if i := strings.LastIndexAny(name, "/:"); i >= 0 { + name = name[i+1:] + } + return name +} + +// Clone clones rawURL into BaseDir/name (name defaults from the URL). With +// force, an existing folder of that name is replaced once the new clone has +// succeeded. +func (m *Manager) Clone(ctx context.Context, rawURL, name, ref string, force bool, log operation.Logger) (string, error) { + src, err := m.source(rawURL) + if err != nil { + return "", err + } + if name == "" { + name = NameFromURL(rawURL) + } + if !ValidName(name) { + return "", fmt.Errorf("invalid repository name %q", name) + } + if ref != "" && !refRe.MatchString(ref) { + return "", fmt.Errorf("invalid branch or tag %q", ref) + } + // Absolute paths: git runs in another folder than Galvanize, and + // challenge_dir is usually relative (./data/challenges) + base, err := filepath.Abs(m.BaseDir) + if err != nil { + return "", err + } + dest := filepath.Join(base, name) + if _, err := os.Stat(dest); err == nil && !force { + return "", fmt.Errorf("%w: %s (use force to replace it)", ErrExists, name) + } + + tmpRoot := filepath.Join(base, tmpDirName) + if err := os.MkdirAll(tmpRoot, 0o755); err != nil { + return "", err + } + tmp, err := os.MkdirTemp(tmpRoot, name+"-") + if err != nil { + return "", err + } + defer func() { _ = os.RemoveAll(tmp) }() + clone := filepath.Join(tmp, "clone") + + args := []string{"clone", "--quiet"} + if ref != "" { + args = append(args, "--branch", ref) + } + args = append(args, "--", rawURL, clone) + if ref != "" { + log.Infof("Cloning %s (%s) into %s", rawURL, ref, name) + } else { + log.Infof("Cloning %s into %s", rawURL, name) + } + if _, err := m.run(ctx, base, src, args...); err != nil { + return "", fmt.Errorf("git clone failed: %s", firstLine(err.Error())) + } + if ref != "" { + if _, err := m.run(ctx, clone, nil, "config", refConfigKey, ref); err != nil { + return "", err + } + } + + if _, err := os.Stat(dest); err == nil { + old := filepath.Join(tmp, "previous") + if err := os.Rename(dest, old); err != nil { + return "", fmt.Errorf("cannot replace %s: %w", name, err) + } + log.Infof("Replacing the previous %s", name) + } + if err := os.Rename(clone, dest); err != nil { + return "", fmt.Errorf("cannot move the clone into place: %w", err) + } + m.warnLFS(dest, log) + return name, nil +} + +// warnLFS warns when the repository stores files with Git LFS but git-lfs is +// not installed: the folder then holds small pointer files instead of them. +func (m *Manager) warnLFS(dir string, log operation.Logger) { + if _, err := exec.LookPath("git-lfs"); err == nil { + return + } + found := "" + _ = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { + if err != nil || found != "" { + return filepath.SkipDir + } + if d.IsDir() && d.Name() == ".git" { + return filepath.SkipDir + } + if !d.IsDir() && d.Name() == ".gitattributes" { + if data, err := os.ReadFile(path); err == nil && strings.Contains(string(data), "filter=lfs") { + found = path + } + } + return nil + }) + if found != "" { + rel, _ := filepath.Rel(dir, found) + log.Warnf("The repository uses Git LFS (%s) but git-lfs is not installed: LFS files are pointers, not their content", rel) + } +} + +// Pull fetches the ref the repository follows and hard-resets to it: the +// folder becomes an exact copy of the remote (local changes to tracked files +// are discarded). Returns the commit before and after. +func (m *Manager) Pull(ctx context.Context, name string, log operation.Logger) (string, string, error) { + dir, err := m.Path(name) + if err != nil { + return "", "", err + } + info := m.Describe(ctx, name) + if !info.IsGit { + return "", "", fmt.Errorf("%s is not a git repository", name) + } + if info.Ref == "" { + return "", "", fmt.Errorf("%s: HEAD is detached and no branch or tag is recorded", name) + } + remote, err := m.run(ctx, dir, nil, "remote", "get-url", "origin") + if err != nil { + return "", "", fmt.Errorf("%s has no origin remote", name) + } + src, err := m.source(strings.TrimSpace(remote)) + if err != nil { + return "", "", err + } + log.Infof("Fetching %s from %s", info.Ref, info.Remote) + if _, err := m.run(ctx, dir, src, "fetch", "--quiet", "--force", "--tags", "origin", info.Ref); err != nil { + return "", "", fmt.Errorf("git fetch failed: %s", firstLine(err.Error())) + } + changed, _ := m.run(ctx, dir, nil, "status", "--porcelain", "-z", "--untracked-files=no") + if _, err := m.run(ctx, dir, nil, "reset", "--quiet", "--hard", "FETCH_HEAD"); err != nil { + return "", "", fmt.Errorf("git reset failed: %s", firstLine(err.Error())) + } + if files := changedFiles(changed); len(files) > 0 { + shown := files + if len(shown) > maxListedChanges { + shown = append(shown[:maxListedChanges:maxListedChanges], fmt.Sprintf("and %d more", len(files)-maxListedChanges)) + } + log.Warnf("Discarded local changes to %d tracked file(s) of %s: %s", len(files), name, strings.Join(shown, ", ")) + } + after := m.Describe(ctx, name).Commit + m.warnLFS(dir, log) + return info.Commit, after, nil +} + +// maxListedChanges is how many discarded files Pull names. +const maxListedChanges = 10 + +// changedFiles reads the paths of git status --porcelain -z (unquoted; +// a rename or copy is followed by its origin, which is skipped). +func changedFiles(porcelain string) []string { + var out []string + entries := strings.Split(porcelain, "\x00") + for i := 0; i < len(entries); i++ { + e := entries[i] + if len(e) <= 3 { + continue + } + out = append(out, e[3:]) + if e[0] == 'R' || e[0] == 'C' { + i++ + } + } + return out +} + +// Remove deletes a repository folder. +func (m *Manager) Remove(name string) error { + dir, err := m.Path(name) + if err != nil { + return err + } + return os.RemoveAll(dir) +} + +// run runs git in dir. src, when set, provides the credentials. +func (m *Manager) run(ctx context.Context, dir string, src *config.RepositorySource, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(ctx, m.Config.GitTimeoutOrDefault()) + defer cancel() + cmd := exec.CommandContext(ctx, m.git(), args...) + // A killed git can leave children (git-remote-https, git-lfs) holding + // the output pipes: do not wait for them forever + cmd.WaitDelay = 10 * time.Second + cmd.Dir = dir + env := append(os.Environ(), + "GIT_TERMINAL_PROMPT=0", + "GIT_ASKPASS=/bin/false", + ) + // Configuration through the environment (git 2.31+): nothing is written + // to disk and nothing shows in the process list. safe.directory: the + // folders may belong to another user (copied by hand, or by setup tools). + // The other settings keep a repository's content from running anything + // in Galvanize (hooks, fsmonitor) and git from using transports that run + // commands or read local paths given by a URL. + gitConf := [][2]string{ + {"safe.directory", "*"}, + {"core.hooksPath", os.DevNull}, + {"core.fsmonitor", "false"}, + {"protocol.ext.allow", "never"}, + } + if src != nil && src.Token != "" { + user := src.Username + if user == "" { + user = "x-access-token" + } + basic := base64.StdEncoding.EncodeToString([]byte(user + ":" + src.Token)) + // Scoped to the source: git (and git-lfs) send the header only to + // URLs below url_prefix, not to an LFS server a repository's + // .lfsconfig names. No redirects: git would send the header to the + // redirected host for the rest of the command. + gitConf = append(gitConf, + [2]string{"http." + src.URLPrefix + ".extraHeader", "Authorization: Basic " + basic}, + [2]string{"http.followRedirects", "false"}, + ) + } + env = append(env, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(gitConf))) + for i, kv := range gitConf { + env = append(env, fmt.Sprintf("GIT_CONFIG_KEY_%d=%s", i, kv[0]), fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, kv[1])) + } + cmd.Env = env + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + if err := cmd.Run(); err != nil { + msg := strings.TrimSpace(stderr.String()) + if ctx.Err() == context.DeadlineExceeded { + msg = "timed out" + } else if strings.Contains(msg, "could not read Username") || strings.Contains(msg, "could not read Password") { + // Prompts are disabled: git's first line would be "unable to + // read askpass response from '/bin/false'" + msg = "the server asked for credentials: the repository does not exist, or it is private and its source in repositories.sources has no token able to read it" + } + if msg == "" { + msg = err.Error() + } + return "", errors.New(msg) + } + return stdout.String(), nil +} + +// MaskURL removes credentials from a URL. +func MaskURL(raw string) string { + u, err := url.Parse(raw) + if err != nil || u.User == nil { + return raw + } + u.User = nil + return u.String() +} + +func firstLine(s string) string { + s = strings.TrimSpace(s) + if i := strings.IndexByte(s, '\n'); i >= 0 { + return s[:i] + } + return s +} diff --git a/galvanize-instancer/internal/repo/repo_test.go b/galvanize-instancer/internal/repo/repo_test.go new file mode 100644 index 0000000..d57752c --- /dev/null +++ b/galvanize-instancer/internal/repo/repo_test.go @@ -0,0 +1,316 @@ +package repo + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type nopLog struct{} + +func (nopLog) Infof(string, ...interface{}) {} +func (nopLog) Debugf(string, ...interface{}) {} +func (nopLog) Successf(string, ...interface{}) {} +func (nopLog) Warnf(string, ...interface{}) {} +func (nopLog) Errorf(string, ...interface{}) {} + +type warnLog struct { + nopLog + warnings []string +} + +func (w *warnLog) Warnf(f string, a ...interface{}) { + w.warnings = append(w.warnings, fmt.Sprintf(f, a...)) +} + +func git(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t") + out, err := cmd.CombinedOutput() + require.NoError(t, err, string(out)) + return strings.TrimSpace(string(out)) +} + +// newRemote creates a bare repository with one commit on main (file +// challenge.yml) and a tag v1, and returns its file:// URL and a work tree to +// push more commits from. +func newRemote(t *testing.T) (string, string) { + t.Helper() + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not installed") + } + root := t.TempDir() + bare := filepath.Join(root, "remote.git") + work := filepath.Join(root, "work") + git(t, root, "init", "--quiet", "--bare", "-b", "main", bare) + git(t, root, "clone", "--quiet", bare, work) + require.NoError(t, os.WriteFile(filepath.Join(work, "challenge.yml"), []byte("v1\n"), 0o644)) + git(t, work, "add", ".") + git(t, work, "commit", "--quiet", "-m", "first") + git(t, work, "tag", "v1") + git(t, work, "push", "--quiet", "origin", "main", "--tags") + return "file://" + bare, work +} + +func push(t *testing.T, work, content, msg string) { + t.Helper() + require.NoError(t, os.WriteFile(filepath.Join(work, "challenge.yml"), []byte(content), 0o644)) + git(t, work, "commit", "--quiet", "-am", msg) + git(t, work, "push", "--quiet", "origin", "main") +} + +func manager(t *testing.T, prefix string) *Manager { + return &Manager{BaseDir: t.TempDir(), Config: config.RepositoriesConfig{ + Sources: []config.RepositorySource{{URLPrefix: prefix}}, + }} +} + +func TestClone_AndDescribe(t *testing.T) { + url, _ := newRemote(t) + m := manager(t, "file://") + name, err := m.Clone(context.Background(), url, "", "", false, nopLog{}) + require.NoError(t, err) + assert.Equal(t, "remote", name, "name derived from the URL") + + info := m.Describe(context.Background(), name) + assert.True(t, info.IsGit) + assert.Equal(t, "main", info.Branch) + assert.Equal(t, "main", info.Ref) + assert.Equal(t, "first", info.CommitMessage) + assert.False(t, info.Dirty) + assert.NoDirExists(t, filepath.Join(m.BaseDir, tmpDirName, name), "temporary clone removed") + + list, err := m.List(context.Background()) + require.NoError(t, err) + require.Len(t, list, 1, "the hidden temporary folder is not a repository") + assert.Equal(t, "remote", list[0].Name) +} + +func TestClone_Refusals(t *testing.T) { + url, _ := newRemote(t) + ctx := context.Background() + + disabled := &Manager{BaseDir: t.TempDir()} + _, err := disabled.Clone(ctx, url, "x", "", false, nopLog{}) + assert.ErrorIs(t, err, ErrCloneDisabled) + + m := manager(t, "https://github.com/org/") + _, err = m.Clone(ctx, url, "x", "", false, nopLog{}) + assert.ErrorIs(t, err, ErrNotAllowed, "URL outside the allowed sources") + + _, err = m.Clone(ctx, "https://user:token@github.com/org/repo.git", "x", "", false, nopLog{}) + assert.ErrorIs(t, err, ErrNotAllowed, "credentials in the URL") + + m = manager(t, "file://") + for _, bad := range []string{"../evil", ".hidden", "a/b", "", "x..y"} { + if bad == "" { + continue + } + _, err = m.Clone(ctx, url, bad, "", false, nopLog{}) + assert.Error(t, err, "name %q", bad) + } + _, err = m.Clone(ctx, url, "ok", "--upload-pack=evil", false, nopLog{}) + assert.Error(t, err, "option-like ref refused") +} + +func TestClone_ExistingNeedsForceAndForceReplaces(t *testing.T) { + url, work := newRemote(t) + m := manager(t, "file://") + ctx := context.Background() + _, err := m.Clone(ctx, url, "chals", "", false, nopLog{}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(m.BaseDir, "chals", "local.txt"), []byte("x"), 0o644)) + + _, err = m.Clone(ctx, url, "chals", "", false, nopLog{}) + assert.ErrorIs(t, err, ErrExists) + + push(t, work, "v2\n", "second") + _, err = m.Clone(ctx, url, "chals", "", true, nopLog{}) + require.NoError(t, err) + assert.Equal(t, "second", m.Describe(ctx, "chals").CommitMessage) + assert.NoFileExists(t, filepath.Join(m.BaseDir, "chals", "local.txt"), "folder replaced") +} + +func TestClone_FailedForceKeepsTheOldFolder(t *testing.T) { + url, _ := newRemote(t) + m := manager(t, "file://") + ctx := context.Background() + _, err := m.Clone(ctx, url, "chals", "", false, nopLog{}) + require.NoError(t, err) + + _, err = m.Clone(ctx, url+"-missing", "chals", "", true, nopLog{}) + require.Error(t, err) + assert.FileExists(t, filepath.Join(m.BaseDir, "chals", "challenge.yml"), "the previous clone is kept") +} + +func TestPull_FollowsBranchAndDiscardsLocalChanges(t *testing.T) { + url, work := newRemote(t) + m := manager(t, "file://") + ctx := context.Background() + _, err := m.Clone(ctx, url, "chals", "", false, nopLog{}) + require.NoError(t, err) + file := filepath.Join(m.BaseDir, "chals", "challenge.yml") + require.NoError(t, os.WriteFile(file, []byte("local edit\n"), 0o644)) + assert.True(t, m.Describe(ctx, "chals").Dirty) + + push(t, work, "v2\n", "second") + log := &warnLog{} + before, after, err := m.Pull(ctx, "chals", log) + require.NoError(t, err) + assert.NotEqual(t, before, after) + data, _ := os.ReadFile(file) + assert.Equal(t, "v2\n", string(data)) + assert.False(t, m.Describe(ctx, "chals").Dirty) + require.Len(t, log.warnings, 1) + assert.Equal(t, "Discarded local changes to 1 tracked file(s) of chals: challenge.yml", log.warnings[0]) + + // Regression: with no new commit, local changes were discarded and the + // pull only said the repository was up to date + require.NoError(t, os.WriteFile(file, []byte("local edit\n"), 0o644)) + log = &warnLog{} + before, after, err = m.Pull(ctx, "chals", log) + require.NoError(t, err) + assert.Equal(t, before, after) + require.Len(t, log.warnings, 1) + assert.Contains(t, log.warnings[0], "Discarded local changes") + data, _ = os.ReadFile(file) + assert.Equal(t, "v2\n", string(data)) + + log = &warnLog{} + _, _, err = m.Pull(ctx, "chals", log) + require.NoError(t, err) + assert.Empty(t, log.warnings, "nothing discarded") +} + +func TestChangedFiles(t *testing.T) { + assert.Equal(t, []string{"a.yml", "dir/l'été.md", "new"}, changedFiles(" M a.yml\x00M dir/l'été.md\x00R new\x00old\x00")) + assert.Empty(t, changedFiles("")) +} + +func TestRun_CredentialPromptMessage(t *testing.T) { + // Regression: a missing (or private) GitHub repository failed with + // "unable to read askpass response from '/bin/false'" + fake := filepath.Join(t.TempDir(), "git") + require.NoError(t, os.WriteFile(fake, []byte("#!/bin/sh\n"+ + "echo \"error: unable to read askpass response from '/bin/false'\" >&2\n"+ + "echo \"fatal: could not read Username for 'https://github.com': terminal prompts disabled\" >&2\n"+ + "exit 128\n"), 0o755)) + m := &Manager{BaseDir: t.TempDir(), Git: fake, Config: config.RepositoriesConfig{ + Sources: []config.RepositorySource{{URLPrefix: "https://github.com/org/"}}, + }} + _, err := m.Clone(context.Background(), "https://github.com/org/missing.git", "", "", false, nopLog{}) + require.Error(t, err) + assert.Contains(t, err.Error(), "the repository does not exist, or it is private") + assert.NotContains(t, err.Error(), "askpass") +} + +func TestPull_FollowsTag(t *testing.T) { + url, work := newRemote(t) + m := manager(t, "file://") + ctx := context.Background() + _, err := m.Clone(ctx, url, "chals", "v1", false, nopLog{}) + require.NoError(t, err) + info := m.Describe(ctx, "chals") + assert.Equal(t, "", info.Branch, "a tag checks out a detached HEAD") + assert.Equal(t, "v1", info.Ref) + + push(t, work, "v2\n", "second") // main moves, v1 does not + before, after, err := m.Pull(ctx, "chals", nopLog{}) + require.NoError(t, err) + assert.Equal(t, before, after, "still on v1") +} + +func TestPull_RefusesRemoteOutsideSources(t *testing.T) { + url, _ := newRemote(t) + m := manager(t, "file://") + ctx := context.Background() + _, err := m.Clone(ctx, url, "chals", "", false, nopLog{}) + require.NoError(t, err) + m.Config.Sources = []config.RepositorySource{{URLPrefix: "https://github.com/org/"}} + _, _, err = m.Pull(ctx, "chals", nopLog{}) + assert.ErrorIs(t, err, ErrNotAllowed) +} + +func TestToken_NeverWrittenToTheClone(t *testing.T) { + url, _ := newRemote(t) + m := &Manager{BaseDir: t.TempDir(), Config: config.RepositoriesConfig{ + Sources: []config.RepositorySource{{URLPrefix: "file://", Token: "s3cr3t-token"}}, + }} + _, err := m.Clone(context.Background(), url, "chals", "", false, nopLog{}) + require.NoError(t, err) + gitConfig, err := os.ReadFile(filepath.Join(m.BaseDir, "chals", ".git", "config")) + require.NoError(t, err) + assert.NotContains(t, string(gitConfig), "s3cr3t") + assert.NotContains(t, string(gitConfig), "extraHeader") +} + +func TestRemove(t *testing.T) { + m := manager(t, "file://") + require.NoError(t, os.MkdirAll(filepath.Join(m.BaseDir, "folder", "web"), 0o755)) + require.NoError(t, m.Remove("folder")) + assert.NoDirExists(t, filepath.Join(m.BaseDir, "folder")) + assert.ErrorIs(t, m.Remove("folder"), ErrNotFound) + assert.Error(t, m.Remove("..")) +} + +func TestHelpers(t *testing.T) { + assert.Equal(t, "repo", NameFromURL("https://github.com/org/repo.git")) + assert.Equal(t, "repo", NameFromURL("https://github.com/org/repo/")) + assert.Equal(t, "repo", NameFromURL("git@github.com:org/repo.git")) + assert.Equal(t, "https://github.com/org/r.git", MaskURL("https://u:tok@github.com/org/r.git")) + + m := &Manager{BaseDir: "/data/challenges"} + assert.Equal(t, "repo", m.RepoOf("/data/challenges/repo/web/a")) + assert.Equal(t, "", m.RepoOf("/data/challenges")) + assert.Equal(t, "", m.RepoOf("/elsewhere/x")) +} + +func TestClone_RelativeChallengeDir(t *testing.T) { + // challenge_dir is relative in the usual configuration (./data/challenges) + url, _ := newRemote(t) + root := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(root, "data", "challenges"), 0o755)) + t.Chdir(root) + m := &Manager{BaseDir: "./data/challenges", Config: config.RepositoriesConfig{ + Sources: []config.RepositorySource{{URLPrefix: "file://"}}, + }} + name, err := m.Clone(context.Background(), url, "chals", "", false, nopLog{}) + require.NoError(t, err) + assert.FileExists(t, filepath.Join(root, "data", "challenges", name, "challenge.yml")) + assert.NoDirExists(t, filepath.Join(root, "data", "challenges", "data"), "nothing cloned relative to the wrong folder") + assert.Equal(t, "chals", m.RepoOf("data/challenges/chals/web/x"), "relative paths of the index") + _, _, err = m.Pull(context.Background(), "chals", nopLog{}) + assert.NoError(t, err) +} + +func TestClone_WarnsAboutLFSWithoutGitLFS(t *testing.T) { + url, work := newRemote(t) + require.NoError(t, os.MkdirAll(filepath.Join(work, "forensic"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(work, "forensic", ".gitattributes"), []byte("dump.raw filter=lfs diff=lfs merge=lfs -text\n"), 0o644)) + git(t, work, "add", ".") + git(t, work, "commit", "--quiet", "-m", "lfs") + git(t, work, "push", "--quiet", "origin", "main") + // Hide git-lfs if the machine has it: only git stays on PATH + gitPath, err := exec.LookPath("git") + require.NoError(t, err) + bin := t.TempDir() + require.NoError(t, os.Symlink(gitPath, filepath.Join(bin, "git"))) + t.Setenv("PATH", bin) + + m := manager(t, "file://") + log := &warnLog{} + _, err = m.Clone(context.Background(), url, "chals", "", false, log) + require.NoError(t, err) + require.Len(t, log.warnings, 1) + assert.Contains(t, log.warnings[0], "git-lfs is not installed") +} diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index d506002..0f87059 100755 --- a/galvanize-instancer/pkg/api/api.gen.go +++ b/galvanize-instancer/pkg/api/api.gen.go @@ -8,6 +8,7 @@ import ( "compress/gzip" "encoding/base64" "fmt" + "net/http" "net/url" "path" "strings" @@ -15,12 +16,20 @@ import ( "github.com/getkin/kin-openapi/openapi3" "github.com/labstack/echo/v4" + "github.com/oapi-codegen/runtime" ) const ( BearerAuthScopes = "bearerAuth.Scopes" ) +// Defines values for BuildPlanKind. +const ( + Compose BuildPlanKind = "compose" + Image BuildPlanKind = "image" + None BuildPlanKind = "none" +) + // Defines values for DeploymentInfoStatus. const ( DeploymentInfoStatusRunning DeploymentInfoStatus = "running" @@ -34,6 +43,39 @@ const ( ErrorDeploymentInfoPreviousStatusStopping ErrorDeploymentInfoPreviousStatus = "stopping" ) +// Defines values for ImagesRequestAction. +const ( + ImagesRequestActionRemove ImagesRequestAction = "remove" + ImagesRequestActionStatus ImagesRequestAction = "status" +) + +// Defines values for OperationKind. +const ( + OperationKindBuild OperationKind = "build" + OperationKindClone OperationKind = "clone" + OperationKindImages OperationKind = "images" + OperationKindPull OperationKind = "pull" + OperationKindRemove OperationKind = "remove" +) + +// Defines values for OperationStatus. +const ( + OperationStatusCancelled OperationStatus = "cancelled" + OperationStatusFailed OperationStatus = "failed" + OperationStatusRunning OperationStatus = "running" + OperationStatusSuccess OperationStatus = "success" + OperationStatusWarning OperationStatus = "warning" +) + +// Defines values for OperationLineLevel. +const ( + OperationLineLevelDebug OperationLineLevel = "debug" + OperationLineLevelError OperationLineLevel = "error" + OperationLineLevelInfo OperationLineLevel = "info" + OperationLineLevelSuccess OperationLineLevel = "success" + OperationLineLevelWarning OperationLineLevel = "warning" +) + // Defines values for RetryDeploymentRequestAction. const ( Delete RetryDeploymentRequestAction = "delete" @@ -58,6 +100,30 @@ type AdminDeployRequest struct { ChallengeName string `json:"challenge_name"` } +// BuildPlan defines model for BuildPlan. +type BuildPlan struct { + // Buildable A build of this challenge builds something (it is deployable, and kind is image or compose) + Buildable bool `json:"buildable"` + Images []string `json:"images"` + Kind BuildPlanKind `json:"kind"` + + // Reason Why there is nothing to build, or why the build is refused + Reason *string `json:"reason,omitempty"` + + // Refused There is something to build, but the challenge may not build it (unsafe build section, invalid name, image used by another challenge folder or by the platform, compose file and deployment disagreeing on an image) + Refused *bool `json:"refused,omitempty"` +} + +// BuildPlanKind defines model for BuildPlan.Kind. +type BuildPlanKind string + +// BuildRequest The challenges to work on, by repository or by name (both may be given; neither means every challenge) +type BuildRequest struct { + Challenges *[]ChallengeRef `json:"challenges,omitempty"` + NoCache *bool `json:"no_cache,omitempty"` + Repo *string `json:"repo,omitempty"` +} + // BulkOperationResponse defines model for BulkOperationResponse. type BulkOperationResponse struct { Challenges []ChallengeCategoryResponse `json:"challenges"` @@ -71,6 +137,75 @@ type ChallengeCategoryResponse struct { ChallengeName string `json:"challenge_name"` } +// ChallengeDefinition defines model for ChallengeDefinition. +type ChallengeDefinition struct { + Build BuildPlan `json:"build"` + Category string `json:"category"` + + // Commit Current commit of the repository (abbreviated), when it is a git clone + Commit *string `json:"commit,omitempty"` + + // Definition The whole definition file as parsed + Definition map[string]interface{} `json:"definition"` + + // Deployable The challenge can be deployed (type zync, in the deployment index) + Deployable bool `json:"deployable"` + + // Dir Challenge folder, relative to challenge_dir + Dir string `json:"dir"` + Files []ChallengeFile `json:"files"` + Name string `json:"name"` + + // Path Definition file, relative to challenge_dir + Path string `json:"path"` + PlaybookName *string `json:"playbook_name,omitempty"` + + // Repository Repository folder, empty for a challenge directly in challenge_dir + Repository string `json:"repository"` + Type string `json:"type"` +} + +// ChallengeDefinitionList defines model for ChallengeDefinitionList. +type ChallengeDefinitionList struct { + Challenges []ChallengeDefinition `json:"challenges"` + Skipped []SkippedChallenge `json:"skipped"` +} + +// ChallengeFile A file of the definition's files list, looked up in the challenge folder, then in its files/ subfolder. Absolute paths, paths leaving the challenge folder (symlinks included) or going through .git, and Git LFS pointers are errors. +type ChallengeFile struct { + // Declared The path as written in the definition + Declared string `json:"declared"` + + // Error Why the file cannot be served + Error *string `json:"error,omitempty"` + + // Path The file found, relative to challenge_dir (to download with /admin/challenges/file) + Path *string `json:"path,omitempty"` + Size *int64 `json:"size,omitempty"` +} + +// ChallengeRef A deployable challenge, by definition file (path) or by category and name +type ChallengeRef struct { + Category *string `json:"category,omitempty"` + Name *string `json:"name,omitempty"` + + // Path Definition file, relative to challenge_dir (as ChallengeDefinition.path) + Path *string `json:"path,omitempty"` +} + +// CloneRepositoryRequest defines model for CloneRepositoryRequest. +type CloneRepositoryRequest struct { + // Force Replace an existing folder of that name + Force *bool `json:"force,omitempty"` + + // Name Folder name (default from the URL) + Name *string `json:"name,omitempty"` + + // Ref Branch or tag (default branch of the remote) + Ref *string `json:"ref,omitempty"` + Url string `json:"url"` +} + // DeployRequest defines model for DeployRequest. type DeployRequest struct { // Category The category of the challenge to deploy. @@ -132,6 +267,51 @@ type ErrorDeploymentInfo struct { // ErrorDeploymentInfoPreviousStatus The status before the deployment transitioned to error. Indicates whether a deploy or terminate action was in progress. type ErrorDeploymentInfoPreviousStatus string +// FileChecksum defines model for FileChecksum. +type FileChecksum struct { + Sha1 string `json:"sha1"` + Size int64 `json:"size"` +} + +// ImagesRequest defines model for ImagesRequest. +type ImagesRequest struct { + Action ImagesRequestAction `json:"action"` + Challenges *[]ChallengeRef `json:"challenges,omitempty"` + Repo *string `json:"repo,omitempty"` +} + +// ImagesRequestAction defines model for ImagesRequest.Action. +type ImagesRequestAction string + +// Operation defines model for Operation. +type Operation struct { + CreatedAt time.Time `json:"created_at"` + FinishedAt *time.Time `json:"finished_at,omitempty"` + Id string `json:"id"` + Kind OperationKind `json:"kind"` + LineCount int `json:"line_count"` + Lines []OperationLine `json:"lines"` + Result *map[string]interface{} `json:"result,omitempty"` + Status OperationStatus `json:"status"` + Target string `json:"target"` +} + +// OperationKind defines model for Operation.Kind. +type OperationKind string + +// OperationStatus defines model for Operation.Status. +type OperationStatus string + +// OperationLine defines model for OperationLine. +type OperationLine struct { + Level OperationLineLevel `json:"level"` + Message string `json:"message"` + Time time.Time `json:"time"` +} + +// OperationLineLevel defines model for OperationLine.Level. +type OperationLineLevel string + // ReloadChallengesResponse defines model for ReloadChallengesResponse. type ReloadChallengesResponse struct { // Indexed Number of challenges in the index after the reload. @@ -141,6 +321,37 @@ type ReloadChallengesResponse struct { Skipped []SkippedChallenge `json:"skipped"` } +// Repository defines model for Repository. +type Repository struct { + // Branch Current branch, empty when HEAD is detached (tag) + Branch *string `json:"branch,omitempty"` + + // Challenges Challenge definitions in the folder + Challenges int `json:"challenges"` + Commit *string `json:"commit,omitempty"` + CommitMessage *string `json:"commit_message,omitempty"` + CommitTime *time.Time `json:"commit_time,omitempty"` + + // Dirty Tracked files differ from the commit + Dirty *bool `json:"dirty,omitempty"` + Error *string `json:"error,omitempty"` + IsGit bool `json:"is_git"` + Name string `json:"name"` + + // Ref Branch or tag the repository follows on update + Ref *string `json:"ref,omitempty"` + + // Remote Remote URL, without credentials + Remote *string `json:"remote,omitempty"` +} + +// RepositoryList defines model for RepositoryList. +type RepositoryList struct { + // CloneSources URL prefixes clones are allowed from (empty means cloning is disabled) + CloneSources []string `json:"clone_sources"` + Repositories []Repository `json:"repositories"` +} + // RetryDeploymentRequest defines model for RetryDeploymentRequest. type RetryDeploymentRequest struct { // Action The action to perform - 'deploy' to retry deployment, 'terminate' to terminate the failed deployment, 'delete' to remove the deployment from the database. If not provided, the action will be inferred from the previous status (deploy or terminate only). @@ -195,9 +406,39 @@ type VersionResponse struct { Version string `json:"version"` } +// ListChallengeDefinitionsParams defines parameters for ListChallengeDefinitions. +type ListChallengeDefinitionsParams struct { + // Repo Only the challenges of this repository + Repo *string `form:"repo,omitempty" json:"repo,omitempty"` +} + +// GetChallengeFileParams defines parameters for GetChallengeFile. +type GetChallengeFileParams struct { + // Path Path relative to challenge_dir + Path string `form:"path" json:"path"` + + // Checksum Return the file's SHA-1 and size (JSON) instead of its content + Checksum *bool `form:"checksum,omitempty" json:"checksum,omitempty"` +} + +// GetOperationParams defines parameters for GetOperation. +type GetOperationParams struct { + // Offset Return the log lines from this index on + Offset *int `form:"offset,omitempty" json:"offset,omitempty"` +} + +// BuildChallengesJSONRequestBody defines body for BuildChallenges for application/json ContentType. +type BuildChallengesJSONRequestBody = BuildRequest + // DeployAdminInstanceJSONRequestBody defines body for DeployAdminInstance for application/json ContentType. type DeployAdminInstanceJSONRequestBody = AdminDeployRequest +// ManageImagesJSONRequestBody defines body for ManageImages for application/json ContentType. +type ManageImagesJSONRequestBody = ImagesRequest + +// CloneRepositoryJSONRequestBody defines body for CloneRepository for application/json ContentType. +type CloneRepositoryJSONRequestBody = CloneRepositoryRequest + // RetryDeploymentJSONRequestBody defines body for RetryDeployment for application/json ContentType. type RetryDeploymentJSONRequestBody = RetryDeploymentRequest @@ -212,6 +453,15 @@ type TerminateInstanceJSONRequestBody = DeployRequest // ServerInterface represents all server handlers. type ServerInterface interface { + // Build challenge images (admin only) + // (POST /admin/build) + BuildChallenges(ctx echo.Context) error + // List challenge definitions (admin only) + // (GET /admin/challenges) + ListChallengeDefinitions(ctx echo.Context, params ListChallengeDefinitionsParams) error + // Download a file of a challenge (admin only) + // (GET /admin/challenges/file) + GetChallengeFile(ctx echo.Context, params GetChallengeFileParams) error // Check communication with Zync // (POST /admin/config-check) ConfigCheck(ctx echo.Context) error @@ -224,12 +474,36 @@ type ServerInterface interface { // List all deployments in error status (admin only) // (GET /admin/error-deployments) ListErrorDeployments(ctx echo.Context) error + // Check or remove challenge images (admin only) + // (POST /admin/images) + ManageImages(ctx echo.Context) error // List all unique challenges // (GET /admin/list-unique-challs) ListUniqueChallenges(ctx echo.Context) error + // List recent operations (admin only) + // (GET /admin/operations) + ListOperations(ctx echo.Context) error + // Get an operation and its log (admin only) + // (GET /admin/operations/{id}) + GetOperation(ctx echo.Context, id string, params GetOperationParams) error + // Cancel a running operation (admin only) + // (POST /admin/operations/{id}/cancel) + CancelOperation(ctx echo.Context, id string) error // Reload challenges index // (POST /admin/reload-challs) ReloadChallenges(ctx echo.Context) error + // List challenge repositories (admin only) + // (GET /admin/repos) + ListRepositories(ctx echo.Context) error + // Clone a challenge repository (admin only) + // (POST /admin/repos) + CloneRepository(ctx echo.Context) error + // Remove a challenge repository (admin only) + // (DELETE /admin/repos/{name}) + RemoveRepository(ctx echo.Context, name string) error + // Update a challenge repository (admin only) + // (POST /admin/repos/{name}/pull) + PullRepository(ctx echo.Context, name string) error // Retry a failed deployment (admin only) // (POST /admin/retry-deployment) RetryDeployment(ctx echo.Context) error @@ -267,6 +541,64 @@ type ServerInterfaceWrapper struct { Handler ServerInterface } +// BuildChallenges converts echo context to params. +func (w *ServerInterfaceWrapper) BuildChallenges(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.BuildChallenges(ctx) + return err +} + +// ListChallengeDefinitions converts echo context to params. +func (w *ServerInterfaceWrapper) ListChallengeDefinitions(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Parameter object where we will unmarshal all parameters from the context + var params ListChallengeDefinitionsParams + // ------------- Optional query parameter "repo" ------------- + + err = runtime.BindQueryParameter("form", true, false, "repo", ctx.QueryParams(), ¶ms.Repo) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter repo: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.ListChallengeDefinitions(ctx, params) + return err +} + +// GetChallengeFile converts echo context to params. +func (w *ServerInterfaceWrapper) GetChallengeFile(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Parameter object where we will unmarshal all parameters from the context + var params GetChallengeFileParams + // ------------- Required query parameter "path" ------------- + + err = runtime.BindQueryParameter("form", true, true, "path", ctx.QueryParams(), ¶ms.Path) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter path: %s", err)) + } + + // ------------- Optional query parameter "checksum" ------------- + + err = runtime.BindQueryParameter("form", true, false, "checksum", ctx.QueryParams(), ¶ms.Checksum) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter checksum: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetChallengeFile(ctx, params) + return err +} + // ConfigCheck converts echo context to params. func (w *ServerInterfaceWrapper) ConfigCheck(ctx echo.Context) error { var err error @@ -311,6 +643,17 @@ func (w *ServerInterfaceWrapper) ListErrorDeployments(ctx echo.Context) error { return err } +// ManageImages converts echo context to params. +func (w *ServerInterfaceWrapper) ManageImages(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.ManageImages(ctx) + return err +} + // ListUniqueChallenges converts echo context to params. func (w *ServerInterfaceWrapper) ListUniqueChallenges(ctx echo.Context) error { var err error @@ -322,6 +665,62 @@ func (w *ServerInterfaceWrapper) ListUniqueChallenges(ctx echo.Context) error { return err } +// ListOperations converts echo context to params. +func (w *ServerInterfaceWrapper) ListOperations(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.ListOperations(ctx) + return err +} + +// GetOperation converts echo context to params. +func (w *ServerInterfaceWrapper) GetOperation(ctx echo.Context) error { + var err error + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", ctx.Param("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter id: %s", err)) + } + + ctx.Set(BearerAuthScopes, []string{}) + + // Parameter object where we will unmarshal all parameters from the context + var params GetOperationParams + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameter("form", true, false, "offset", ctx.QueryParams(), ¶ms.Offset) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter offset: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetOperation(ctx, id, params) + return err +} + +// CancelOperation converts echo context to params. +func (w *ServerInterfaceWrapper) CancelOperation(ctx echo.Context) error { + var err error + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", ctx.Param("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter id: %s", err)) + } + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.CancelOperation(ctx, id) + return err +} + // ReloadChallenges converts echo context to params. func (w *ServerInterfaceWrapper) ReloadChallenges(ctx echo.Context) error { var err error @@ -333,6 +732,64 @@ func (w *ServerInterfaceWrapper) ReloadChallenges(ctx echo.Context) error { return err } +// ListRepositories converts echo context to params. +func (w *ServerInterfaceWrapper) ListRepositories(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.ListRepositories(ctx) + return err +} + +// CloneRepository converts echo context to params. +func (w *ServerInterfaceWrapper) CloneRepository(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.CloneRepository(ctx) + return err +} + +// RemoveRepository converts echo context to params. +func (w *ServerInterfaceWrapper) RemoveRepository(ctx echo.Context) error { + var err error + // ------------- Path parameter "name" ------------- + var name string + + err = runtime.BindStyledParameterWithOptions("simple", "name", ctx.Param("name"), &name, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter name: %s", err)) + } + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.RemoveRepository(ctx, name) + return err +} + +// PullRepository converts echo context to params. +func (w *ServerInterfaceWrapper) PullRepository(ctx echo.Context) error { + var err error + // ------------- Path parameter "name" ------------- + var name string + + err = runtime.BindStyledParameterWithOptions("simple", "name", ctx.Param("name"), &name, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter name: %s", err)) + } + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.PullRepository(ctx, name) + return err +} + // RetryDeployment converts echo context to params. func (w *ServerInterfaceWrapper) RetryDeployment(ctx echo.Context) error { var err error @@ -469,12 +926,23 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL Handler: si, } + router.POST(baseURL+"/admin/build", wrapper.BuildChallenges) + router.GET(baseURL+"/admin/challenges", wrapper.ListChallengeDefinitions) + router.GET(baseURL+"/admin/challenges/file", wrapper.GetChallengeFile) router.POST(baseURL+"/admin/config-check", wrapper.ConfigCheck) router.POST(baseURL+"/admin/deploy", wrapper.DeployAdminInstance) router.POST(baseURL+"/admin/deploy-all", wrapper.DeployAllAdminInstances) router.GET(baseURL+"/admin/error-deployments", wrapper.ListErrorDeployments) + router.POST(baseURL+"/admin/images", wrapper.ManageImages) router.GET(baseURL+"/admin/list-unique-challs", wrapper.ListUniqueChallenges) + router.GET(baseURL+"/admin/operations", wrapper.ListOperations) + router.GET(baseURL+"/admin/operations/:id", wrapper.GetOperation) + router.POST(baseURL+"/admin/operations/:id/cancel", wrapper.CancelOperation) router.POST(baseURL+"/admin/reload-challs", wrapper.ReloadChallenges) + router.GET(baseURL+"/admin/repos", wrapper.ListRepositories) + router.POST(baseURL+"/admin/repos", wrapper.CloneRepository) + router.DELETE(baseURL+"/admin/repos/:name", wrapper.RemoveRepository) + router.POST(baseURL+"/admin/repos/:name/pull", wrapper.PullRepository) router.POST(baseURL+"/admin/retry-deployment", wrapper.RetryDeployment) router.GET(baseURL+"/admin/team-deployments", wrapper.ListTeamDeployments) router.POST(baseURL+"/admin/terminate", wrapper.TerminateAdminInstance) @@ -491,47 +959,93 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/+xabW8UORL+K6W+kwCpMwkL6HS5TywBLqfT3grCIR2gyGlXp73pthvbHZhF899PLrvf", - "3ZMJm2Rhtd+mp8t2ueqpFz/uL0mmqlpJlNYkh18SkxVYMfr5lFdCHmFdqvUr/Nigse7fWqsatRVIMhmz", - "eK702v3maDItaiuUTA6TkwKhfQsqB+ueC1aWKM8RrAJOM6+SNLHrGpPDxFgt5HmySZNO7lSyCuNzuzfX", - "m3eTJho/NkIjTw7f9arP1vvQDVVnv2BmnUo/NuXFf2rUzKnwCk2tpMGIPdqZ6ElYrOjHXzXmyWHyl/3e", - "2PvB0vvP2iHPgkLd7JtOD6Y1W48sY04z1UjySJAR0uI5aidVoTHsHAcvF2zQCkYmHv4Vtciy3ltRsoOz", - "b9Jvf+J3aIcKpT2WubppF6VJpqTEzO3vVIQFZjJ+Z8hPeePj6NRgpiQ3cwsdBQkQEoIQGCEzBN5tBIxl", - "2iIfmGoQA91iNCzuAysqJAcMJv3EDGQaWZg4V7piNjlMOLO45wbEHI6fa6HRnDI7X+htgXK6SJBfwU9N", - "WUKuNDRSfGyGMmb31Y1ltiEjomwqhw2yjHubJrqR0v8yVtW1+/nh66HVLTYz8Db3xgD5XGul5zjcmrri", - "k9w6tD0adnbu1yHI7eR0sPs5WkkEggjkWlW0cs5EiXygQDQlCR6fdKD38VE8kmqNl0I15rTH2Xwe/w7O", - "MFd6FlNWM2mEk0buUhztZAXHkgvnHAOfCrQFamBhFCgNFnUlJLMIjPIK2VVIqLU612goPiJ434LyNLHI", - "qtMlU7iXIDhKK3KBegXPq9quwY8eBOk+c43RNFRnazU1vzZsSmYshIG7YmcSu4InaQ/5SAC3Npg7dorC", - "EfRHG4oF9CssFeNdV2CW2wEhOX7GiBd+aqoz1K4qdlqTy52laBCw3KKmZ03LxRFrLkRdxxbotINclGig", - "xNyCamxbiGkRN+dOndtrv0w36bxhm/ombLzXMG5Iq9d9UlvsXXxYxLHs37lYq1E7FMEe3PNgu+f+1W6N", - "AfpSuNfFGwl0T/Eck7rZSgzCGit1OYv6LkNxZtkZM7iC4xyksi6ELwVHnoLtdf0kyhLOnA9y1Bp5P77F", - "aZtk7seShJLl+sEwJ3ghAnyQoRrllI7mhl7zxQxxfNQCZZjcgjVjUJz4f7xEzPczSM28XjNbzLX7mdli", - "3k06kEdzk0ZmYtB5W6xB+FQUEHp1H0oKdVNGN0Vu23I82KF3pI7JdxWUBg+/7NyaWZRmOG7iV9cDth0L", - "IMsK6IYA49zAfVydr1J4nzw6qN4n7sfD4n3yYLV1NXPqcsu2FNeL+jTkCowthBlWcth7CCKHRpaiEout", - "7rz/izR96bBIUp6PRoEvcdGKRRWaNBQG2LxjdfEo1bD9OFOqRCbjvdsJsqrPclvg0a+w+6F60hNGTtJ3", - "1wpM4qWvv8ONxeLmv6jNVrbh0gvM9xBGthkhwAFesvKSSfErekzDwepvq0cPrla5XWeupEMfZo0Wdv3a", - "md7rdYZMo37a2KJ/etFG67/enjgwknRyGN72KhTW1snGTdzmgvHWnv58TA7wxnO7enbyYtgvNMb9+VQa", - "cVZSRhC2dBP3mz+WxjKZ0aqdCRNnjCfO7KpGyWqRHCaPVgerR0lKKY425v29nymZi/O9rMDsgryifH1W", - "LUF0zF2zQVLPSMjZ03uR5vnh4CDSnKiqaqTriH05tAX8by0zME2WoTF5UzrtHh88nA99I1ljC6XFr8i9", - "0KO50AulzwTnKGEPiNsDRhND5+pNmjyJaXYsLWrJSjCoL1H7/n3k/OTw3djt7z5sPqSJaaqKuZNXQmaA", - "LL5FmirYNpTtRav6yCb9Wz8mHq1o7I+Kr0NFsejZMVbXZVhw/5dQ9HyWuCqHRPjPzTgyrG5wM3PtDxE6", - "o0+SQVOyfW1bd0WNfslKwSGsDfvwRl5I9UlC38UeH90BJB4f/H3rjlipkfE14GdhrBmA6Ea88DxgbZNO", - "NLgBUPpN9LWs75zu+8ROTeUcnXusLK9EaFmOQGqSOFBuxEhxdjpiNCcYodC+48TS+rAsZ140i26kdfYm", - "jcU5Rvq1l2hp7oGsz1vhLEIzpSBkVjbcFZ4RS+OcPgbHv4WxE9bKLFSHnZGxU0cUo8rm59UZYJy+1K3S", - "toYWuzPIfPNphGw0BYmQwWbtoXUBiqUwds8jd4+QO8TiHDtvSLJnWe4EO9e4olpG0Cw6v+Ok03k8sqne", - "tZ6iGni1rRdjfTxxNqa8HNdF/AcX5gKY5IEVDCxVhZW7lvJ0FUxZLVswCxmTUllHqNRMG8e10PmSWeCN", - "BwQCk4oOdd3S90x357UvWYUpMI0tFUBqOLgib0m5Fnr/oKfJZIYGB86LuJ8xO8GFxsy6ffS6amSBFcoa", - "rVHaYAth4AJrSyo8OThwzxpto6U/E4/jZMpE/tYY2RYai6xnJBKCo/8Q/fwCaMfwt3o9KLLbIsCxkWzE", - "qjmkilkaXcHrGjORr1vWkJme11R6yGLGcDEiVm/p2LBA337t0cHbZsup4bbLoz+FtAqMmgAicyceupMD", - "yePb3/jReJe5auR31ZS0MTWj7hc7EYusupGeuCUa0454InR4IjKFc60aV07O1p5no6ED/VoyNto7T1jD", - "O2l/lpjKazQ/Q1PVqGnjf3bQ2zvoKU6Wcdve7yweyU9akW+ZN4oU6lZvV+nutG0IKXZyd6FG13uTjHjj", - "oDjpPwDYnaDpwLCdo+kBcTVNc/A70TR26PzvnqcZePNaVM3gjiNajF7RMcDQmeHyimuPFOjaw10fELNu", - "FRCHH7pNajid25h1dwcrbyRDOqVglBeTKOicU5dsjdqApNsgZ36Uls5VHLJSUAorkWkJnwqRFa1yKZ1h", - "jAr/ekZXGNOgScctcMHMvId9iTZc7twmUKc3TxGI9tcprYduG5vXQVtEOwep3S4Xbrk+/IGuFHa7GBh8", - "tEX2KNHid3lN0Jcf0UKEYEVX+XwZVs/p/QhWtxS4k08tYuea7lMHUgqHfES5XoTOM0/R+EGj04T7O2Ta", - "FKxSgEy7fFmxz8NvHDSyrHA0FNps9eAaGLuqEbnNouUd57/4ae2m8lGa9ggokJW2GBSpWdb+p5f4jb4f", - "3//3H35c+a3sHAivUV+KDF3N89qvp7YZmcLr7+ul33O/+tKeW8S/br8v/B1x7yXoUy2Bl8hvB4HffC5z", - "Z/fx/R9xNs6f1zlHfXsl8uZPT3dxrolWlM3m/wMAd0nbbZY1AAA=", + "H4sIAAAAAAAC/+xde4/cNpL/KkTfAe4BND3OZvcO5/zlteNkFr7E8OMWuMQYsKXqbu5QpEJSM+4E/u6H", + "KlISJVH9sKfHds5/uUeiyGLxV8V6kf5jluuy0gqUs7NHf8xsvoGS08/HRSnUU6ik3r6E32qwDp9WRldg", + "nABqk3MHa222+LsAmxtROaHV7NHs9QZY85bpFXP494ZLCWoNzGlWUM+LWTZz2wpmj2bWGaHWs/fZrG13", + "pXgJ6b7xzXH9vs9mBn6rhYFi9uiXjvTReG/bT/XyX5A7JOnvtZDFC8nVmAdLfMWXMkHoY0YvPZ3CRoTS", + "c8usLsFthFqzuXBM2EA99pYxrgp2LVSBz0XJ18C0YbRcFs66+S21lsAVUkmtiCjhoKQfI+aGB9wYvsW/", + "cQRsCKoukS/UBzLFDzTLZkqrmCldVwa41Wo87X9utrguBpBypf0EnfaTznAWt75FYI+wzMCqtlDMkqP4", + "VykY+CE6LnaDLGs3wEbJt0hMM6Zj81pZvmqIsJBjvxkT6oZLURDCssB4JIAtt4zjbMBEva60LMDgnJZ+", + "SpXkbqVNmTVLxVZCAi2mX9wSlGOFsHxtAJBorRhXfqDUsg5wS+vVLnUWwW8St5H4JoS0mYpF7t1qc82Q", + "C8stM1BpKxwJME2PZG6+1G5DzFwCW4sbUN8xBYLYUgJXlsENmG3XL85poDXaIXtQ/XcDq9mj2b9ddCrp", + "IuijiyfNJy9hlUKx0lc5zzcQQT6SC5xJQhjeJxkmr3+uwHBk0UuwlVYWEorvI6bwJGietvfEfLr+r3Jd", + "KxdRL5SDNRhsVYK1KK3JqcWgaRomOo4fJSE0TffO7eAArX6XCrql8imshBIe4ElVvW+dOlWPRO+ckS5L", + "kRCrJ7UxKOT+fbNLReI058ulgRvBHRRnGbvdgGJe/3O2Fo7lElVuQhcWvcnxoqDfXL6IpulMDVlC0G83", + "WgLregh6ybKKm57q7Zja7UZ7dAfLuUJ94D+Ags2xL/b7VuWoUGn+kfYTqoB36S2sECbB0IG6zZgByZ24", + "oR2/Qwd+nOAaTvQD5PSZkEnZnIBvNqu424yJf9rn+JG0V5Jvl1pfX02O2uFqPPbLDnMN56CsHP5lGI/W", + "rxAGcie3uFh7afIPjpBfoj181yM48Mwvew9vYWObNavXw/6BCuC5SNqsH6G6I+WSAIa9FlXlLZWDun3l", + "27e9j/scsrQjvRttJzMIwwm7lGQ/KKaOsQ8svbBMCusyJrW+hoLVVSPC+UgOHaku1F7h0wtm66V/u2CP", + "l1bL2gHDVbaZ/4dJ4DdkrCV6ZHO7LaVQ15YJlcu6gOIMrY+19l8YXa83bLEWztvHPwjHnj97xSqN26Kx", + "jBtgYIw2djGyOwrIJTcTpiQRh+rw1gjn/Kz63EmJAg01aQF7Nudckd0JzIK5SRu5adXxuulipWtV7NAc", + "bI6ej75VUvOC3Qq3YRcc/beLDjIX2NNZanArfieQoNnKnTcx/uOvXcvW4hjAseXnTgiixZZAYCfr3VTI", + "7BzuUHPkzVkwQVuXEhc/qJUjbJCTqW4255Yl1MSCiE86o2OO4a7faexJp3ulTQ5JXS95jp4Gg3fCOhSY", + "xjtBQeeOxXq4t+um/exn/mtv9hew4rV0bGV0Sdh+8/L52YS/Nu7q74arfIOL6Pi662wZHjcWUqldGqK1", + "kft3HGyUguLXIEbMB7TALtVK37X5jvawUt6LvhJhgIQF6y3Eq6L2PtaVhVyrwiakL7RATRwaMStU3jMl", + "rePGQbFIaKtoMPosvQZOlDC0T2+5ZbkBHjpu9WLBHZzjB8mt4F0lDNgr7lL7AYyM4NB+wX6qpSSDrFbi", + "tzpuYw8f3TruahsHcogz+DabmVop/8s6XVX48+2HQ6sdbMTgXcubAuT3ze7Zx+FOtzbdycmh7dFw8OJ+", + "GIJwJlfR7MdopSYsNOl08YoLCXGAKamSxITlE9F9+TQtSRW6q7q2Vx3Oxv34d2wJK21GMuUMV5b2RChQ", + "xdFMFuxSFQIXx6IXTEEkHr6izQJMKRR3wDjpFeKrUKwyem3Aknwk8L4D5dnMAS+vpliBL5koQDmxEmjC", + "fk/ukv86ElJvXQ1FdbxtVcXRsJHcOhY+PBQ7A9kVaGPuEuCGB+OFHaKwB/3ehFICje7Gkw3k1xbXZCiE", + "dsO/SUrXhxqg1GH4PEXOJQVJJzd+j6mBzvRMQFPkJh31PkH0cjo+Gc82kJuaaBuxTGi+nuY6TBGh9Wo3", + "R37kRWr0eJhfaGJbVS1lx+jO3Q+B7RTnpVCwKxyK7w9flJZnz4WC9KrYWrp9gbbRWox34mj7rfMcLALs", + "lpvwzOtuEliVg5Q9fypSW9yswe1HCUl1SBKEb6INuyfMnl89vu4EFzFqBDAJNyDj6RawrHFiZAOm5+zd", + "5tQ0p/f+bEbIOxCPA66ERp7WbpTUdF8COtGtyNrpcDeFMVPhhJ/qcundrii7EuIJ9BHjKwcmOD04XHrX", + "jQJKkwFRH6+BlWO6bmPNNAj2eZo4VDPx3UGol73A5CAST47fdOjcv2+ilRQg//H7x099itTxfEMxZr4+", + "m+3V0FOc6+IM7dp4dzm5FF2sfyINcLULuaHJMQCmmKhLOaWG59dQhJUvxGoFprMEA50pJ7+NVY1Vt71a", + "9yaXCA18iJ8/SHustJT61jKtgn2TDh+U2iXDG/icvXn5PKMAF6I9N0CmGpd2rwYIlk+Y6t6sVwfeiSgy", + "bmNXVtcmT8HszcvnrDKwEu/A+nSOD01y5AAuHq7X3KPbZ02xEdqYiHBh+VJCcRYL8N5EfstoccQmGMno", + "PqHv9Z8NGJBmoTPbzjE7wAwb2+PB7HeaVWBQbNg5e+AN5gf41OAYkQWdsQetz0ANOg8i6Sdl2JuE0Ngb", + "I0OjvJWtgju+5BYW7HJFpQSV0TeigILi4K2LIqRkS9TBKzCmWWsqDQi2duMozVOOjlZyexb7Nb4RGe2h", + "DfnZSHRyB+0on/RyLp92sf/OQQvcXBwS+I2HSK39aEsZrXo64vqCu804IoaqbjE7sgJFeHcq7FD7Y2kh", + "ExW6TE6Klm1H+vuA+BdFfXxk5LjdAN45UDb+brCuogTWRF0Y8HzD2k8YLwrL5rBYLzL26+zbh+WvM/zx", + "zebX2dli52j2Cm2LXSZO19SbIegkU7VTFI1g598wsWK1kqIUk+G6nZZz49JnsaM/bUd6Nz3pdVOUgSik", + "hPso6obyqHQcQolrcUaoeA287LTcDnhEwYKD9fMgrpVQ+/cXzhia1G0MIZ5YSm7+B4zdWU1z4xuM5xC+", + "bBMEHg7sBy5vuBK/g8c0e7j4z8W3Z/tJbsYZE4nog7w2wm1fIeuDlQrcgHlce03l/3rWSOs//vkawUit", + "ESP0tiNh41w1e48dN7pgkAF7cUkL4JmHs3ry+lnsL9QWHz5WVvh8uBNOYsfd5C+Vdegz4qgtC2fIjL8h", + "23UFildi9mj27eLh4tuQbKeJheRgWw9T6VR52CsUNMu4YrpxAX0eKVQv9pS0feBL2KxPPz7V+TXqBxXK", + "wcI82EZbt2CXzjLvXlOq2Q4yrSFRPJ9Mt50RCS5rNvR5KBJsKOtyx1wVzRbA5sNaRIJMO7fLAg1YfP4k", + "zrMbb7f8XRfboOQd+AgEryopcvr24l9hH/KCe1CNUWMQve/D1JkafPSBpIXW6y8P/3JnY3exIhq4v+Tt", + "yyaxgkD668OHdza6D/knRr4MZZem4QqO+03Csla8dhttxO8Ncd+mMpdmKYoCFDtnVMfMnL4G5aGJWPt1", + "VnLF1/DrjNlcV8Ba/lOX/3X6+T4OpaSdaAnbKLiePpo9+qWviX55+/5tNrN1WXJ0rT1kI2spiOHc63Sy", + "J6nDUUUA0h5iSn3avu9XcI5S8iMDjQICGbvdcIfiTuUgqAe9q+arQ2opWWApm68kX0dimrXVEhbttlBY", + "YDP6svMgH9impg7F+rZVReQ3Oe9IjUUaHbhEat6SQjS8BAfGEpcHsqDkdqDj2kruXg2TwNa/1dDVOj3y", + "Id0sAslwZ3o7EvG7E7KpWqgEDJPxkE8rfH89vfBFdXHox1F5zXFCh/xMSsghgkelOJPSF6qzhLKigCgu", + "heCLa/biWF8whFxTx0RNm/qcULxiAVivMOxswV7QRiuU01RUFUayVKQvgZNk6dq1lIwrwLiBpnp/LHo/", + "gOuXou0ROXL/dtVHpkStddziHXSX6GXj2JKrjWp10APLXv34+PwbbzyQmfmPVz//dIZL4oDTeQ5UTA1G", + "02TlTR4sQUrnUJxSDfSycQjEuCudO3Dn1hngZb/L1h9dCsVpRkMGjuTpGdW5eZoJO8Seduh7NiEIEH92", + "FUYs/0Dl9bSpFOTtfh4rlkkFptVKrM9pXWOvoS/zT6gV4W6WBvdgB9JlWavAHc/h/92qnIW80aqWd72W", + "nDruLdnfUpRdKgdGcenrNo0vWTiO08QGMloSU4x5G6J8k1z1gQCiv3H7TuSbJM79He6hDOsn25hKoJR4", + "X/X9irQQh7HZBXujrpW+Vd3exS6f3gMkghcwOSMuDfBi64stbQSiUyu5jwaln0QX+tov+R6d51zKvQiV", + "sgdSOzuhK5s+rJVgGjZMVA1+wYqlWUMpR6s4bYHSOOeDOGTSBv0BHPUdtfV6K6QuqKcsOHBoJPYK02zS", + "BxsU6tnZR5o+BwVQU9WB40zXCDBk3utVmFbMsXuDzGevRohHQ5AIFXjW5LgmoNgdVT4y9uitSjb3/dO5", + "AJ+2o3gh/jibCkxOBCNf1FJC0TRCf0ZREMP3VvSilSWvrE+u+IPBTpOpi8QAq8BQl2zu+zrzZ1So+SC4", + "2XzYxGo6as8W7BX2Zh+xyoAN+Qi+pF/NrL9riMuaN9pEsVB89cg7h0SlQAqFlP5U9tl3rFYGqaLTF3Ns", + "R2QXoiCLkit7C4ZY69eSmjhur5sxtHeW8KszimJ7voZT6mhNUod+HdACaro2NWJh7Cj+N1nTl82h5lPY", + "Nf1iwK9B169B148JunrDvlU+h4dfpbDu3G/Z5/RRvAmPN8031HKQkDj1pnnEUfXprXNklnzB1la71SUm", + "1S1tu3rTdtXrDbASVaOB3LtFTSAyC/dQ4I4R9GjbXVfx5DYgDJN6nQ5z/9xRcB84ibTaflz8HE3HDdiw", + "EuZTap+joRDI7lZoUty7Jhd/iOL9pKz/AN3ijaOkFF8Mcc4QXqTM+93EPKVeM6oFbkqVhA1RZaIlFdzU", + "q5X1lcXDEbuaoVOGNnfupyhkOobmnzoQ2FkPHxgNJF8vtrNJBTlLuDgQ1xe+eH1HVJDenxTibw8JSXk6", + "pJ9oMHvuPhDwZYDknoyunji2YbPmjMmRZhctH+NtKVDX8RRSfYF9ZGulHU5f9t8v2EcVSCqxEPaaxMLX", + "LYe8WwmlRq+Hiu3ZsCbfe6vt2X9/ywolR+hNUXtGw/hSqQe2PXV84W+hQqe0qWJBMtCIRJdVhRJrj/rv", + "6K9BZ96jDRX7VLnaz+P5mz9wHh2tuEJ+k85DPb7nhbDsGiqfff/bw4f+4i7cRlK5v+E5itkJt4PJMxvJ", + "3C8t9J8ivTAB2j78Kz1tjz4X1xCc95EpGi4/y7ruz9urzDqxA1XQ5RuZtxsUQEFhGx4rwo22EFRfLrko", + "ETmRUpwLa2t/wxqC7snrZ+01ag9sw55VSCvqW8VylOUsxGk2XBX+TOnS6FsLxp4tmC9hcbo6pzM/UQq9", + "l1KOClTWwvk4jo/ahCsO9lbxpw3xl/1i+RMCv3dMYVepg4BPWtfxRUU1O/UYn3oYbDHZ0aFLj6DBqRgq", + "vhiAkq7V8RuXTZVaLdjrAM+ytiGd4ddBKwrAxWQvwiGNMVIHN46cKPA2ca/J1wjcHUTgTlxj8MEST3YO", + "4pPiyV5dfhZRvmCA9SSwyeAeZYgiqHtVE737/aZM0Urbiz/Qpnvvl5hO8RyuQfwHNnGwrruNa6faeBnq", + "pG83ocTMJ2nbiqbOkCCmpKy6Ut/0dcZ+Ry6cvftoV+6TKYL/d6WQn4uk7kXosfYyBes/Qmwv6N6C49OW", + "K3D5Jkju8pBDsmiDGrAQDkcE+5XShmwudc4lTqJ18Aphc27aWuo9auCyPcOhdIg2zy0Ai8+FJA5HvKil", + "/Cr6X0X/80rFvfExmaOF2pltVAuzKzLkzLa9lsiflUWRFqNqhwV7VUEuVtvmLDC33WllbeKzyamdtXdc", + "+kTG+MSh7A+t8PO82VHcd6/WM+vV6hCoByt0L3WD9yC6T/uzbEX3S/GyG5kaHciflFcHvLyT0rXm+HDW", + "xZARHf54ccbWRtdViEUBL/2n8c39dZvBGId9BmeB7yUJO3X++IhUfcyqCq0M4OXXQrfdhW5DnEzjtrm1", + "YTI39rpp8jmXdycC2A3dZDPdZzg9qNjBjQS6d2nHQCPeOShed1cTHl5H3YJhdyl1B4j91dQPP1E1tYsX", + "/4svp45W86iK6ujmguRm5KssvBd2s+cyg4zRGb6VNv4ADIWFIb8O1iYZnLhs3ImlhIVnkiWaMmZ1uOI5", + "/FcsleRbMOjfGVYT+0E5yjcWLJeCVJgEbhS73Yh80xDncx9Wh6f+4AVlZ2zWN4E33CbP+4UrG04J1OF9", + "EgmIdpckNCt0amweVXExpg4hddgZoBPvD3+ikz+Hnd+JrpMlflBI9ks8zRNHeQJECFZ0QU8xDavv6X0P", + "VicS3MEFSim/pr3AiIiCOE8vt5PQeeJLF/xHPW8iFJ37gKLTmgE3qC9L/i6+uYjK4aHIGLh8cXYExvYZ", + "IqfctPzC+btTGr6Fg9/d8IiADXDp77CZqj380bf4yLUfXPfbXue09xbvMRBegbkROR1d8NRvh7zpscLT", + "7/dLP+du9Kk5N4h/1V36+8lw71vQBWwCbo4ypY5A4Gevy9B37x/To5gNrucxftTnt0Xevfd0H35Nckd5", + "//7/AgAA//+WtlprNXQAAA==", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/galvanize-instancer/pkg/config/config.go b/galvanize-instancer/pkg/config/config.go index 8b1b4c7..9f23d32 100755 --- a/galvanize-instancer/pkg/config/config.go +++ b/galvanize-instancer/pkg/config/config.go @@ -61,6 +61,67 @@ type InstancerConfig struct { NumWorkers int `mapstructure:"num_workers,omitempty"` // Number of Ansible workers (default: 10) Metrics MetricsConfig `mapstructure:"metrics"` // Metrics endpoint configuration DefaultResourceLimits ResourceLimits `mapstructure:"default_resource_limits"` // Default container resource limits applied to all deployments + Repositories RepositoriesConfig `mapstructure:"repositories"` // Challenge repositories managed through the admin API + Build BuildConfig `mapstructure:"build"` // Image builds on the Ansible hosts +} + +// RepositoriesConfig lists where challenge repositories may be cloned from. +// Cloning is disabled while Sources is empty; repositories already in +// challenge_dir can still be listed, updated and removed. +type RepositoriesConfig struct { + Sources []RepositorySource `mapstructure:"sources"` + GitTimeout time.Duration `mapstructure:"git_timeout,omitempty"` // Time limit of one git command (default: 10m) +} + +// RepositorySource allows clones of the repositories below URLPrefix, a URL +// ending with "/" (same scheme, host and port, path inside its folder; see +// Allows). Token, when +// set, is sent as HTTP basic auth (Username, default "x-access-token") to +// fetch private repositories; it is never written to the clone. +type RepositorySource struct { + URLPrefix string `mapstructure:"url_prefix"` + Username string `mapstructure:"username,omitempty"` + Token string `mapstructure:"token,omitempty"` +} + +// BuildConfig controls image builds, run with Docker on every Ansible host. +type BuildConfig struct { + Concurrency int `mapstructure:"concurrency,omitempty"` // Challenges built at the same time (default: 2) + Timeout time.Duration `mapstructure:"timeout,omitempty"` // Time limit of one challenge build (default: 30m) + // ProtectedImages are images challenges may never build (an image + // repository, any tag, or a prefix ending with "/"): the platform's own. + // Unset: Galvanize's defaults (traefik, mariadb, redis...); [] disables. + ProtectedImages []string `mapstructure:"protected_images"` +} + +const ( + DefaultGitTimeout = 10 * time.Minute + DefaultBuildConcurrency = 2 + DefaultBuildTimeout = 30 * time.Minute +) + +// GitTimeoutOrDefault returns git_timeout, or its default when unset. +func (r RepositoriesConfig) GitTimeoutOrDefault() time.Duration { + if r.GitTimeout > 0 { + return r.GitTimeout + } + return DefaultGitTimeout +} + +// ConcurrencyOrDefault returns build.concurrency, or its default when unset. +func (b BuildConfig) ConcurrencyOrDefault() int { + if b.Concurrency > 0 { + return b.Concurrency + } + return DefaultBuildConcurrency +} + +// TimeoutOrDefault returns build.timeout, or its default when unset. +func (b BuildConfig) TimeoutOrDefault() time.Duration { + if b.Timeout > 0 { + return b.Timeout + } + return DefaultBuildTimeout } type RedisConfig struct { @@ -133,6 +194,14 @@ func (ic InstancerConfig) RandomizedPortRange() (lo, hi int) { // Validate checks the instancer settings that have no safe fallback. func (ic InstancerConfig) Validate() error { + for i, src := range ic.Repositories.Sources { + if src.URLPrefix == "" { + return fmt.Errorf("repositories.sources[%d]: url_prefix is required", i) + } + if err := src.ValidatePrefix(); err != nil { + return fmt.Errorf("repositories.sources[%d]: url_prefix %w", i, err) + } + } lo, hi := ic.RandomizedPortRange() if lo < 1 || hi > 65535 || lo > hi { return fmt.Errorf("invalid randomized port range %d-%d: randomized_port_min and randomized_port_max must be between 1 and 65535, the minimum not above the maximum (defaults: %d-%d)", @@ -146,20 +215,24 @@ var ( mu sync.RWMutex ) +// Load replaces the current config with the one of the global viper. func Load() error { - zap.S().Infof("Loading config from %s", viper.ConfigFileUsed()) - mu.Lock() - defer mu.Unlock() + return load(viper.GetViper()) +} +func load(v *viper.Viper) error { + zap.S().Infof("Loading config from %s", v.ConfigFileUsed()) cfg := &Config{} - if err := viper.Unmarshal(cfg); err != nil { + if err := v.Unmarshal(cfg); err != nil { return err } if err := cfg.Instancer.Validate(); err != nil { return fmt.Errorf("instancer: %w", err) } - zap.S().Info("Config loaded successfully") + mu.Lock() current = cfg + mu.Unlock() + zap.S().Info("Config loaded successfully") return nil } @@ -169,8 +242,17 @@ func Get() *Config { return current } -func Reload() error { - return Load() +// Reload replaces the current config with the one v read from the changed +// file. The file may have been read while it was being written (cp +// truncates it first): a config without challenge_dir or ansible_dir, which +// every config has, is refused and the current one kept. +func Reload(v *viper.Viper) error { + for _, key := range []string{"instancer.challenge_dir", "instancer.ansible_dir"} { + if v.GetString(key) == "" { + return fmt.Errorf("%s is missing: the file is empty or incomplete, the current config is kept", key) + } + } + return load(v) } func LoadDefaults() error { diff --git a/galvanize-instancer/pkg/config/repositories.go b/galvanize-instancer/pkg/config/repositories.go new file mode 100644 index 0000000..d8e8f1e --- /dev/null +++ b/galvanize-instancer/pkg/config/repositories.go @@ -0,0 +1,140 @@ +package config + +import ( + "fmt" + "net/url" + "strings" +) + +// Repository URLs are compared structurally, never as strings: a plain +// prefix test lets "https://github.com/org" allow "https://github.com/org-evil/x", +// "https://git.example.com" allow "https://git.example.com.evil.tld/x" (which +// then receives the token), and "https://github.com/org/../other/x" escape the +// organisation. + +// repoSchemes are the URL schemes repositories may be cloned with. +var repoSchemes = map[string]string{"https": "443", "http": "80", "ssh": "22", "git": "9418", "file": ""} + +// repoURL is a parsed repository URL or source prefix. +type repoURL struct { + scheme, host, port string + // segments of the path, without the empty first one; a trailing slash + // gives an empty last segment + segments []string +} + +// parseRepoURL parses and checks a repository URL. Percent-encoding, +// backslashes, credentials, queries, fragments and "." or ".." segments are +// refused: they are never needed and each one is a way to make two +// comparisons of the same URL disagree. +func parseRepoURL(raw string) (*repoURL, error) { + if raw == "" { + return nil, fmt.Errorf("empty URL") + } + for _, r := range raw { + if r <= ' ' || r == 0x7f || r == '\\' || r == '%' { + return nil, fmt.Errorf("%q: spaces, control characters, backslashes and percent-encoding are not allowed", raw) + } + } + u, err := url.Parse(raw) + if err != nil { + return nil, fmt.Errorf("%q is not a URL", raw) + } + scheme := strings.ToLower(u.Scheme) + defaultPort, ok := repoSchemes[scheme] + if !ok { + return nil, fmt.Errorf("%q: the scheme must be https, http, ssh, git or file", raw) + } + if u.User != nil { + return nil, fmt.Errorf("%q: credentials in the URL are not allowed; configure a token on the source instead", raw) + } + if u.Opaque != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || strings.Contains(raw, "#") { + return nil, fmt.Errorf("%q: queries and fragments are not allowed", raw) + } + host := strings.ToLower(u.Hostname()) + if scheme != "file" && host == "" { + return nil, fmt.Errorf("%q has no host", raw) + } + if scheme == "file" && host != "" { + return nil, fmt.Errorf("%q: file URLs take no host (file:///path)", raw) + } + port := u.Port() + if port == "" { + port = defaultPort + } + path := u.Path + if path == "" { + path = "/" + } + if !strings.HasPrefix(path, "/") { + return nil, fmt.Errorf("%q: invalid path", raw) + } + segments := strings.Split(path[1:], "/") + for i, s := range segments { + if s == "." || s == ".." { + return nil, fmt.Errorf("%q: \".\" and \"..\" path segments are not allowed", raw) + } + if s == "" && i != len(segments)-1 { + return nil, fmt.Errorf("%q: empty path segment", raw) + } + } + return &repoURL{scheme: scheme, host: host, port: port, segments: segments}, nil +} + +// ValidatePrefix checks url_prefix: a URL whose path ends with "/", so that +// it names a host or a folder of it, never the start of a name. +func (s RepositorySource) ValidatePrefix() error { + p, err := parseRepoURL(s.URLPrefix) + if err != nil { + return err + } + if p.segments[len(p.segments)-1] != "" { + return fmt.Errorf("%q must end with \"/\" (e.g. https://github.com/your-org/)", s.URLPrefix) + } + if s.Token != "" && p.scheme != "https" { + return fmt.Errorf("%q: a token can only be sent over https", s.URLPrefix) + } + return nil +} + +// Allows reports whether rawURL is a repository below the source: same +// scheme, host and port, and a path continuing url_prefix's folders. +func (s RepositorySource) Allows(rawURL string) bool { + p, err := parseRepoURL(s.URLPrefix) + if err != nil || p.segments[len(p.segments)-1] != "" { + return false + } + u, err := parseRepoURL(rawURL) + if err != nil { + return false + } + if u.scheme != p.scheme || u.host != p.host || u.port != p.port { + return false + } + folders := p.segments[:len(p.segments)-1] + if len(u.segments) <= len(folders) || u.segments[len(folders)] == "" { + return false // the URL must name something inside the folder + } + for i, f := range folders { + if u.segments[i] != f { + return false + } + } + return true +} + +// CheckRepositoryURL returns an error explaining why rawURL cannot be used. +func CheckRepositoryURL(rawURL string) error { + _, err := parseRepoURL(rawURL) + return err +} + +// SourceFor returns the source allowing rawURL, or nil. +func (r RepositoriesConfig) SourceFor(rawURL string) *RepositorySource { + for i := range r.Sources { + if r.Sources[i].Allows(rawURL) { + return &r.Sources[i] + } + } + return nil +} diff --git a/galvanize-instancer/pkg/config/repositories_test.go b/galvanize-instancer/pkg/config/repositories_test.go new file mode 100644 index 0000000..1b34bd6 --- /dev/null +++ b/galvanize-instancer/pkg/config/repositories_test.go @@ -0,0 +1,66 @@ +package config + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestRepositorySource_Allows(t *testing.T) { + org := RepositorySource{URLPrefix: "https://github.com/org/"} + for _, ok := range []string{ + "https://github.com/org/repo", + "https://github.com/org/repo.git", + "https://GitHub.com/org/repo.git", + "https://github.com:443/org/repo.git", + "https://github.com/org/team/repo.git", + } { + assert.True(t, org.Allows(ok), ok) + } + for _, bad := range []string{ + "https://github.com/org", // the folder itself + "https://github.com/org/", // the folder itself + "https://github.com/org-evil/repo", // longer name, same start + "https://github.com.evil.tld/org/repo", // longer host, same start + "https://github.com:8443/org/repo", // other port + "http://github.com/org/repo", // other scheme + "https://github.com/org/../attacker/repo", // dot segments + "https://github.com/org/./repo", // dot segments + "https://github.com/org/%2e%2e/attacker/repo", // encoded dot segments + "https://github.com/org//repo", // empty segment + "https://user:pass@github.com/org/repo", // credentials + "https://github.com/org/repo?x=1", // query + "https://github.com/org/repo#frag", // fragment + "https://github.com/org/re po", // space + "https://github.com/org\\repo", // backslash + "ext::sh -c touch% /tmp/pwned", // command transport + "git@github.com:org/repo.git", // scp syntax: not a URL + "", + } { + assert.False(t, org.Allows(bad), bad) + } + + // A prefix without a trailing slash allows nothing (Validate refuses it) + assert.False(t, RepositorySource{URLPrefix: "https://github.com/org"}.Allows("https://github.com/org/repo")) + + host := RepositorySource{URLPrefix: "https://git.example.com/"} + assert.True(t, host.Allows("https://git.example.com/any/repo.git")) + assert.False(t, host.Allows("https://git.example.com.evil.tld/any/repo.git")) + + local := RepositorySource{URLPrefix: "file://"} + assert.True(t, local.Allows("file:///srv/git/chals.git")) + assert.False(t, local.Allows("file://host/srv/git/chals.git")) +} + +func TestRepositorySource_ValidatePrefix(t *testing.T) { + assert.NoError(t, RepositorySource{URLPrefix: "https://github.com/org/", Token: "t"}.ValidatePrefix()) + assert.NoError(t, RepositorySource{URLPrefix: "git://192.168.1.2/"}.ValidatePrefix()) + assert.NoError(t, RepositorySource{URLPrefix: "file://"}.ValidatePrefix()) + assert.Error(t, RepositorySource{URLPrefix: "https://github.com/org"}.ValidatePrefix(), "no trailing slash") + assert.Error(t, RepositorySource{URLPrefix: "github.com/org/"}.ValidatePrefix(), "no scheme") + assert.Error(t, RepositorySource{URLPrefix: "http://git.local/", Token: "t"}.ValidatePrefix(), "token over http") + assert.Error(t, RepositorySource{URLPrefix: "https://u:p@github.com/org/"}.ValidatePrefix()) + + ic := InstancerConfig{Repositories: RepositoriesConfig{Sources: []RepositorySource{{URLPrefix: "https://github.com/org"}}}} + assert.ErrorContains(t, ic.Validate(), "repositories.sources[0]") +} diff --git a/galvanize-instancer/pkg/restserver.go b/galvanize-instancer/pkg/restserver.go index cb382bf..1301c5b 100755 --- a/galvanize-instancer/pkg/restserver.go +++ b/galvanize-instancer/pkg/restserver.go @@ -10,7 +10,9 @@ import ( "github.com/28Pollux28/galvanize/internal/ansible" "github.com/28Pollux28/galvanize/internal/auth" + "github.com/28Pollux28/galvanize/internal/build" "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/internal/operation" "github.com/28Pollux28/galvanize/pkg/api" "github.com/28Pollux28/galvanize/pkg/config" pkgmetrics "github.com/28Pollux28/galvanize/pkg/metrics" @@ -36,6 +38,13 @@ type Server struct { wg sync.WaitGroup jobQueue *worker.Queue // Redis job queue (optional, nil means use direct goroutines) version string // reported to admins only + operations *operation.Manager + builder *build.Builder + gitBinary string + // buildCat is the build catalog of the current challenge index (see + // buildCatalog) + buildCatMu sync.Mutex + buildCat *build.Catalog } // ServerOpts holds the dependencies needed to construct a Server. @@ -53,6 +62,12 @@ type ServerOpts struct { JobQueue *worker.Queue // Optional: if provided, jobs are queued to Redis // Version of the running Galvanize, reported to admins only Version string + // Operations runs repository, build and image operations (default: a new manager) + Operations *operation.Manager + // UtilityRunner runs the build and image playbooks (default: Ansible) + UtilityRunner ansible.UtilityRunner + // GitBinary is the git executable (default: "git" from PATH) + GitBinary string } var _ api.ServerInterface = (*Server)(nil) @@ -73,7 +88,18 @@ func NewServerWithOpts(opts ServerOpts) *Server { if teamDeployer == nil { teamDeployer = deployer } + ops := opts.Operations + if ops == nil { + ops = operation.NewManager() + } + runner := opts.UtilityRunner + if runner == nil { + runner = ansible.AnsibleUtilityRunner{} + } return &Server{ + operations: ops, + builder: &build.Builder{Runner: runner}, + gitBinary: opts.GitBinary, db: opts.DB, challIdx: opts.ChallengeIndexer, confProv: opts.ConfigProvider, @@ -98,6 +124,9 @@ func (s *Server) StartScheduler(ctx context.Context, sched *scheduler.ExpirySche // Wait blocks until all background goroutines have completed. func (s *Server) Wait(ctx context.Context) error { + if err := s.operations.Shutdown(ctx); err != nil { + return err + } done := make(chan struct{}) go func() { s.wg.Wait() diff --git a/galvanize-instancer/pkg/restserver_repos.go b/galvanize-instancer/pkg/restserver_repos.go new file mode 100644 index 0000000..9a2ed8d --- /dev/null +++ b/galvanize-instancer/pkg/restserver_repos.go @@ -0,0 +1,666 @@ +package pkg + +import ( + "context" + "crypto/sha1" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/28Pollux28/galvanize/internal/auth" + "github.com/28Pollux28/galvanize/internal/build" + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/internal/operation" + "github.com/28Pollux28/galvanize/internal/pathutil" + "github.com/28Pollux28/galvanize/internal/repo" + "github.com/28Pollux28/galvanize/pkg/api" + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/28Pollux28/galvanize/pkg/models" + "github.com/28Pollux28/galvanize/pkg/utils" + "github.com/labstack/echo/v4" + "go.uber.org/zap" +) + +// Repository, build and image management (admin API). Everything here works +// on challenge_dir and the Ansible hosts, without any knowledge of the CTF +// platform calling it. + +// requireAdmin answers 401/403 and returns false unless the caller is admin +// with the manage scope (see auth.ScopeManage). +func requireAdmin(ctx echo.Context) (bool, error) { + claims, err := auth.GetClaims(ctx) + if err != nil { + return false, ctx.JSON(401, api.Error{Message: utils.Ptr("Unauthorized")}) + } + if claims.Role != "admin" { + return false, ctx.JSON(403, api.Error{Message: utils.Ptr("Forbidden - Admin access required")}) + } + if claims.Scope != auth.ScopeManage { + return false, ctx.JSON(403, api.Error{Message: utils.Ptr("Forbidden - this endpoint needs an admin token with the \"manage\" scope")}) + } + return true, nil +} + +func apiError(ctx echo.Context, code int, format string, args ...interface{}) error { + return ctx.JSON(code, api.Error{Message: utils.Ptr(fmt.Sprintf(format, args...))}) +} + +func (s *Server) repos() *repo.Manager { + conf := s.confProv.GetConfig() + return &repo.Manager{BaseDir: conf.Instancer.ChallengeDir, Config: conf.Instancer.Repositories, Git: s.gitBinary} +} + +func toAPIOperation(snap operation.Snapshot) api.Operation { + lines := make([]api.OperationLine, 0, len(snap.Lines)) + for _, l := range snap.Lines { + lines = append(lines, api.OperationLine{Time: l.Time, Level: api.OperationLineLevel(l.Level), Message: l.Message}) + } + op := api.Operation{ + Id: snap.ID, Kind: api.OperationKind(snap.Kind), Target: snap.Target, + Status: api.OperationStatus(snap.Status), CreatedAt: snap.CreatedAt, FinishedAt: snap.FinishedAt, + Lines: lines, LineCount: snap.LineCount, + } + if snap.Result != nil { + op.Result = &snap.Result + } + return op +} + +// startOperation starts fn and answers 202 with the operation, or 409. +func (s *Server) startOperation(ctx echo.Context, kind, target string, fn operation.Func) error { + op, err := s.operations.Start(kind, target, fn) + if errors.Is(err, operation.ErrBusy) { + snap := op.Snapshot(0) + return apiError(ctx, 409, "Operation %s (%s %s) is still running", snap.ID, snap.Kind, snap.Target) + } + if err != nil { + return apiError(ctx, 500, "%v", err) + } + zap.S().Infof("Operation %s started: %s %s", op.ID, kind, target) + return ctx.JSON(202, toAPIOperation(op.Snapshot(0))) +} + +// reindex reloads the challenge index after challenge_dir changed. +func (s *Server) reindex(log operation.Logger) { + conf := s.confProv.GetConfig() + if err := s.challIdx.BuildIndex(conf.Instancer.ChallengeDir); err != nil { + log.Errorf("Challenge index not reloaded: %v", err) + return + } + updateChallengeIndexMetrics(s.challIdx) + skipped := s.challIdx.Skipped() + log.Infof("Challenge index reloaded: %d deployable challenge(s), %d definition(s) skipped", len(s.challIdx.GetAll()), len(skipped)) + for _, sk := range skipped { + log.Warnf("Skipped %s: %s", s.relPath(sk.Path), sk.Reason) + } +} + +// relPath makes path relative to challenge_dir when it is inside it. +func (s *Server) relPath(path string) string { + base := s.confProv.GetConfig().Instancer.ChallengeDir + if rel, err := filepath.Rel(base, path); err == nil && pathutil.Inside(base, path) { + return filepath.ToSlash(rel) + } + return path +} + +// relPaths are the definition files of challs, relative to challenge_dir: +// how results name challenges. +func (s *Server) relPaths(challs []*challenge.Challenge) []string { + out := make([]string, 0, len(challs)) + for _, c := range challs { + out = append(out, s.relPath(c.File)) + } + return out +} + +// buildCatalog returns the build catalog of the current challenge index, +// made once per index: the index makes new Challenge values each time it is +// rebuilt. It is kept here rather than by the index, which the build +// package depends on. +func (s *Server) buildCatalog() *build.Catalog { + catalog := s.challIdx.Catalog() + s.buildCatMu.Lock() + defer s.buildCatMu.Unlock() + if !s.buildCat.Of(catalog) { + s.buildCat = build.NewCatalog(catalog) + } + return s.buildCat +} + +// liveDeployments returns the deployments that may still have containers. +func (s *Server) liveDeployments() ([]models.Deployment, error) { + var deployments []models.Deployment + err := s.db.Where("status IN ?", []string{ + models.DeploymentStatusStarting, models.DeploymentStatusRunning, + models.DeploymentStatusStopping, models.DeploymentStatusError, + }).Find(&deployments).Error + return deployments, err +} + +func deploymentOf(d models.Deployment, c *challenge.Challenge) bool { + return strings.EqualFold(d.Category, c.Category) && (d.ChallengeName == c.InstanceKey() || d.ChallengeName == c.Name) +} + +func describeDeployment(d models.Deployment) string { + team := "unique" + if d.TeamID != nil { + team = "team " + *d.TeamID + } + return fmt.Sprintf("%s/%s (%s, %s)", d.Category, d.ChallengeName, team, d.Status) +} + +// ── Repositories ───────────────────────────────────────────────────────────── + +func (s *Server) ListRepositories(ctx echo.Context) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + mgr := s.repos() + infos, err := mgr.List(ctx.Request().Context()) + if err != nil { + return apiError(ctx, 500, "Cannot read the challenge folder: %v", err) + } + counts := map[string]int{} + for _, c := range s.challIdx.Catalog() { + counts[mgr.RepoOf(c.Dir)]++ + } + out := api.RepositoryList{Repositories: make([]api.Repository, 0, len(infos)), CloneSources: []string{}} + for _, info := range infos { + r := api.Repository{Name: info.Name, IsGit: info.IsGit, Challenges: counts[info.Name]} + if info.IsGit { + r.Remote, r.Branch, r.Ref = utils.Ptr(info.Remote), utils.Ptr(info.Branch), utils.Ptr(info.Ref) + r.Commit, r.CommitMessage, r.CommitTime = utils.Ptr(info.Commit), utils.Ptr(info.CommitMessage), info.CommitTime + r.Dirty = utils.Ptr(info.Dirty) + } + if info.Error != "" { + r.Error = utils.Ptr(info.Error) + } + out.Repositories = append(out.Repositories, r) + } + for _, src := range s.confProv.GetConfig().Instancer.Repositories.Sources { + out.CloneSources = append(out.CloneSources, src.URLPrefix) + } + return ctx.JSON(200, out) +} + +func (s *Server) CloneRepository(ctx echo.Context) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + var req api.CloneRepositoryRequest + if err := ctx.Bind(&req); err != nil || strings.TrimSpace(req.Url) == "" { + return apiError(ctx, 400, "Invalid request: url is required") + } + url := strings.TrimSpace(req.Url) + name := strings.TrimSpace(deref(req.Name)) + if name == "" { + name = repo.NameFromURL(url) + } + ref := strings.TrimSpace(deref(req.Ref)) + force := req.Force != nil && *req.Force + mgr := s.repos() + + // Checks that need no git run answer synchronously + if !repo.ValidName(name) { + return apiError(ctx, 400, "Invalid repository name %q", name) + } + if len(mgr.Config.Sources) == 0 { + return apiError(ctx, 403, "%v", repo.ErrCloneDisabled) + } + if err := config.CheckRepositoryURL(url); err != nil { + return apiError(ctx, 403, "URL not allowed: %v", err) + } + if mgr.Config.SourceFor(url) == nil { + return apiError(ctx, 403, "URL not allowed: it must be inside one of repositories.sources") + } + if _, err := mgr.Path(name); err == nil && !force { + return apiError(ctx, 409, "Repository %s already exists (use force to replace it)", name) + } + if force { + if blocked := s.deploymentsInRepo(mgr, name); len(blocked) > 0 { + return apiError(ctx, 409, "Instances of %s are running, terminate them first: %s", name, strings.Join(blocked, ", ")) + } + } + + return s.startOperation(ctx, "clone", name, func(opCtx context.Context, log operation.Logger) (map[string]interface{}, error) { + created, err := mgr.Clone(opCtx, url, name, ref, force, log) + if err != nil { + return nil, err + } + info := mgr.Describe(opCtx, created) + log.Successf("Cloned %s at %s (%s)", created, info.Commit, info.CommitMessage) + s.reindex(log) + return map[string]interface{}{"repository": created, "commit": info.Commit}, nil + }) +} + +func deref(p *string) string { + if p == nil { + return "" + } + return *p +} + +// deploymentsInRepo lists the live deployments of the repository's challenges. +func (s *Server) deploymentsInRepo(mgr *repo.Manager, name string) []string { + deployments, err := s.liveDeployments() + if err != nil { + return []string{fmt.Sprintf("(cannot check: %v)", err)} + } + var out []string + for _, c := range s.challIdx.GetAll() { + if mgr.RepoOf(c.Dir) != name { + continue + } + for _, d := range deployments { + if deploymentOf(d, c) { + out = append(out, describeDeployment(d)) + } + } + } + sort.Strings(out) + return out +} + +func (s *Server) PullRepository(ctx echo.Context, name string) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + mgr := s.repos() + if _, err := mgr.Path(name); err != nil { + return apiError(ctx, 404, "Repository not found: %s", name) + } + return s.startOperation(ctx, "pull", name, func(opCtx context.Context, log operation.Logger) (map[string]interface{}, error) { + before, after, err := mgr.Pull(opCtx, name, log) + if err != nil { + return nil, err + } + if before == after { + // Not "up to date": local changes may just have been discarded + log.Infof("No new commit on %s (%s)", name, after) + } else { + log.Successf("%s updated: %s → %s", name, before, after) + } + s.reindex(log) + s.warnOrphans(log) + return map[string]interface{}{"before": before, "after": after}, nil + }) +} + +// warnOrphans reports live deployments whose challenge left the index: they +// cannot be terminated until the challenge is back. +func (s *Server) warnOrphans(log operation.Logger) { + deployments, err := s.liveDeployments() + if err != nil { + return + } + for _, d := range deployments { + if _, err := s.challIdx.Get(d.Category, d.ChallengeName); err != nil { + log.Warnf("Instance %s has no challenge any more: restore the challenge to terminate it", describeDeployment(d)) + } + } +} + +func (s *Server) RemoveRepository(ctx echo.Context, name string) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + mgr := s.repos() + if _, err := mgr.Path(name); err != nil { + return apiError(ctx, 404, "Repository not found: %s", name) + } + if blocked := s.deploymentsInRepo(mgr, name); len(blocked) > 0 { + return apiError(ctx, 409, "Instances of %s's challenges exist, terminate them first: %s", name, strings.Join(blocked, ", ")) + } + return s.startOperation(ctx, "remove", name, func(opCtx context.Context, log operation.Logger) (map[string]interface{}, error) { + if err := mgr.Remove(name); err != nil { + return nil, err + } + log.Successf("Removed %s", name) + s.reindex(log) + return map[string]interface{}{"repository": name}, nil + }) +} + +// ── Challenge definitions and files ────────────────────────────────────────── + +func toAPIPlan(p build.Plan, deployable bool) api.BuildPlan { + out := api.BuildPlan{Kind: api.BuildPlanKind(p.Kind), Images: p.Images, Buildable: deployable && p.Kind != build.KindNone} + if out.Images == nil { + out.Images = []string{} + } + if p.Reason != "" { + out.Reason = utils.Ptr(p.Reason) + } + if p.Refused { + out.Refused = utils.Ptr(true) + } + return out +} + +func (s *Server) toAPIFiles(files []challenge.File) []api.ChallengeFile { + out := make([]api.ChallengeFile, 0, len(files)) + for _, f := range files { + item := api.ChallengeFile{Declared: f.Declared} + if f.Path != "" { + item.Path, item.Size = utils.Ptr(s.relPath(f.Path)), utils.Ptr(f.Size) + } + if f.Error != "" { + item.Error = utils.Ptr(f.Error) + } + out = append(out, item) + } + return out +} + +func (s *Server) ListChallengeDefinitions(ctx echo.Context, params api.ListChallengeDefinitionsParams) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + mgr := s.repos() + if params.Repo != nil && *params.Repo != "" { + if _, err := mgr.Path(*params.Repo); err != nil { + return apiError(ctx, 404, "Repository not found: %s", *params.Repo) + } + } + out := api.ChallengeDefinitionList{Challenges: []api.ChallengeDefinition{}, Skipped: []api.SkippedChallenge{}} + cat, protected := s.buildCatalog(), build.ProtectedImages(s.confProv.GetConfig()) + commits := map[string]string{} + for _, c := range s.challIdx.Catalog() { + repoName := mgr.RepoOf(c.Dir) + if params.Repo != nil && *params.Repo != repoName { + continue + } + deployable := false + if c.Type == "zync" { + if indexed, err := s.challIdx.Get(c.Category, c.Name); err == nil && indexed.File == c.File { + deployable = true + } + } + def := c.Definition + if def == nil { + def = map[string]interface{}{} + } + item := api.ChallengeDefinition{ + Category: c.Category, Name: c.Name, Type: c.Type, Repository: repoName, + Path: s.relPath(c.File), Dir: s.relPath(c.Dir), Deployable: deployable, + Build: toAPIPlan(cat.PlanIn(c, protected), deployable), Files: s.toAPIFiles(c.Files()), Definition: def, + } + if c.PlaybookName != "" { + item.PlaybookName = utils.Ptr(c.PlaybookName) + } + if repoName != "" { + commit, ok := commits[repoName] + if !ok { + commit = mgr.Commit(ctx.Request().Context(), repoName) + commits[repoName] = commit + } + if commit != "" { + item.Commit = utils.Ptr(commit) + } + } + out.Challenges = append(out.Challenges, item) + } + for _, sk := range s.challIdx.Skipped() { + rel := s.relPath(sk.Path) + if params.Repo != nil && mgr.RepoOf(sk.Path) != *params.Repo { + continue + } + out.Skipped = append(out.Skipped, api.SkippedChallenge{Path: rel, Reason: sk.Reason}) + } + return ctx.JSON(200, out) +} + +// ResolveChallengeFile returns the real path of a file inside the folder of +// a challenge of the catalog, rel being relative to challenge_dir. Paths +// through .git, or leading (symlinks included) outside the challenge folder, +// are refused. The int is the HTTP status for the error. +func (s *Server) ResolveChallengeFile(rel string) (string, int, error) { + base := s.confProv.GetConfig().Instancer.ChallengeDir + clean := filepath.Clean(filepath.FromSlash(rel)) + if rel == "" || filepath.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) { + return "", 400, fmt.Errorf("invalid path") + } + for _, part := range strings.Split(filepath.ToSlash(clean), "/") { + if part == ".git" { + return "", 400, fmt.Errorf("paths into .git are refused") + } + } + requested := filepath.Join(base, clean) + for _, c := range s.challIdx.Catalog() { + if !pathutil.Inside(filepath.Clean(c.Dir), requested) { + continue + } + real, err := pathutil.Resolve(c.Dir, requested) + if errors.Is(err, pathutil.ErrOutside) { + return "", 400, fmt.Errorf("path leads outside the challenge folder") + } + if err != nil { + return "", 404, fmt.Errorf("file not found") + } + st, err := os.Stat(real) + if err != nil || !st.Mode().IsRegular() { + return "", 404, fmt.Errorf("file not found") + } + return real, 200, nil + } + return "", 404, fmt.Errorf("not a file of a challenge") +} + +func (s *Server) GetChallengeFile(ctx echo.Context, params api.GetChallengeFileParams) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + real, code, err := s.ResolveChallengeFile(params.Path) + if err != nil { + return apiError(ctx, code, "%v", err) + } + if params.Checksum != nil && *params.Checksum { + sum, size, err := sha1File(real) + if err != nil { + return apiError(ctx, 500, "Cannot read the file: %v", err) + } + return ctx.JSON(200, api.FileChecksum{Sha1: sum, Size: size}) + } + return ctx.Attachment(real, filepath.Base(real)) +} + +func sha1File(path string) (string, int64, error) { + f, err := os.Open(path) + if err != nil { + return "", 0, err + } + defer func() { _ = f.Close() }() + h := sha1.New() + n, err := io.Copy(h, f) + if err != nil { + return "", 0, err + } + return hex.EncodeToString(h.Sum(nil)), n, nil +} + +// ── Builds and images ──────────────────────────────────────────────────────── + +// selectChallenges returns the deployable challenges of repoName and/or refs +// (all of them when neither is given). +func (s *Server) selectChallenges(repoName *string, refs *[]api.ChallengeRef) ([]*challenge.Challenge, error) { + mgr := s.repos() + var out []*challenge.Challenge + if refs != nil && len(*refs) > 0 { + byPath := map[string]*challenge.Challenge{} + for _, c := range s.challIdx.GetAll() { + byPath[s.relPath(c.File)] = c + } + var missing []string + for _, r := range *refs { + var c *challenge.Challenge + label := deref(r.Path) + if label != "" { + c = byPath[label] + } else { + label = deref(r.Category) + "/" + deref(r.Name) + c, _ = s.challIdx.Get(deref(r.Category), deref(r.Name)) + } + if c == nil || (repoName != nil && *repoName != "" && mgr.RepoOf(c.Dir) != *repoName) { + missing = append(missing, label) + continue + } + out = append(out, c) + } + if len(missing) > 0 { + return nil, fmt.Errorf("not deployable challenges: %s", strings.Join(missing, ", ")) + } + } else { + if repoName != nil && *repoName != "" { + if _, err := mgr.Path(*repoName); err != nil { + return nil, fmt.Errorf("repository not found: %s", *repoName) + } + } + for _, c := range s.challIdx.GetAll() { + if repoName == nil || *repoName == "" || mgr.RepoOf(c.Dir) == *repoName { + out = append(out, c) + } + } + } + sort.Slice(out, func(i, j int) bool { return out[i].File < out[j].File }) + return out, nil +} + +func target(repoName *string, challs []*challenge.Challenge) string { + if len(challs) == 1 { + return build.Label(challs[0]) + } + if repoName != nil && *repoName != "" { + return *repoName + } + return fmt.Sprintf("%d challenge(s)", len(challs)) +} + +func (s *Server) BuildChallenges(ctx echo.Context) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + var req api.BuildRequest + if err := ctx.Bind(&req); err != nil { + return apiError(ctx, 400, "Invalid request") + } + challs, err := s.selectChallenges(req.Repo, req.Challenges) + if err != nil { + return apiError(ctx, 400, "%v", err) + } + noCache := req.NoCache != nil && *req.NoCache + conf := s.confProv.GetConfig() + return s.startOperation(ctx, "build", target(req.Repo, challs), func(opCtx context.Context, log operation.Logger) (map[string]interface{}, error) { + log.Infof("Building %d challenge(s) on %s, %d at a time", len(challs), conf.Instancer.Ansible.Inventory, conf.Instancer.Build.ConcurrencyOrDefault()) + res := s.builder.Build(opCtx, conf, challs, s.buildCatalog(), noCache, log) + log.Infof("Built: %d, failed: %d, nothing to build: %d", len(res.Built), len(res.Failed), len(res.Skipped)) + result := map[string]interface{}{"built": s.relPaths(res.Built), "failed": s.relPaths(res.Failed), "skipped": s.relPaths(res.Skipped)} + if len(res.Failed) > 0 && len(res.Built) == 0 { + return result, fmt.Errorf("no challenge built") + } + return result, nil + }) +} + +func (s *Server) ManageImages(ctx echo.Context) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + var req api.ImagesRequest + if err := ctx.Bind(&req); err != nil { + return apiError(ctx, 400, "Invalid request") + } + action := string(req.Action) + if action != build.ImagesStatus && action != build.ImagesRemove { + return apiError(ctx, 400, "action must be status or remove") + } + challs, err := s.selectChallenges(req.Repo, req.Challenges) + if err != nil { + return apiError(ctx, 400, "%v", err) + } + if action == build.ImagesRemove { + if blocked := s.liveOf(challs); len(blocked) > 0 { + return apiError(ctx, 409, "Instances use these images, terminate them first: %s", strings.Join(blocked, ", ")) + } + } + conf := s.confProv.GetConfig() + return s.startOperation(ctx, "images", target(req.Repo, challs), func(opCtx context.Context, log operation.Logger) (map[string]interface{}, error) { + res, err := s.builder.Images(opCtx, conf, challs, s.buildCatalog(), action, log) + if err != nil { + return nil, err + } + images, byPath := map[string]interface{}{}, map[string]interface{}{} + for img, hosts := range res.States { + images[img] = hosts + } + for c, imgs := range res.Challenges { + byPath[s.relPath(c.File)] = imgs + } + return map[string]interface{}{"images": images, "challenges": byPath}, nil + }) +} + +func (s *Server) liveOf(challs []*challenge.Challenge) []string { + deployments, err := s.liveDeployments() + if err != nil { + return []string{fmt.Sprintf("(cannot check: %v)", err)} + } + var out []string + for _, c := range challs { + for _, d := range deployments { + if deploymentOf(d, c) { + out = append(out, describeDeployment(d)) + } + } + } + return out +} + +// ── Operations ─────────────────────────────────────────────────────────────── + +func (s *Server) ListOperations(ctx echo.Context) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + out := []api.Operation{} + for _, op := range s.operations.List() { + snap := op.Snapshot(-1) // no lines + out = append(out, toAPIOperation(snap)) + } + return ctx.JSON(200, out) +} + +func (s *Server) GetOperation(ctx echo.Context, id string, params api.GetOperationParams) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + op, found := s.operations.Get(id) + if !found { + return apiError(ctx, 404, "Operation not found") + } + offset := 0 + if params.Offset != nil { + offset = *params.Offset + } + return ctx.JSON(200, toAPIOperation(op.Snapshot(offset))) +} + +func (s *Server) CancelOperation(ctx echo.Context, id string) error { + if ok, err := requireAdmin(ctx); !ok { + return err + } + found, running := s.operations.Cancel(id) + if !found { + return apiError(ctx, 404, "Operation not found") + } + if !running { + return apiError(ctx, 409, "Operation %s already finished", id) + } + return ctx.NoContent(202) +} diff --git a/galvanize-instancer/pkg/restserver_repos_test.go b/galvanize-instancer/pkg/restserver_repos_test.go new file mode 100644 index 0000000..ceb3f81 --- /dev/null +++ b/galvanize-instancer/pkg/restserver_repos_test.go @@ -0,0 +1,488 @@ +package pkg + +import ( + "bytes" + "context" + "crypto/sha1" + "encoding/hex" + "encoding/json" + "io" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/28Pollux28/galvanize/internal/ansible" + "github.com/28Pollux28/galvanize/internal/auth" + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/pkg/api" + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/28Pollux28/galvanize/pkg/models" + "github.com/28Pollux28/galvanize/pkg/utils" + "github.com/golang-jwt/jwt/v5" + echojwt "github.com/labstack/echo-jwt/v4" + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const testSecret = "repo-test-secret" + +type recordingRunner struct { + mu sync.Mutex + calls []map[string]interface{} +} + +func (r *recordingRunner) Run(ctx context.Context, conf *config.Config, name string, vars map[string]interface{}, _ time.Duration) ([]ansible.HostResult, error) { + r.mu.Lock() + defer r.mu.Unlock() + call := map[string]interface{}{"playbook": name} + for k, v := range vars { + call[k] = v + } + r.calls = append(r.calls, call) + if name == ansible.PlaybookImages { + var lines []string + for _, i := range vars["images"].([]string) { + lines = append(lines, "present "+i) + } + return []ansible.HostResult{{Host: "h1", Task: "Images", Stdout: lines}}, nil + } + return []ansible.HostResult{{Host: "h1", Task: "Build"}}, nil +} + +type repoEnv struct { + t *testing.T + e *echo.Echo + srv *Server + dir string + runner *recordingRunner +} + +// newRepoEnv serves the API like `galvanize serve` (generated routes, JWT +// middleware) on a challenge_dir holding one repository. +func newRepoEnv(t *testing.T, sources ...config.RepositorySource) *repoEnv { + t.Helper() + dir := t.TempDir() + writeChallenge(t, dir, "Repo/web/app", "name: App\ncategory: Web\ntype: zync\nplaybook_name: http\ndeploy_parameters:\n image: app\n") + require.NoError(t, os.WriteFile(filepath.Join(dir, "Repo/web/app/Dockerfile"), []byte("FROM busybox\n"), 0o644)) + writeChallenge(t, dir, "Repo/misc/intro", "name: Intro\ncategory: Misc\ntype: standard\nflags: [\"F{intro}\"]\nfiles: [notes.txt]\n") + require.NoError(t, os.WriteFile(filepath.Join(dir, "Repo/misc/intro/notes.txt"), []byte("notes"), 0o644)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "Repo/.git"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "Repo/.git/config"), []byte("[core]"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "Repo/secret.txt"), []byte("not a challenge file"), 0o644)) + writeChallenge(t, dir, "Other/pwn/bin", "name: Bin\ncategory: Pwn\ntype: zync\nplaybook_name: tcp\ndeploy_parameters:\n image: ghcr.io/org/bin:1\n") + + cfg := &config.Config{ + Auth: config.AuthConfig{JWTSecret: testSecret}, + Instancer: config.InstancerConfig{ + ChallengeDir: dir, + Repositories: config.RepositoriesConfig{Sources: sources}, + Ansible: config.AnsibleConfig{Inventory: "h1,"}, + }, + } + db, err := InitDB(":memory:") + require.NoError(t, err) + idx, err := challenge.NewChallengeIndex(dir) + require.NoError(t, err) + runner := &recordingRunner{} + srv := NewServerWithOpts(ServerOpts{DB: db, ChallengeIndexer: idx, ConfigProvider: &config.StaticProvider{Cfg: cfg}, UtilityRunner: runner}) + + e := echo.New() + e.Use(echojwt.WithConfig(echojwt.Config{ + NewClaimsFunc: func(c echo.Context) jwt.Claims { return new(auth.Claims) }, + SigningKey: []byte(testSecret), + })) + api.RegisterHandlers(e, srv) + return &repoEnv{t: t, e: e, srv: srv, dir: dir, runner: runner} +} + +func (env *repoEnv) do(method, path, role string, body interface{}) *httptest.ResponseRecorder { + env.t.Helper() + var reader io.Reader + if body != nil { + data, _ := json.Marshal(body) + reader = bytes.NewReader(data) + } + req := httptest.NewRequest(method, path, reader) + req.Header.Set("Content-Type", "application/json") + // "admin" is the platform server's token (manage scope); "admin-browser" + // the admin token a dashboard hands to browsers (no scope) + claims := &auth.Claims{Role: role, RegisteredClaims: jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))}} + switch role { + case "admin": + claims.Scope = auth.ScopeManage + case "admin-browser": + claims.Role = "admin" + } + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + signed, _ := token.SignedString([]byte(testSecret)) + req.Header.Set("Authorization", "Bearer "+signed) + rec := httptest.NewRecorder() + env.e.ServeHTTP(rec, req) + return rec +} + +func sha1Hex(s string) string { + h := sha1.Sum([]byte(s)) + return hex.EncodeToString(h[:]) +} + +func decode[T any](t *testing.T, rec *httptest.ResponseRecorder) T { + t.Helper() + var v T + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &v), rec.Body.String()) + return v +} + +// waitOp polls an operation until it finishes. +func (env *repoEnv) waitOp(id string) api.Operation { + env.t.Helper() + for i := 0; i < 500; i++ { + rec := env.do("GET", "/admin/operations/"+id, "admin", nil) + require.Equal(env.t, 200, rec.Code) + op := decode[api.Operation](env.t, rec) + if op.Status != "running" { + return op + } + time.Sleep(10 * time.Millisecond) + } + env.t.Fatal("operation did not finish") + return api.Operation{} +} + +func TestRepoAPI_RequiresAdmin(t *testing.T) { + env := newRepoEnv(t) + for _, c := range []struct{ method, path string }{ + {"GET", "/admin/repos"}, {"POST", "/admin/repos"}, {"POST", "/admin/repos/Repo/pull"}, + {"DELETE", "/admin/repos/Repo"}, {"GET", "/admin/challenges"}, {"GET", "/admin/challenges/file?path=Repo/misc/intro/notes.txt"}, + {"POST", "/admin/build"}, {"POST", "/admin/images"}, {"GET", "/admin/operations"}, + } { + assert.Equal(t, 403, env.do(c.method, c.path, "user", map[string]string{}).Code, "%s %s", c.method, c.path) + rec := env.do(c.method, c.path, "admin-browser", map[string]string{}) + assert.Equal(t, 403, rec.Code, "admin without the manage scope: %s %s", c.method, c.path) + assert.Contains(t, rec.Body.String(), "manage") + } + req := httptest.NewRequest("GET", "/admin/repos", nil) + rec := httptest.NewRecorder() + env.e.ServeHTTP(rec, req) + assert.Equal(t, 401, rec.Code, "no token") +} + +func TestListRepositories(t *testing.T) { + env := newRepoEnv(t, config.RepositorySource{URLPrefix: "https://github.com/org/", Token: "secret"}) + rec := env.do("GET", "/admin/repos", "admin", nil) + require.Equal(t, 200, rec.Code) + assert.NotContains(t, rec.Body.String(), "secret", "tokens are never returned") + list := decode[api.RepositoryList](t, rec) + assert.Equal(t, []string{"https://github.com/org/"}, list.CloneSources) + require.Len(t, list.Repositories, 2) + assert.Equal(t, "Other", list.Repositories[0].Name) + assert.Equal(t, 2, list.Repositories[1].Challenges) +} + +func TestListChallengeDefinitions(t *testing.T) { + env := newRepoEnv(t) + rec := env.do("GET", "/admin/challenges?repo=Repo", "admin", nil) + require.Equal(t, 200, rec.Code) + list := decode[api.ChallengeDefinitionList](t, rec) + require.Len(t, list.Challenges, 2) + byName := map[string]api.ChallengeDefinition{} + for _, c := range list.Challenges { + byName[c.Name] = c + } + intro := byName["Intro"] + assert.Equal(t, "Repo", intro.Repository) + assert.Equal(t, "Repo/misc/intro/challenge.yml", intro.Path) + assert.Equal(t, "Repo/misc/intro", intro.Dir) + assert.False(t, intro.Deployable, "standard challenges are listed but not deployable") + assert.Equal(t, []interface{}{"F{intro}"}, intro.Definition["flags"]) + assert.Equal(t, api.BuildPlanKind("none"), intro.Build.Kind) + assert.False(t, intro.Build.Buildable) + require.Len(t, intro.Files, 1) + assert.Equal(t, api.ChallengeFile{Declared: "notes.txt", Path: utils.Ptr("Repo/misc/intro/notes.txt"), Size: utils.Ptr(int64(5))}, intro.Files[0]) + assert.Nil(t, intro.Commit, "not a git clone") + app := byName["App"] + assert.True(t, app.Deployable) + assert.Equal(t, api.BuildPlanKind("image"), app.Build.Kind) + assert.True(t, app.Build.Buildable) + assert.Empty(t, app.Files) + + all := decode[api.ChallengeDefinitionList](t, env.do("GET", "/admin/challenges", "admin", nil)) + assert.Len(t, all.Challenges, 3) + + // Regression: an unknown repository listed nothing with 200, and + // clients took it for an empty repository + rec = env.do("GET", "/admin/challenges?repo=Missing", "admin", nil) + assert.Equal(t, 404, rec.Code) + assert.Contains(t, rec.Body.String(), "Repository not found: Missing") + assert.Equal(t, 404, env.do("GET", "/admin/challenges?repo=..", "admin", nil).Code) +} + +func TestGetChallengeFile(t *testing.T) { + env := newRepoEnv(t) + outside := filepath.Join(t.TempDir(), "outside.txt") + require.NoError(t, os.WriteFile(outside, []byte("outside"), 0o644)) + require.NoError(t, os.Symlink(outside, filepath.Join(env.dir, "Repo/misc/intro/link.txt"))) + + rec := env.do("GET", "/admin/challenges/file?path=Repo/misc/intro/notes.txt", "admin", nil) + require.Equal(t, 200, rec.Code) + assert.Equal(t, "notes", rec.Body.String()) + + sum := decode[api.FileChecksum](t, env.do("GET", "/admin/challenges/file?path=Repo/misc/intro/notes.txt&checksum=true", "admin", nil)) + assert.Equal(t, api.FileChecksum{Sha1: sha1Hex("notes"), Size: 5}, sum) + + for path, code := range map[string]int{ + "Repo/misc/intro/../../secret.txt": 404, // inside the repository, but not in a challenge folder + "Repo/secret.txt": 404, + "Repo/.git/config": 400, + "../outside.txt": 400, + "/etc/passwd": 400, + "Repo/misc/intro/link.txt": 400, // symlink leading outside + "Repo/misc/intro/missing.txt": 404, + "Repo/misc/intro": 404, // a folder + } { + assert.Equal(t, code, env.do("GET", "/admin/challenges/file?path="+path, "admin", nil).Code, path) + } +} + +func TestCloneRepository_Refusals(t *testing.T) { + env := newRepoEnv(t) + assert.Equal(t, 403, env.do("POST", "/admin/repos", "admin", map[string]string{"url": "https://github.com/org/x.git"}).Code, "no sources: cloning disabled") + + env = newRepoEnv(t, config.RepositorySource{URLPrefix: "https://github.com/org/"}) + assert.Equal(t, 403, env.do("POST", "/admin/repos", "admin", map[string]string{"url": "https://evil.example/x.git"}).Code) + assert.Equal(t, 400, env.do("POST", "/admin/repos", "admin", map[string]string{}).Code) + assert.Equal(t, 400, env.do("POST", "/admin/repos", "admin", map[string]string{"url": "https://github.com/org/x.git", "name": "../x"}).Code) + assert.Equal(t, 409, env.do("POST", "/admin/repos", "admin", map[string]string{"url": "https://github.com/org/Repo.git"}).Code, "exists") + for _, url := range []string{ + "https://github.com/org-evil/x.git", + "https://github.com.evil.tld/org/x.git", + "https://github.com/org/../attacker/x.git", + "https://github.com/org/%2e%2e/attacker/x.git", + "https://user:pw@github.com/org/x.git", + } { + assert.Equal(t, 403, env.do("POST", "/admin/repos", "admin", map[string]string{"url": url, "name": "x"}).Code, url) + } +} + +func TestListChallengeDefinitions_UnencodableDefinitionIsSkipped(t *testing.T) { + env := newRepoEnv(t) + writeChallenge(t, env.dir, "Repo/misc/nan", "name: Nan\ncategory: Misc\ntype: standard\nvalue: .nan\n") + writeChallenge(t, env.dir, "Repo/misc/keys", "name: Keys\ncategory: Misc\ntype: standard\nextra:\n 1: one\n true: yes\n") + require.NoError(t, env.srv.challIdx.BuildIndex(env.dir)) + rec := env.do("GET", "/admin/challenges", "admin", nil) + require.Equal(t, 200, rec.Code, "one bad definition does not break the catalog") + list := decode[api.ChallengeDefinitionList](t, rec) + names := map[string]api.ChallengeDefinition{} + for _, c := range list.Challenges { + names[c.Name] = c + } + assert.NotContains(t, names, "Nan") + assert.Equal(t, map[string]interface{}{"1": "one", "true": "yes"}, names["Keys"].Definition["extra"], "scalar keys become strings") + var reasons []string + for _, sk := range list.Skipped { + reasons = append(reasons, sk.Path+": "+sk.Reason) + } + assert.Contains(t, strings.Join(reasons, "\n"), "Repo/misc/nan/challenge.yml: challenge file cannot be served as JSON") +} + +func TestBuild_RefusesAnImageOfAnotherChallenge(t *testing.T) { + env := newRepoEnv(t) + // Other/pwn/bin deploys ghcr.io/org/bin:1; a challenge of Repo builds it + writeChallenge(t, env.dir, "Repo/pwn/evil", "name: Evil\ncategory: Pwn\ntype: zync\nplaybook_name: tcp\ndeploy_parameters:\n image: ghcr.io/org/bin:1\n") + require.NoError(t, os.WriteFile(filepath.Join(env.dir, "Repo/pwn/evil/Dockerfile"), []byte("FROM busybox\n"), 0o644)) + writeChallenge(t, env.dir, "Repo/web/proxy", "name: Proxy\ncategory: Web\ntype: zync\nplaybook_name: http\ndeploy_parameters:\n image: traefik:v3.7\n") + require.NoError(t, os.WriteFile(filepath.Join(env.dir, "Repo/web/proxy/Dockerfile"), []byte("FROM busybox\n"), 0o644)) + require.NoError(t, env.srv.challIdx.BuildIndex(env.dir)) + + list := decode[api.ChallengeDefinitionList](t, env.do("GET", "/admin/challenges?repo=Repo", "admin", nil)) + for _, c := range list.Challenges { + switch c.Name { + case "Evil": + assert.Equal(t, api.BuildPlanKind("none"), c.Build.Kind) + assert.Contains(t, *c.Build.Reason, "also used by") + assert.True(t, *c.Build.Refused) + assert.False(t, c.Build.Buildable) + case "Proxy": + assert.Contains(t, *c.Build.Reason, "platform image") + } + } + + rec := env.do("POST", "/admin/build", "admin", map[string]interface{}{"challenges": []map[string]string{{"category": "Pwn", "name": "Evil"}, {"category": "Web", "name": "Proxy"}}}) + require.Equal(t, 202, rec.Code, rec.Body.String()) + op := env.waitOp(decode[api.Operation](t, rec).Id) + assert.Equal(t, api.OperationStatus("failed"), op.Status, "nothing built") + assert.Equal(t, []interface{}{"Repo/pwn/evil/challenge.yml", "Repo/web/proxy/challenge.yml"}, (*op.Result)["failed"], "refused builds fail") + assert.Empty(t, env.runner.calls, "no build ran") + + rec = env.do("POST", "/admin/images", "admin", map[string]interface{}{"action": "remove", "challenges": []map[string]string{{"category": "Pwn", "name": "Evil"}}}) + require.Equal(t, 202, rec.Code, rec.Body.String()) + env.waitOp(decode[api.Operation](t, rec).Id) + assert.Empty(t, env.runner.calls, "the other challenge's image is not removed") +} + +func TestCloneAndPullRepository(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not installed") + } + root := t.TempDir() + bare := filepath.Join(root, "chals.git") + work := filepath.Join(root, "work") + run := func(dir string, args ...string) { + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t") + out, err := cmd.CombinedOutput() + require.NoError(t, err, string(out)) + } + run(root, "init", "--quiet", "--bare", "-b", "main", bare) + run(root, "clone", "--quiet", bare, work) + writeChallenge(t, work, "web/new", "name: New\ncategory: Web\ntype: zync\nplaybook_name: http\ndeploy_parameters:\n image: new\n") + run(work, "add", ".") + run(work, "commit", "--quiet", "-m", "one") + run(work, "push", "--quiet", "origin", "main") + + env := newRepoEnv(t, config.RepositorySource{URLPrefix: "file://"}) + rec := env.do("POST", "/admin/repos", "admin", map[string]string{"url": "file://" + bare}) + require.Equal(t, 202, rec.Code, rec.Body.String()) + op := env.waitOp(decode[api.Operation](t, rec).Id) + require.Equal(t, api.OperationStatus("success"), op.Status, "%+v", op.Lines) + _, err := env.srv.challIdx.Get("Web", "New") + assert.NoError(t, err, "the index is reloaded after the clone") + listing := decode[api.ChallengeDefinitionList](t, env.do("GET", "/admin/challenges?repo=chals", "admin", nil)) + require.Len(t, listing.Challenges, 1) + require.NotNil(t, listing.Challenges[0].Commit, "the repository's commit") + first := *listing.Challenges[0].Commit + + // Busy while running is covered by the operation tests; here: pull + writeChallenge(t, work, "web/new2", "name: New2\ncategory: Web\ntype: zync\nplaybook_name: http\ndeploy_parameters:\n image: new2\n") + run(work, "add", ".") + run(work, "commit", "--quiet", "-m", "two") + run(work, "push", "--quiet", "origin", "main") + rec = env.do("POST", "/admin/repos/chals/pull", "admin", nil) + require.Equal(t, 202, rec.Code, rec.Body.String()) + op = env.waitOp(decode[api.Operation](t, rec).Id) + require.Equal(t, api.OperationStatus("success"), op.Status) + _, err = env.srv.challIdx.Get("Web", "New2") + assert.NoError(t, err) + listing = decode[api.ChallengeDefinitionList](t, env.do("GET", "/admin/challenges?repo=chals", "admin", nil)) + require.Len(t, listing.Challenges, 2) + assert.NotEqual(t, first, *listing.Challenges[0].Commit, "a pull changes the commit") + assert.Empty(t, env.runner.calls, "a clone or a pull builds nothing") + + assert.Equal(t, 404, env.do("POST", "/admin/repos/missing/pull", "admin", nil).Code) +} + +func TestRemoveRepository_RefusedWhileInstancesExist(t *testing.T) { + env := newRepoEnv(t) + team := "7" + require.NoError(t, env.srv.db.Create(&models.Deployment{ChallengeName: "App", Category: "Web", TeamID: &team, Status: models.DeploymentStatusRunning}).Error) + + rec := env.do("DELETE", "/admin/repos/Repo", "admin", nil) + assert.Equal(t, 409, rec.Code) + assert.Contains(t, rec.Body.String(), "Web/App (team 7, running)") + assert.DirExists(t, filepath.Join(env.dir, "Repo")) + + rec = env.do("DELETE", "/admin/repos/Other", "admin", nil) + require.Equal(t, 202, rec.Code) + op := env.waitOp(decode[api.Operation](t, rec).Id) + assert.Equal(t, api.OperationStatus("success"), op.Status) + assert.NoDirExists(t, filepath.Join(env.dir, "Other")) + _, err := env.srv.challIdx.Get("Pwn", "Bin") + assert.Error(t, err, "index reloaded without the removed repository") +} + +func TestBuildAndImages(t *testing.T) { + env := newRepoEnv(t) + rec := env.do("POST", "/admin/build", "admin", map[string]interface{}{"repo": "Repo", "no_cache": true}) + require.Equal(t, 202, rec.Code, rec.Body.String()) + op := env.waitOp(decode[api.Operation](t, rec).Id) + require.Equal(t, api.OperationStatus("success"), op.Status) + assert.Equal(t, []interface{}{"Repo/web/app/challenge.yml"}, (*op.Result)["built"], "results name definition files") + require.Len(t, env.runner.calls, 1) + argv := strings.Join(env.runner.calls[0]["build_argv"].([]string), " ") + assert.Equal(t, "docker build --progress=plain --no-cache -t app -f Dockerfile .", argv) + + rec = env.do("POST", "/admin/build", "admin", map[string]interface{}{"challenges": []map[string]string{{"category": "Misc", "name": "Intro"}}}) + assert.Equal(t, 400, rec.Code, "only deployable challenges can be built") + rec = env.do("POST", "/admin/build", "admin", map[string]interface{}{"challenges": []map[string]string{{"path": "Repo/misc/intro/challenge.yml"}}}) + assert.Equal(t, 400, rec.Code, "by path too") + + // By definition path, with a challenge that has nothing to build + rec = env.do("POST", "/admin/build", "admin", map[string]interface{}{"challenges": []map[string]string{ + {"path": "Repo/web/app/challenge.yml"}, {"path": "Other/pwn/bin/challenge.yml"}}}) + require.Equal(t, 202, rec.Code, rec.Body.String()) + op = env.waitOp(decode[api.Operation](t, rec).Id) + assert.Equal(t, []interface{}{"Repo/web/app/challenge.yml"}, (*op.Result)["built"]) + assert.Equal(t, []interface{}{"Other/pwn/bin/challenge.yml"}, (*op.Result)["skipped"]) + + rec = env.do("POST", "/admin/images", "admin", map[string]interface{}{"action": "status"}) + require.Equal(t, 202, rec.Code, rec.Body.String()) + op = env.waitOp(decode[api.Operation](t, rec).Id) + images := (*op.Result)["images"].(map[string]interface{}) + assert.Equal(t, map[string]interface{}{"h1": "present"}, images["app"]) + assert.Contains(t, images, "ghcr.io/org/bin:1") + assert.Equal(t, []interface{}{"app"}, (*op.Result)["challenges"].(map[string]interface{})["Repo/web/app/challenge.yml"]) + + team := "1" + require.NoError(t, env.srv.db.Create(&models.Deployment{ChallengeName: "App", Category: "Web", TeamID: &team, Status: models.DeploymentStatusRunning}).Error) + rec = env.do("POST", "/admin/images", "admin", map[string]interface{}{"action": "remove", "repo": "Repo"}) + assert.Equal(t, 409, rec.Code, "images in use are not removed") + assert.Equal(t, 400, env.do("POST", "/admin/images", "admin", map[string]interface{}{"action": "explode"}).Code) + + list := decode[[]api.Operation](t, env.do("GET", "/admin/operations", "admin", nil)) + require.Len(t, list, 3) + assert.Equal(t, api.OperationKind("images"), list[0].Kind, "most recent first") + assert.Empty(t, list[0].Lines, "the list has no logs") + assert.Equal(t, 404, env.do("GET", "/admin/operations/nope", "admin", nil).Code) + + // Regression: cancelling a finished operation answered 202 + rec = env.do("POST", "/admin/operations/"+list[0].Id+"/cancel", "admin", nil) + assert.Equal(t, 409, rec.Code) + assert.Contains(t, rec.Body.String(), "already finished") + assert.Equal(t, 404, env.do("POST", "/admin/operations/nope/cancel", "admin", nil).Code) +} + +func TestBuildCatalog_MadeOncePerIndex(t *testing.T) { + env := newRepoEnv(t) + cat := env.srv.buildCatalog() + assert.Same(t, cat, env.srv.buildCatalog(), "kept while the index is unchanged") + require.NoError(t, env.srv.challIdx.BuildIndex(env.dir)) + assert.NotSame(t, cat, env.srv.buildCatalog(), "made again after a reindex") +} + +func TestListChallengeDefinitions_DeclaredFiles(t *testing.T) { + env := newRepoEnv(t) + dir := filepath.Join(env.dir, "Repo/misc/files") + writeChallenge(t, env.dir, "Repo/misc/files", "name: Files\ncategory: Misc\ntype: standard\n"+ + "files: [a.txt, b.txt, missing.txt, /etc/passwd, ../intro/notes.txt, .git/config, out.txt, lfs.bin]\n") + require.NoError(t, os.WriteFile(filepath.Join(dir, "a.txt"), []byte("a"), 0o644)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "files"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "files/b.txt"), []byte("bb"), 0o644)) + require.NoError(t, os.Symlink(filepath.Join(env.dir, "Repo/secret.txt"), filepath.Join(dir, "out.txt"))) + require.NoError(t, os.WriteFile(filepath.Join(dir, "lfs.bin"), []byte("version https://git-lfs.github.com/spec/v1\noid sha256:x\nsize 9\n"), 0o644)) + require.NoError(t, env.srv.challIdx.BuildIndex(env.dir)) + + list := decode[api.ChallengeDefinitionList](t, env.do("GET", "/admin/challenges?repo=Repo", "admin", nil)) + var files []api.ChallengeFile + for _, c := range list.Challenges { + if c.Name == "Files" { + files = c.Files + } + } + require.Len(t, files, 8) + assert.Equal(t, "Repo/misc/files/a.txt", *files[0].Path) + assert.Equal(t, "Repo/misc/files/files/b.txt", *files[1].Path, "then the files/ subfolder") + assert.Equal(t, int64(2), *files[1].Size) + for i, want := range []string{"not found", "absolute", "leaves the challenge folder", ".git", "leads outside", "Git LFS pointer"} { + f := files[i+2] + require.NotNil(t, f.Error, f.Declared) + assert.Contains(t, *f.Error, want, f.Declared) + } + assert.Nil(t, files[0].Error) +} diff --git a/galvanize-instancer/pkg/restserver_test.go b/galvanize-instancer/pkg/restserver_test.go index 59b3376..4fcb61d 100644 --- a/galvanize-instancer/pkg/restserver_test.go +++ b/galvanize-instancer/pkg/restserver_test.go @@ -115,6 +115,7 @@ func (m *mockChallengeIndexer) GetAll() []*challenge.Challenge { func (m *mockChallengeIndexer) BuildIndex(_ string) error { return nil } func (m *mockChallengeIndexer) Skipped() []challenge.SkippedChallenge { return nil } +func (m *mockChallengeIndexer) Catalog() []*challenge.Challenge { return nil } var _ challenge.ChallengeIndexer = (*mockChallengeIndexer)(nil) diff --git a/galvanize-instancer/pkg/scheduler/scheduler_test.go b/galvanize-instancer/pkg/scheduler/scheduler_test.go index d94d3b6..5168f7a 100644 --- a/galvanize-instancer/pkg/scheduler/scheduler_test.go +++ b/galvanize-instancer/pkg/scheduler/scheduler_test.go @@ -53,6 +53,7 @@ func (m *mockIndexer) GetAllUnique() []*challenge.Challenge { return nil } func (m *mockIndexer) GetAll() []*challenge.Challenge { return nil } func (m *mockIndexer) BuildIndex(string) error { return nil } func (m *mockIndexer) Skipped() []challenge.SkippedChallenge { return nil } +func (m *mockIndexer) Catalog() []*challenge.Challenge { return nil } func (m *mockIndexer) add(c *challenge.Challenge) *mockIndexer { m.challs[c.Category+"/"+c.Name] = c return m