diff --git a/.bumpversion.toml b/.bumpversion.toml index 6d289c2..7498d30 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.1.0+261031" +current_version = "1.5.0+261122" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" @@ -30,18 +30,18 @@ search = 'version = "{current_version}"' replace = 'version = "{new_version}"' [[tool.bumpversion.files]] -filename = "src/odmdm_fleet/__init__.py" +filename = "src/odmdm_connector/__init__.py" search = '__version__ = "{current_version}"' replace = '__version__ = "{new_version}"' [[tool.bumpversion.files]] -filename = "tests/test_odmdm_fleet.py" +filename = "tests/test_odmdm_connector.py" search = '__version__ == "{current_version}"' replace = '__version__ == "{new_version}"' [[tool.bumpversion.files]] filename = "uv.lock" -search = '''name = "odmdm-fleet" +search = '''name = "odmdm-connector" version = "{current_version}"''' -replace = '''name = "odmdm-fleet" +replace = '''name = "odmdm-connector" version = "{new_version}"''' diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 2e70504..0000000 --- a/.dockerignore +++ /dev/null @@ -1,55 +0,0 @@ -# General good ideas to ignore -.idea -.git -.cache -.venv - -# docker build files (so just changing them does not invalidate *all* caches) -.dockerignore -Dockerfile - -# Byte-compiled / optimized / DLL files -**/__pycache__/ -**/*.py[cod] -**/*$py.class - -# Distribution / packaging -**/.Python -**/build/ -**/develop-eggs/ -**/dist/ -**/downloads/ -**/eggs/ -**/.eggs/ -**/lib/ -**/lib64/ -**/parts/ -**/sdist/ -**/var/ -**/wheels/ -**/pip-wheel-metadata/ -**/share/python-wheels/ -**/*.egg-info/ -**/.installed.cfg -**/*.egg - -# Unit test / coverage reports -**/htmlcov/ -**/.tox/ -**/.nox/ -**/.coverage -**/.coverage.* -**/.cache -**/nosetests.xml -**/coverage.xml -**/*.cover -**/*.py,cover -**/.hypothesis/ -**/.pytest_cache/ - -# mypy -**/.mypy_cache/ -**/.ruff_cache/ -.prettier_cache -**/.dmypy.json -**/dmypy.json diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml deleted file mode 100644 index 6e69775..0000000 --- a/.github/actionlint.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# Configuration related to self-hosted runner. -self-hosted-runner: - # Labels of self-hosted runner in array of strings. - labels: - - arc-runner-set diff --git a/.github/workflows/mdm_connector.yml b/.github/workflows/mdm_connector.yml new file mode 100644 index 0000000..6b5253a --- /dev/null +++ b/.github/workflows/mdm_connector.yml @@ -0,0 +1,152 @@ +# The mdm-connector folder Deploy App's UI serves, built once for every caller: the self-contained +# file per system and the one file for Python, each started, and connector.json, as the artifact +# mdm-connector. pull_request.yml calls it on the change, push_to_main.yml on the commit it has just tagged. +on: + workflow_call: + inputs: + ref: + description: "Commit, branch or tag to build; empty builds the commit that triggered the caller" + type: string + required: false + default: "" + +permissions: + contents: read + +jobs: + # The connector as one self-contained file per system, which Deploy App's MDM page offers for + # download. PyInstaller is a build tool only; the file is packed as connector.json names it. Not signed. + # Every leg builds with uv's own Python (python-build-standalone), not the runner's. On Linux the + # file needs the glibc it was built on or newer, so that leg builds in AlmaLinux 8 (glibc 2.28). + # macos-15-intel: a browser cannot tell an Intel Mac from an Apple Silicon one, so both get a file. + one-file: + name: Self-contained file (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest, macos-15-intel] + env: + UV_PYTHON_PREFERENCE: only-managed + UV_PYTHON: "3.12" + ALMALINUX_8: almalinux:8@sha256:768bedc30fe0a536adb0a65d2eddb7caad364e514fbddd0ae9e026975f590342 + DEBIAN_11: debian:11@sha256:6f519a81440354a85eb592c5f32109ab80605f6b892455983a6f618bf87fabe9 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + with: + python-version: "3.12" + - name: Build and pack it, as README.rst says + if: runner.os != 'Linux' + run: uv run --locked --group dist python packaging/build.py + # The same command in AlmaLinux 8 with this runner's uv; the checkout is read-only in it, and copied + - name: Build and pack it on Linux, in AlmaLinux 8 + if: runner.os == 'Linux' + run: | + mkdir -p dist/mdm-connector + docker run --rm -e UV_PYTHON_PREFERENCE -e UV_PYTHON -v "$PWD:/src:ro" -v "$PWD/dist/mdm-connector:/out" \ + -v "$(command -v uv):/usr/local/bin/uv:ro" "$ALMALINUX_8" sh -euc ' + cp -r /src /work && cd /work && rm -rf .venv build dist + uv run --locked --group dist python packaging/build.py /out' + - run: echo "VERSION=$(uv version --short)" >> "$GITHUB_ENV" + # As an operator gets it: unpacked, started with nothing but its own files, writing only into a scratch home + - name: Unpack it and prove it runs, finds Fleet and serves the page + env: + HOME: ${{ runner.temp }}/home + LOCALAPPDATA: ${{ runner.temp }}/home + XDG_CONFIG_HOME: ${{ runner.temp }}/home + run: | + mkdir -p "$HOME" "$RUNNER_TEMP/unpacked" + for packed in dist/mdm-connector/*; do + case "$packed" in + *.zip) unzip -q "$packed" -d "$RUNNER_TEMP/unpacked" ;; + *.tar.gz) tar -xzf "$packed" -C "$RUNNER_TEMP/unpacked" ;; + *.exe) cp "$packed" "$RUNNER_TEMP/unpacked/odmdm-connector.exe" ;; + esac + done + cd "$RUNNER_TEMP/unpacked" + connector=./odmdm-connector + [ -f "$connector" ] || connector=./odmdm-connector.exe + test -x "$connector" + "$connector" --version | tr -d '\r' | tee version.txt + grep -Fqx "odmdm-connector, version $VERSION" version.txt + "$connector" mdms | tr -d '\r' | tr -s ' ' | tee mdms.txt + grep -Eqx 'fleet odmdm-connector [^ ]+ built in' mdms.txt + # Fleet loads, and asks for its address + if "$connector" phones 2> phones.txt; then exit 1; fi + cat phones.txt + grep -Fq 'Fleet address is missing' phones.txt + port=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])') + "$connector" web --no-browser --port "$port" > web.txt 2>&1 & + pid=$! + for _ in $(seq 100); do grep -q 'Press Ctrl+C' web.txt && break; sleep 0.2; done + cat web.txt + curl -fsS --max-time 10 "http://127.0.0.1:$port/" -o page.html + grep -Fq '' page.html + curl -fsS --max-time 10 "http://127.0.0.1:$port/app.js" -o app.js + test -s app.js + kill "$pid" + wait "$pid" || true + # The floor, proven by starting it there. The keychain loads cryptography, which --version and + # mdms never do: with a Secret Service on a session bus the page must find the keychain usable. + - name: Start it on glibc 2.28 (AlmaLinux 8, keychain included) and 2.31 (Debian 11) + if: runner.os == 'Linux' + run: | + for image in "$ALMALINUX_8" "$DEBIAN_11"; do + docker run --rm -e HOME=/tmp -v "$RUNNER_TEMP/unpacked:/c:ro" "$image" sh -euc ' + ldd --version | sed -n 1p + /c/odmdm-connector --version + /c/odmdm-connector mdms | grep "built in"' + done + docker run --rm --cap-add IPC_LOCK -e HOME=/tmp -v "$RUNNER_TEMP/unpacked:/c:ro" "$ALMALINUX_8" sh -euc ' + dnf -q -y install gnome-keyring dbus-daemon > /dev/null + dbus-run-session -- sh -euc " + printf x | gnome-keyring-daemon --unlock --components=secrets > /dev/null + /c/odmdm-connector web --no-browser --port 8080 > /tmp/web.txt 2>&1 & + for _ in \$(seq 100); do grep -q Ctrl+C /tmp/web.txt && break; sleep 0.2; done + kill \$!" + cat /tmp/web.txt + grep -q Ctrl+C /tmp/web.txt + if grep -q keychain /tmp/web.txt; then exit 1; fi' + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: connector-${{ runner.os }}-${{ runner.arch }} + path: dist/mdm-connector/ + if-no-files-found: error + + # What a deployment serves beside its UI as mdm-connector/: the four files, the one file for + # Python (README.rst, "Into a network without internet") and connector.json, as ONE artifact + mdm-connector: + name: The mdm-connector folder + needs: one-file + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + with: + python-version: "3.12" + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: connector-* + merge-multiple: true + path: dist/mdm-connector + - name: Add the one file for Python, without the demo plugin, and write connector.json + run: | + uv build --wheel --out-dir dist + uv pip install --target build/pyz --no-deps dist/odmdm_connector-*.whl + python -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o "dist/mdm-connector/odmdm-connector-$(uv version --short).pyz" + uv run --locked python packaging/manifest.py dist/mdm-connector + cat dist/mdm-connector/connector.json + jq -e '(.files | length) == 5 and .mdms == [{"name": "fleet", "title": "Fleet"}]' dist/mdm-connector/connector.json + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mdm-connector + path: dist/mdm-connector/ + if-no-files-found: error diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index e89b6bc..b6989e8 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -2,108 +2,116 @@ on: pull_request: workflow_dispatch: # Allow manual triggering +permissions: + contents: read + jobs: - # Only the bumpversion half. The library's prek job is checkout + prek-action with no venv, and - # the generated python config ends in a local mypy hook that resolves from PATH, so it cannot - # run there. Every sibling runs prek itself, after setup-python. - general-checks: - name: General checks - uses: pvarki/config-ci-library/.github/workflows/general-check.yml@main - with: - run-prek: false + # The library's general-check runs prek without a venv, and the generated python config ends in a + # local mypy hook that resolves from PATH, so prek runs here after setup-python instead. + bumpversion-check: + name: Validate .bumpversion.toml + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/validate-bumpversion@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 pre-commit: name: Run pre-commit checks runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: pvarki/config-ci-library/.github/actions/setup-python@main + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: - python-version: "3.11" + python-version: "3.12" - name: Do pre-commit checks - run: | - uv run prek run --all-files + run: uv run prek run --all-files test: - name: Run tests - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - checks: write + name: Test (${{ matrix.os }}, Python ${{ matrix.python-version }}) + runs-on: ${{ matrix.os }} strategy: + fail-fast: false matrix: - python-version: ["3.11"] + os: [ubuntu-latest, windows-latest, macos-latest] + python-version: ["3.12"] + include: + - os: ubuntu-latest + python-version: "3.11" steps: - - uses: actions/checkout@v6 - - uses: pvarki/config-ci-library/.github/actions/setup-python@main + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: python-version: ${{ matrix.python-version }} - - name: Test with pytest - run: | - uv run py.test -v --junitxml=pytest.xml - - name: Publish Test Report - uses: mikepenz/action-junit-report@v4 - if: success() || failure() # always run even if the previous step fails + - name: Test with pytest, coverage floor in pyproject.toml + run: uv run pytest -v + + # A plugin is a package of its own, found through its entry point once installed: build both + # wheels and install them the way an operator would, into a throwaway tool directory. + plugin-install: + name: Install with a plugin (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: - report_paths: "**/pytest*.xml" - detailed_summary: true - check_name: "JUnit report (local)" + python-version: "3.12" + - name: Build both wheels and install them as a tool + env: + UV_TOOL_DIR: ${{ runner.temp }}/uv-tools + UV_TOOL_BIN_DIR: ${{ runner.temp }}/uv-bin + run: | + uv build --out-dir dist + uv build --out-dir dist examples/odmdm-connector-demo + uv tool install dist/odmdm_connector-*.whl --with dist/odmdm_connector_demo-*.whl + echo "$UV_TOOL_BIN_DIR" >> "$GITHUB_PATH" + - name: Fleet is built in, the demo is found as a plugin and used + run: | + odmdm-connector mdms | tr -d '\r' | tr -s ' ' | tee mdms.txt + grep -Eqx 'fleet odmdm-connector [^ ]+ built in' mdms.txt + grep -Fqx 'demo odmdm-connector-demo 1.0.0 plugin' mdms.txt + odmdm-connector --mdm demo phones 2> plugin.txt | tee phones.txt + cat plugin.txt + grep -Fq 'a plugin from odmdm-connector-demo 1.0.0' plugin.txt + grep -Eq '^d1 +- +Pretend Phone 7' phones.txt + # The one file README.rst describes for a network without internet, run by a Python with nothing installed + - name: One file with the demo plugin inside, on Python 3.11 + run: | + uv pip install --target build/pyz --no-deps dist/odmdm_connector-*.whl dist/odmdm_connector_demo-*.whl + bare() { uv run --no-project --isolated --python 3.11 python "$@"; } + bare -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o dist/odmdm-connector.pyz + bare dist/odmdm-connector.pyz --version + # Built without keyring: the file runs, and has no keychain + bare -c "import sys; sys.path.insert(0, 'dist/odmdm-connector.pyz'); from odmdm_connector import store; assert store.platform_backend() is None" + bare dist/odmdm-connector.pyz mdms | tr -d '\r' | tr -s ' ' | tee pyz-mdms.txt + grep -Eqx 'fleet odmdm-connector [^ ]+ built in' pyz-mdms.txt + grep -Fqx 'demo odmdm-connector-demo 1.0.0 plugin' pyz-mdms.txt + bare dist/odmdm-connector.pyz --mdm demo phones 2> pyz-plugin.txt | tee pyz-phones.txt + cat pyz-plugin.txt + grep -Fq 'a plugin from odmdm-connector-demo 1.0.0' pyz-plugin.txt + grep -Eq '^d1 +- +Pretend Phone 7' pyz-phones.txt + + # The connector's files and the mdm-connector artifact, defined once in mdm_connector.yml + mdm-connector: + name: Connector files + uses: ./.github/workflows/mdm_connector.yml snyk-test: name: Run Snyk test runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: pvarki/config-ci-library/.github/actions/setup-python@main + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: python-version: "3.11" - - uses: pvarki/config-ci-library/.github/actions/snyk-test@main + - uses: pvarki/config-ci-library/.github/actions/snyk-test@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: snyk-org: deployapp-core-services snyk-token: ${{ secrets.SNYK_TOKEN }} - - docker-build-and-verify: - name: Build Docker images - runs-on: ubuntu-latest # arc-runner-set - steps: - # The base images come from Docker Hub, whose anonymous pull limit is shared across all of - # GitHub's egress, so an unauthenticated build fails at random. - - name: Log in to Docker Hub - uses: docker/login-action@v3 - with: - username: ${{ vars.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_TOKEN }} - - uses: actions/checkout@v6 - - name: Build test target - run: docker build --target test -t odmdm-fleet:test . - - name: Build production target - run: docker build --target production -t odmdm-fleet:production . - - publish: - name: Publish Docker image - needs: - [ - "general-checks", - "pre-commit", - "test", - "snyk-test", - "docker-build-and-verify", - ] - runs-on: arc-runner-set - permissions: - contents: read - packages: write - steps: - - uses: actions/checkout@v6 - - name: Publish Docker image - uses: pvarki/config-ci-library/.github/actions/publish-image@main - with: - product: odmdm-fleet - component: server - dockerhub-username: ${{ vars.DOCKERHUB_USERNAME }} - dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }} - github-token: ${{ secrets.GITHUB_TOKEN }} - acr-repo: ${{ vars.ACR_REPO }} - acr-username: ${{ vars.ACR_USERNAME }} - acr-token: ${{ secrets.ACR_TOKEN }} diff --git a/.github/workflows/push_to_main.yml b/.github/workflows/push_to_main.yml index c21aaf8..d0cc352 100644 --- a/.github/workflows/push_to_main.yml +++ b/.github/workflows/push_to_main.yml @@ -4,36 +4,108 @@ on: - main workflow_dispatch: # Allow manual triggering +permissions: + contents: read + jobs: snyk-monitor: name: Run Snyk monitor runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: pvarki/config-ci-library/.github/actions/setup-python@main + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: python-version: "3.11" - - uses: pvarki/config-ci-library/.github/actions/snyk-monitor@main + - uses: pvarki/config-ci-library/.github/actions/snyk-monitor@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: snyk-org: deployapp-core-services snyk-token: ${{ secrets.SNYK_TOKEN }} - publish: - name: Publish Docker image - runs-on: arc-runner-set + release: + name: Tag the current version and release it + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + permissions: + contents: write + packages: read + pull-requests: read + outputs: + tag: ${{ steps.tag.outputs.tag }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + - uses: pvarki/config-ci-library/.github/actions/tag-release@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + id: tag + - uses: pvarki/config-ci-library/.github/actions/release-notes@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + if: steps.tag.outputs.tag != '' + with: + ref: ${{ steps.tag.outputs.tag }} + release: ${{ steps.tag.outputs.version }} + product: odmdm-connector + attach-to-release: "true" + + # The release's mdm-connector folder, built from the tagged commit by the same workflow as a change + mdm-connector: + name: Connector files + needs: release + if: needs.release.outputs.tag != '' + uses: ./.github/workflows/mdm_connector.yml + with: + ref: ${{ github.sha }} # the tag's commit (tag-release tags only HEAD); no '+' through a checkout ref + + # The folder as ONE archive and its SHA-256 on the release: what Deploy App's UI image fetches and + # pins; and SHA256SUMS, each file's SHA-256, which the MDM page shows for the file it offers. The + # names carry no version, so that only the tag changes in the address. Assets already on the release + # are kept: a UI image may pin the archive's SHA-256, and a rebuild would not match it. + publish-mdm-connector: + name: Attach the mdm-connector folder to the release + needs: [release, mdm-connector] + runs-on: ubuntu-latest permissions: - contents: read - packages: write + contents: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ needs.release.outputs.tag }} + defaults: + run: + shell: bash # with pipefail, so that a failing tar fails the pack steps: - - uses: actions/checkout@v6 - - name: Publish Docker image - uses: pvarki/config-ci-library/.github/actions/publish-image@main + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - product: odmdm-fleet - component: server - dockerhub-username: ${{ vars.DOCKERHUB_USERNAME }} - dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }} - github-token: ${{ secrets.GITHUB_TOKEN }} - acr-repo: ${{ vars.ACR_REPO }} - acr-username: ${{ vars.ACR_USERNAME }} - acr-token: ${{ secrets.ACR_TOKEN }} + name: mdm-connector + path: mdm-connector + # The gate refuses a folder Deploy App's UI image would not unpack: a file connector.json does not + # name, anything but a plain file, a name outside its pattern. A release's assets are never replaced. + - name: Pack it as mdm-connector.tar.gz, with its SHA-256 and each file's beside it + run: | + (cd mdm-connector && jq -r '.files[] | "\(.sha256) \(.file)"' connector.json | sha256sum -c --strict) + diff <({ jq -r '.files[].file' mdm-connector/connector.json; echo connector.json; } | LC_ALL=C sort) \ + <(find mdm-connector -mindepth 1 -maxdepth 1 -printf '%f\n' | LC_ALL=C sort) + test -z "$(find mdm-connector -mindepth 1 ! -type f)" + jq -e '(.files | length > 0) and all(.files[].file; test("^[A-Za-z0-9_+-][A-Za-z0-9._+-]{0,119}$"))' \ + mdm-connector/connector.json > /dev/null + (cd mdm-connector && jq -r '.files[].file' connector.json | LC_ALL=C sort | xargs -r -d '\n' sha256sum --) > SHA256SUMS + (cd mdm-connector && sha256sum -c --strict ../SHA256SUMS) + tar --sort=name --owner=0 --group=0 --numeric-owner --mode=u=rwX,go=rX --mtime=@0 -cf - mdm-connector | gzip -n > mdm-connector.tar.gz + sha256sum mdm-connector.tar.gz | tee mdm-connector.tar.gz.sha256 + sha256sum -c --strict mdm-connector.tar.gz.sha256 + # All three or none: a rebuilt SHA256SUMS would not describe an archive already attached + - name: Attach the three to the release + run: | + assets=(mdm-connector.tar.gz mdm-connector.tar.gz.sha256 SHA256SUMS) + gh release view "$TAG" --json assets --jq '.assets[].name' > attached.txt + present=0 + for asset in "${assets[@]}"; do + if grep -Fqx "$asset" attached.txt; then present=$((present + 1)); fi + done + if [ "$present" -eq "${#assets[@]}" ]; then + echo "::warning::$TAG already has ${assets[*]}, kept as they are" + exit 0 + fi + if [ "$present" -ne 0 ]; then + echo "::error::$TAG has only some of ${assets[*]}: complete or remove them by hand, and never replace an attached archive" + exit 1 + fi + gh release upload "$TAG" "${assets[@]}" diff --git a/.gitignore b/.gitignore index 8b1dd4b..45d0186 100644 --- a/.gitignore +++ b/.gitignore @@ -138,3 +138,7 @@ dmypy.json # Pre-commit / prettier cache .prettier_cache .ruff_cache/ + +# MDM API tokens and local template copies: keep them outside the checkout, never commit them +*.token +/template*.json diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 746c1e9..9f688d8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -94,7 +94,7 @@ repos: hooks: - id: bandit stages: [pre-commit] - args: ["--exclude", ".tox,.eggs,tests"] + args: ["--exclude", ".tox,.eggs,tests,conftest.py"] - repo: local # Local to get relevant dependencies hooks: - id: mypy @@ -110,7 +110,7 @@ repos: # >>> END AUTOGENERATED SECTION - config-ci-library # Add any repo-specific hooks below this line - # Repo specific. The generated mypy hook only looks at src, and the tests are annotated too. + # Repo specific. The generated mypy hook only looks at src, and the tests, the demo plugin and packaging are annotated too. - repo: local hooks: - id: mypy-tests @@ -123,3 +123,7 @@ repos: - "--strict" - "--allow-untyped-decorators" - "tests" + - "conftest.py" + - "examples/odmdm-connector-demo/src" + - "examples/odmdm-connector-demo/tests" + - "packaging" diff --git a/.secrets.baseline b/.secrets.baseline index 1b227b5..02ee3f5 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -139,9 +139,9 @@ "filename": "tests/test_template.py", "hashed_secret": "4190096e3d9edbcb774caa4770639409d73ecac6", "is_verified": false, - "line_number": 45 + "line_number": 47 } ] }, - "generated_at": "2026-10-31T22:02:07Z" + "generated_at": "2026-11-21T04:07:40Z" } diff --git a/AGENTS.md b/AGENTS.md index 3505944..07d86cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,18 +1,165 @@ # Agent guidance -Connects FleetDM to an OpenDefence deployment's SCEP enrolment. Read `README.rst` first. +Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment. Read +`README.rst` first. ## The boundary -The deployment speaks standard SCEP and knows no MDM; this repository is the only place that knows +The deployment speaks standard SCEP and knows no MDM; this repository and the plugins beside it are +the only place that knows one, and `fleet.py` and `fleet_plugin.py` the only place here that knows Fleet. Keep it that way in both directions: - Nothing here calls the deployment's API. What crosses over is a SCEP URL, the challenge an operator copies from Deploy App, and the callsign in the certificate subject. -- Nothing Fleet-specific goes back into the deployment's repositories. A Fleet behaviour that - needs handling is handled here. +- Nothing that knows an MDM goes back into the deployment's repositories. An MDM's behaviour that + needs handling is handled in that MDM's plugin: Fleet's here. - No product knowledge in code. What a deployment installs arrives in the template. +## Layout + +The command line knows an MDM only through one contract; Fleet is the plugin built in. + +- `src/odmdm_connector/mdm.py`: the contract (`Mdm`, `Phone`, `State`, `Field`, `Step`, `MdmError`), + standard library only. +- `core.py`: the naming rules, the same for every MDM. `console.py`: the command line. Neither + imports anything from `fleet.py` or `fleet_plugin.py`: the command line gets the MDM chosen with + `--mdm` only through `plugins.load`. +- `plugins.py`: lists the entry point group `odmdm_connector.mdm` without importing anything, and + imports only the one entry point chosen. It is the only dynamic import there is. +- `testing/`: the kit for plugin authors, shipped in the package: `FakeMdm` and `contract.CHECKS`. + The repository runs the checks against the fake, Fleet over the stub, and the demo. +- `examples/odmdm-connector-demo/`: a plugin as a package of its own. CI builds it and the + connector and installs both as an operator would. +- `packaging/`: the self-contained file per system that Deploy App's MDM page offers. `build.py` + runs PyInstaller, a build tool in the `dist` dependency group only, on `launcher.py` and packs the + result; `manifest.py DIR` writes `DIR/connector.json`, the contract with Deploy App's UI (its + test: `tests/test_manifest.py`). The file names, `os`, `arch` and the order are that contract: + change them only together with Deploy App. Started without a command, the connector does what + `web` does, as a downloaded file is started by a double-click. CI builds every file with uv's own + Python (`UV_PYTHON_PREFERENCE=only-managed`), one known build on every system instead of each + runner's, and the Linux file in AlmaLinux 8, as it needs the glibc it was built on or newer. + The build is defined once, in `.github/workflows/mdm_connector.yml` (`workflow_call`), which + `pull_request.yml` calls on every change and `push_to_main.yml` on the commit it has just tagged + (by `github.sha`, so no `+` goes through a checkout ref). Besides `release`, which tags and creates + the release, only `publish-mdm-connector` there has `contents: write`: it refuses a folder that + Deploy App's UI image would refuse (a file `connector.json` does not name, anything but a plain + file, a name outside its pattern), packs the folder as `mdm-connector.tar.gz` (unpacks to + `mdm-connector/`) and attaches it with `mdm-connector.tar.gz.sha256` and `SHA256SUMS` (each file's + SHA-256 but `connector.json`'s, sorted by name), all three or none. No version in any name, as + GitHub may rename an asset with a `+`: only the tag changes in the address. Deploy App's UI image + pins that archive's SHA-256, so assets already on a release are never replaced. +- `fleet_plugin.py`: Fleet behind the contract, registered in `pyproject.toml` as `fleet`. `fleet.py`: + Fleet's HTTP dialect. `template.py` and the shipped `template.json`: what a deployment's phones need. + +## No processes + +The connector starts no process and runs no code it was given: ruff bans `subprocess`, the +`os.system`/`popen`/`exec*`/`spawn*` family, `webbrowser`, `eval` and `exec`, and +`conftest.py` at the root makes every way to start a process raise for the whole test run. A missing +feature is not a reason to shell out. + +The one exception, decided by the owner on 2026-11-21: `web` opens the page in the default browser +through `src/odmdm_connector/browser.py`, the only module ruff lets import `webbrowser` +(`per-file-ignores` in `pyproject.toml`); it starts nothing else. Ruff cannot exempt one API, so +that entry lifts every ban in the file: there `tests/test_no_processes.py`, not ruff, holds the rule. +It reads `browser.py` without importing it and fails on any import but `html`, `logging`, `os`, `sys`, +`webbrowser` and `pathlib`, on any `os` function that starts a process, and on anything of +`webbrowser` but `open` and `Error`. The address holds the page's key, +and on Linux and macOS a program's arguments can be read by other users of the computer, so the +address never goes to the opener: `browser.py` writes `open-page.html` into `store.directory()`, +mode 0600, which leads on to the address, and hands the opener that file's `file:` URI. Without a +desktop (no `DISPLAY` or `WAYLAND_DISPLAY` outside Windows and macOS) it opens nothing, as +`webbrowser` would start a text browser in the terminal. Tests replace the opener with a fake; +`conftest.py` still makes `webbrowser.open` raise in every test. + +The self-contained file of `packaging/` is PyInstaller's one-file mode: its bootloader, not the +connector's code, unpacks Python and the package into a new temporary folder and runs them as a +child process of itself, which it removes again when the connector stops. Nothing of the +connector's code changes for it, and every rule above holds inside it. + +## One dependency: keyring, for the token + +Runtime code under `src/` imports nothing but Python's standard library and the package itself, +with one exception: `store.py` imports keyring, inside `platform_backend()`, to keep the MDM token in +the system's keychain. Nothing else uses keyring, and the connector must run without it: the +one-file Python build (`.pyz`) leaves it out, and there `platform_backend()` is None and the token is held until the +connector stops. `tests/test_standard_library.py` fails on any other import, and on keyring anywhere +but there; CI runs the one file without it. The owner decided on 2026-11-21 first that the connector +goes into a network without internet as one file with no dependencies (README.rst, "Into a network +without internet"), as every dependency is one more thing to carry in and keep up, and then: "We +may have a dependency to manage the token." The operating systems' keychains cannot be reached from +the standard library without starting a process. The connector departs from the organisation's +Python template, which uses click and libadvian: the command line is argparse and Fleet is reached +with urllib. A file the package ships is read through `importlib.resources`, never beside `__file__`, +so that it is found inside the zip too. A missing feature is not a reason to add a dependency: say +it is missing and let the owner decide. Development tools are not runtime code and stay in the `dev` +group. + +## The page + +`web.py` serves the connector as a page on the operator's computer; `static/` holds its three files. +The page draws what `App` answers and decides nothing: a rule that a test of `App` cannot reach does +not belong in `web.py` or `app.js`. Setting up is a row of cards, one thing each, with a bar of three +parts (Deploy App, the MDM's title, Connect) during a first set-up; the daily work is one view of +the phones in the earlier desktop window's layout, with the browser's own `dialog` element for +giving callsigns, one phone, the settings and removing a Deploy App. Keep these when changing either: + +- Standard library only, no framework, no library and no build step: three static files. + `ThreadingHTTPServer` bound to 127.0.0.1, a daemon thread per connection, so that a connection a + browser leaves idle holds nothing up. `Page.lock` is held around every call into `App`, the state + and every action, so `App` sees one caller at a time; the static files take no lock. No timer: + `Page.state()` asks for the phones once `web.REFRESH` seconds have passed, so they are listed only + while a page is open and asking, and never beside a request. +- Every request: the Host header is `127.0.0.1:` or `localhost:` (no DNS rebinding). + The three files in `STATIC` are public code and need nothing more, so that a browser without the + key gets a page that says what to do; `/` reads no query. Everything under `/api/` carries one + header `X-ODMDM-Key` that equals the key, compared with `secrets.compare_digest`. Never a cookie: + a browser sends a cookie for 127.0.0.1 to every port of it, so any program listening on another + port would receive the key as soon as a web page sends the browser there. Every POST: the Origin + is the page's own and the body a JSON object of at most 64 kB. GET changes nothing. +- Every answer carries `web.HEADERS`: no caching, a Content-Security-Policy of `'self'` only, no + framing, no sniffing, no referrer. Hence no inline script or style, and no external resource. +- Only the three files in `STATIC` are served, by a fixed table. No path from a request reaches the + file system. +- No request log on the terminal: the first request's address holds the key. Failures go to the + app's log. +- The page builds elements with `createElement` and text nodes, never `innerHTML` with anything from + the server. The browser keeps exactly one thing, the page's key, in `localStorage`, which a + browser keeps apart for each port, so that every tab of the page has it; it is worthless once the + connector stops. Nothing else may ever be kept there: no other storage, no cookie. Every sentence it + shows comes from an answer; `app.js` adds labels, headings, the lines of the Add card that say + where Deploy App's button is, that it opens a new tab and what to have at hand, the Remove + dialog's line on what removing changes, and the sentences for a connector that refuses this + browser or does not answer. A tab waits for Deploy App only when Deploy App's button opened it, + and a card that holds nothing typed follows a Deploy App added, opened or connected in another + tab. Focus starts in the first field, else on the main button; in the Remove dialog and on the + confirm card for a new Deploy App, on Cancel. The picture of Deploy App's button on the Add card + is no control: a `span`, hidden from assistive technology. Each card and each dialog is a form whose + main button submits it; a button that cannot act is disabled, not hidden. +- Deploy App's MDM page is the address `App.mdm_page` hands in the state, opened in a new tab with + `rel="noopener noreferrer"`; the page makes no address of its own. +- A secret, the token, the settings line or the challenge, is a text input masked by the style + (`-webkit-text-security`), never `type=password`, so that no password manager offers to keep it + and sync it away. +- A settings line arrives by window message from the page that opened this one, never in the + address: the page takes it only when `event.source` is `window.opener`, and passes the message's + origin to `/api/read` and `/api/add` as `from`, where `App` takes a line only from its own Deploy + App's pages. A line typed or pasted has an empty `from`. +- `/api/name` sends the names the preview shown held, and `App` names them only if they are the + last preview that passed. The page asks for one preview at a time, a moment after the typing + stops, and shows only the answer to the last one asked; **Name** waits while one is asked. + Nothing previews again behind the operator's back. +- No answer holds the MDM token or the settings line. A secret field's value never goes to the + page: left empty, the kept one is used. The challenge is answered only where `App.challenge()` + gives it, for an MDM given it by hand. +- Known limits: the button in Deploy App talks to whatever listens on port 8737 of this computer, + so on a computer shared with other users the settings line is copied by hand instead. Another + program on this computer can slow the page down, but cannot read or drive it without the key. +- `web`, or no command at all, opens the page in the default browser through `browser.py` only, and prints the address; + `--no-browser` only prints it. The address is printed first and the browser asked from a daemon + thread as the page starts to serve, since some openers wait for the browser or never return. Deploy App's button finds the page only in the browser where the + address was opened. + ## Facts measured against a live Fleet Comments in `fleet.py` say what each request shape and wait was measured against. Keep that habit: @@ -24,7 +171,51 @@ Names already in use on live Fleets are identities, not cosmetics: the policy pr certificate template name (the Android keystore alias). Changing either duplicates the profile or strands every enrolled phone's key. -## Checks +A certificate authority is the exception: it is known by the address it serves, never by its name +(`FleetMdm.ensure_authority`), so one Fleet serves several Deploy Apps and an authority named +`RMSCEP` or typed by hand keeps working. Never look one up by a fixed name, and never repoint one: +its teams' phones would enrol into another Deploy App. Fleet keeps an authority while a certificate +template is bound to it (a foreign key without ON DELETE in Fleet 4.90.1's schema). + +## Commands + +- Setup: `uv sync` +- Test: `uv run pytest` (coverage floor: 88%, set in `pyproject.toml`). Needs no network, no Fleet + and no phone. +- Hooks, before every commit: `uv run prek run --all-files`. Once per clone: + `uv run prek install --hook-type pre-commit --hook-type commit-msg` +- Self-contained file for this computer: `uv run --locked --group dist python packaging/build.py` +- Version bump, once per pull request, in its own commit: `uv run bump-my-version bump patch|minor|major` + +## Crown jewels -`uv run pytest` needs no network, no Fleet and no phone. `uv run prek run --all-files` before -committing. +- **The MDM API token** (today a Fleet global admin token): it can change what every enrolled + phone of every team installs and trusts. The only place that reads it is `_values` in + `src/odmdm_connector/console.py`, from the file `ODMDM_TOKEN_FILE` names: a plugin field marked + secret is read only from the file `ODMDM__FILE` names, never from `--set` or a plain variable. + The chosen plugin gets it in memory; `FleetPlugin` hands it to `FleetMdm`, which sends it only as + the `Authorization` header to the MDM URL. A plugin from another package sees it too, so the + command line names that package on stderr before loading it. +- The page takes it typed, and `App` holds it in memory, by Deploy App, MDM and field, until the + connector stops. With "Remember on this computer" ticked and a keychain at hand (`App.keeps`), it + is kept in the keychain too, service `odmdm-connector`, account `::`, through + the one keyring back end `store.platform_backend()` names for the system and sets as keyring's, so + that neither `PYTHON_KEYRING_BACKEND`, keyring's configuration file nor another back end installed + chooses where it goes. A secret is looked for in memory first, then in the keychain. Connecting + with remember off, removing the Deploy App and the MDM refusing it (`MdmError.unauthorized`) all + remove the kept copy; there is no other way to forget it. Whatever a back end raises is "the + keychain did not answer", logged by its kind only. Never a plaintext fallback. +- The tool never logs it, prints it, takes it as an option or argument, or writes it to a file: only + the keychain keeps it. + Keep it that way: no `--token` option, no token in an environment variable, no token in an error + message. `.gitignore` ignores `*.token` so a token file in the checkout cannot be committed. +- **The page's key**, made at start by `odmdm-connector web` and printed once, in the address's + fragment (`/#key=…`), which a browser sends to no server: whoever has it drives the connector and + so the MDM. `app.js` takes it out of the address, keeps it in `localStorage` only once + `/api/state` accepts it (any web page can send the browser to the address with a wrong one), and + sends it only as the `X-ODMDM-Key` header to the page's own `/api/`. Never log it, never put it in + an answer, never in a cookie, a query or another program's arguments. +- **`open-page.html`** in `store.directory()`: it holds the address, key and all, while the + connector runs, so it is written mode 0600 and removed in the `web` command's `finally`, only by + a run that asked the browser: with `--no-browser`, without a desktop or on a taken port it may be + a running connector's. diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index f5d32ec..0000000 --- a/Dockerfile +++ /dev/null @@ -1,160 +0,0 @@ -# syntax=docker/dockerfile:1.1.7-experimental -############################################# -# Tox testsuite for multiple python version # -############################################# -FROM advian/tox-base:debian-bookworm AS tox -ARG PYTHON_VERSIONS="3.11 3.12" -ARG UV_VERSION="0.11.6" -RUN export RESOLVED_VERSIONS=`pyenv_resolve $PYTHON_VERSIONS` \ - && echo RESOLVED_VERSIONS=$RESOLVED_VERSIONS \ - && for pyver in $RESOLVED_VERSIONS; do pyenv install -s $pyver; done \ - && pyenv global $RESOLVED_VERSIONS \ - && pip install -U "uv==$UV_VERSION" tox tox-uv \ - && apt-get update && apt-get install -y \ - git \ - musl-dev \ - ca-certificates curl gnupg \ - && rm -rf /var/lib/apt/lists/* \ - && ln -s /usr/lib/x86_64-linux-musl/libc.so /lib/libc.musl-$(uname -m).so.1 \ - # Fix git runtime fatal: - # unsafe repository ('/app' is owned by someone else) - && git config --global --add safe.directory /app \ - && true -COPY ./uv.lock ./pyproject.toml ./README.rst ./.pre-commit-config.yaml /app/ -COPY ./docker /app/docker/ -WORKDIR /app -RUN uv sync --frozen \ - && rm -rf .venv - - -###################### -# Base builder image # -###################### -FROM python:3.11-bookworm AS builder_base -COPY --from=ghcr.io/astral-sh/uv:0.11.6 /uv /uvx /usr/local/bin/ - -ENV \ - # locale - LC_ALL=C.UTF-8 \ - # python: - PYTHONFAULTHANDLER=1 \ - PYTHONUNBUFFERED=1 \ - PYTHONHASHSEED=random \ - # pip: - PIP_NO_CACHE_DIR=off \ - PIP_DISABLE_PIP_VERSION_CHECK=on \ - PIP_DEFAULT_TIMEOUT=100 \ - PIP_INDEX_URL=https://nexus.dev.pvarki.fi/repository/python/simple \ - # uv: - UV_DEFAULT_INDEX=https://nexus.dev.pvarki.fi/repository/python/simple \ - UV_PROJECT_ENVIRONMENT=/.venv \ - UV_LINK_MODE=copy - -RUN apt-get update && apt-get install -y \ - curl \ - git \ - bash \ - build-essential \ - libffi-dev \ - libssl-dev \ - tini \ - openssh-client \ - cargo \ - pkg-config \ - && apt-get autoremove -y \ - && rm -rf /var/lib/apt/lists/* \ - # githublab ssh - && mkdir -p -m 0700 ~/.ssh && ssh-keyscan gitlab.com github.com | sort > ~/.ssh/known_hosts \ - && true - -SHELL ["/bin/bash", "-lc"] - - -# Copy only requirements, to cache them in docker layer: -WORKDIR /pysetup -COPY ./uv.lock ./pyproject.toml ./README.rst /pysetup/ -# Install runtime dependencies into /.venv (without the project itself) -RUN --mount=type=ssh uv venv /.venv \ - && echo 'source /.venv/bin/activate' >>/root/.profile \ - && uv sync --frozen --no-install-project --no-dev \ - && true - - -#################################### -# Base stage for production builds # -#################################### -FROM builder_base AS production_build -# Copy entrypoint scripts -COPY ./docker/entrypoint.sh /docker-entrypoint.sh -# Only files needed by production setup -COPY ./uv.lock ./pyproject.toml ./README.rst /app/ -COPY ./src /app/src/ -WORKDIR /app -# Build the wheel package with uv -RUN --mount=type=ssh source /.venv/bin/activate \ - && mkdir -p /tmp/wheelhouse \ - && uv build --wheel --out-dir /tmp/wheelhouse \ - && chmod a+x /docker-entrypoint.sh \ - && true - - -######################### -# Main production build # -######################### -FROM python:3.11-slim-bookworm AS production -COPY --from=production_build /tmp/wheelhouse /tmp/wheelhouse -COPY --from=production_build /docker-entrypoint.sh /docker-entrypoint.sh -WORKDIR /app -# Install system level deps for running the package (not devel versions for building wheels) -# and install the wheels we built in the previous step. -RUN --mount=type=ssh apt-get update && apt-get install -y \ - bash \ - libffi8 \ - tini \ - && apt-get autoremove -y \ - && rm -rf /var/lib/apt/lists/* \ - && chmod a+x /docker-entrypoint.sh \ - && WHEELFILE=`echo /tmp/wheelhouse/odmdm_fleet-*.whl` \ - && pip3 install --index-url https://nexus.dev.pvarki.fi/repository/python/simple "$WHEELFILE" \ - && rm -rf /tmp/wheelhouse/ \ - && true -ENTRYPOINT ["/usr/bin/tini", "--", "/docker-entrypoint.sh"] - - -##################################### -# Base stage for development builds # -##################################### -FROM builder_base AS devel_build -# Install deps -COPY . /app -WORKDIR /app -RUN --mount=type=ssh source /.venv/bin/activate \ - && uv sync --frozen \ - && true - - -############# -# Run tests # -############# -FROM devel_build AS test -WORKDIR /app -ENTRYPOINT ["/usr/bin/tini", "--", "docker/entrypoint-test.sh"] -# Re run install to get the service itself installed -RUN --mount=type=ssh source /.venv/bin/activate \ - && uv sync --frozen \ - && true - - -########### -# Hacking # -########### -FROM devel_build AS devel_shell -# Copy everything to the image -COPY . /app -WORKDIR /app -RUN apt-get update && apt-get install -y zsh jq vim \ - && sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" \ - && echo "source /root/.profile" >>/root/.zshrc \ - && pip3 install git-up \ - && true -ENTRYPOINT ["/bin/zsh", "-l"] diff --git a/README.rst b/README.rst index 8b48ab0..32f8999 100644 --- a/README.rst +++ b/README.rst @@ -1,160 +1,707 @@ -=========== -odmdm-fleet -=========== - -Connects FleetDM to an OpenDefence deployment's device enrolment. +=============== +odmdm-connector +=============== + +Connects your MDM, the mobile device management system that sets up your unit's Android phones, +to a Deploy App deployment (OpenDefence), so that the phones join Deploy App by themselves, each +under its own callsign, the name Deploy App knows a device by. Fleet (FleetDM) is built in. Any +other MDM that can do what `What an MDM needs`_ lists needs a plugin, a small Python package: +install one that exists, or write one (`Write a plugin`_). + +It is for the admin who runs a unit's MDM and is an admin in its Deploy App. It runs on that +admin's own computer, as a page in the browser or from the command line, and keeps one secret: the +MDM's API token. It: + +- sets the MDM up for one Deploy App, as far as the MDM's API allows: where phones ask for their + certificates and, with Fleet, also what they install and the policy that lets the apps use the + certificate; +- hands the MDM the challenge of each enrolment window: the secret phones must show while an + admin has enrolment open in Deploy App, which the connector holds in memory only; +- lists the phones that enrolled, and where each one's certificate is; +- gives phones their callsigns, any number at once, and asks again for the ones that failed. The deployment knows no MDM. It answers standard SCEP (RFC 8894) at ``https:///scep``, asks for a challenge that is new every time an admin opens enrolment in Deploy App, and makes the -certificate's common name the device's callsign. Everything that knows Fleet lives here: the -certificate authority, the certificate template, the apps, the device policy, the launcher icon, -and naming the phones. +certificate's common name the device's callsign. Everything that knows an MDM lives here, behind +one contract, and each MDM in a plugin of its own: Fleet's is built in (`Fleet`_), another MDM's +is a package beside the connector (`Plugins`_). -Run it from an operator's machine, never inside the deployment: it holds a Fleet API token, and +Run it from an operator's machine, never inside the deployment: it holds the MDM's API token, and something that can reach every device a unit owns has no business running next to an internet facing service. -Enrolling phones ----------------- +What an MDM needs +----------------- -Two Fleet teams: phones enrol into a preparation team and are named there, then move to the team -that gets the certificate. Naming first means the first certificate request already carries the -callsign. +An MDM fits, for managed Android phones, if an operator can do five things in it: -1. Once per deployment, and whenever the template changes:: +1. Keep one Deploy App's phones in a group of its own, with its own enrolment. +2. Send each phone's certificate request to Deploy App's SCEP URL with one challenge, the same + for every phone of an enrolment window. +3. Put a value that can be set for each phone into the certificate subject: the callsign, as the + common name. +4. Take a new challenge for each enrolment window. +5. Ask one phone for its certificate again and leave the others alone. - odmdm-fleet apply --team "Deploy App" --prep-team Preparation +A plugin does through the MDM's API what the MDM lets it do, and at least lists the phones and +names them. For what it cannot do, the connector says what to do in the MDM by hand, and changes +nothing. Fleet can do all five by API. -2. Enrol a phone into the preparation team, then name it:: +The shortest way +---------------- - odmdm-fleet plan OTTER4 +1. Get the connector. In Deploy App, as an admin, open **User Management**, then **MDM**, and + press **Install the ODMDM connector**: download the file for your computer and start it (`A + file to download`_). Or install it with uv (`Install`_) and type ``odmdm-connector``: for an + MDM other than Fleet that is the way, as the downloaded files take no plugin (`Plugins`_). +2. Its page opens in your browser. On Deploy App's MDM page press **Open for 2 hours**, then + **Open in the MDM connector**, and confirm your Deploy App on the connector's page. +3. Give what your MDM asks for, with Fleet its address, an API token and a team (`Fleet`_), and + press **Connect**. +4. Enrol the phones in your MDM, then press **Give callsigns**: with Fleet, only once every phone + has its apps (`The order that works`_). +5. Each phone gets its certificate when it next asks its MDM, with Fleet within about 15 minutes. + Close enrolment in Deploy App once the page shows every phone with its certificate: a request + that arrives after it closes is refused. + +`The page`_ says more of each step, and `Enrolling phones`_ does the same by command. + +Install +------- + +Install it with uv (https://docs.astral.sh/uv/getting-started/installation/); git must be +installed too:: + + uv tool install git+https://github.com/pvarki/python-odmdm-fleet + odmdm-connector --help + +The repository is named after Fleet, the first MDM the connector served. From a checkout, +``uv tool install .`` does the same. Installed this way it brings its one dependency, keyring, +which keeps the MDM token in this computer's keychain: Windows Credential Manager, the macOS +Keychain, or the Secret Service on Linux. Fleet is built in; for another MDM add its plugin in the +same line (`Plugins`_). + +The page +-------- - ``plan`` names the one phone in the preparation team that has no name yet. With two waiting it - names neither, because Fleet shows identical phones as identical rows and nothing tells you - which is the one in your hand. Enrol, plan, next phone. +The connector's everyday face is a page in your browser, served by this computer. Start it:: + + odmdm-connector web + +or ``odmdm-connector`` alone, as a double-click on a downloaded file does (see `A file to +download`_). It asks your default browser to open the page, prints its address, and goes on until +Ctrl+C. ``odmdm-connector web --port N`` serves it on another port than 8737. Deploy App's **Open +in the MDM connector** reaches port 8737 only, so on another port paste the settings line (`The +settings line`_) into the page instead. + +On a computer without a desktop, or with ``odmdm-connector web --no-browser``, the connector only +prints the address. If the page does not appear, or another program opens, open the printed +address yourself. That can happen with a browser installed as a snap on Linux, which may not read +the connector's own folder, on a Mac whose ``.html`` files open in another program than the +browser, and on Linux without a graphical browser, where a text browser may take the terminal: use +``--no-browser`` there. A page opened without that address says so, and goes on by itself once the +address has been opened in the same browser. Deploy App's button finds the page only in the +browser where the address was opened, so use Deploy App in your default browser, or open the +address in the browser you use Deploy App in. + +The first time, the page sets up one thing at a time, on cards under a bar of three parts: Deploy +App, the MDM, Connect. Have at hand Deploy App's MDM page, open as an admin, and what your MDM +asks for. Add the Deploy App: on its MDM page press **Open in the MDM connector**, or copy its +settings line and paste it into the page, and confirm it. Choose the MDM when more than one is +installed; a plugin is asked about first, and used only once you agree, for that package and +version. Then fill in what the MDM asks, one field to a card, with the rarely changed ones under +**More settings**: for Fleet its address, an API token and the team, which the page suggests +naming after the deployment (``golden-monkey DeployApp`` for golden-monkey.example.fi). +**Connect** sets the MDM up and ticks off its steps; it says what is left to do by hand, if +anything, and **Show the phones** goes on. If it failed it says why, and **Change the settings** +goes back. + +The daily work is one view of the phones, as wide as the window. At the top, whether Deploy App +accepts phones now and until when; once enrolment has closed, or when no opening is known, +**Open Deploy App** opens its MDM page in a new tab. Under it one row of buttons, the ways to +select, and the table: each phone's ID, callsign, model, when it joined and where its certificate +is. Click a row to select it, and double-click it, or select one and press **Details**, to see +that phone alone. The line at the bottom says what was done last and, at its right end, when the +phones were last listed: every minute while the page is open in a visible tab, or at once with +**Refresh**. **Settings** shows the MDM's settings, whether its token is kept on this computer, +and where the log is. For an MDM that can send its policy again, as Fleet can, it also offers +**Send the policy again** (see `The order that works`_): it ticks off its steps as **Connect** +does, and the phones keep their certificates and apps. The Deploy App's name at the top right +lists the Deploy Apps added, opens another, adds one or removes the one open. Each is a +connection of its own, with its own settings and its own token. + +For every batch: open enrolment in Deploy App and press **Open in the MDM connector** again, or +**New settings** and paste the line, then **Use the new settings** on the card that follows: only +then does the MDM get the new challenge. An MDM that cannot take it by API gets it by hand: the +page then shows the challenge to copy into the MDM. Let the phones +enrol, then **Give callsigns**, to the phones selected or else to every phone waiting for a name: +numbered or from a list. The preview below follows what you type, and the button, which then +reads **Name 3 phones**, names exactly the phones the preview shows, once it has passed. **Ask +again**, where the MDM can ask, asks refused or failed phones for their certificates again once +the cause is fixed. + +The MDM token is never in the settings file, the log or the page. With **Remember on this +computer** ticked, as it is each time its card is shown, it is kept in this computer's keychain, +under ``odmdm-connector``, and the page connects to the MDM at the next start without asking for +it. Without a keychain, as in the one file for Python (`Into a network without internet`_) or on +Linux where no Secret Service runs, the page says the token is kept only until the connector +stops, and asks for it after a restart: then it shows the phones of the MDM set up before, without +new settings from Deploy App. It asks for it the same way, with the MDM's reason, when the MDM no +longer accepts it, and removes the copy kept. + +To stop keeping the token on this computer, go through the MDM's settings again (**Settings**, +then **Change the Fleet settings**, or your MDM's name in Fleet's place), untick **Remember on +this computer** on the token's card and press **Connect**; or remove the Deploy App. Either +removes it from the keychain. If removing the Deploy App cannot remove it from the keychain, the +page says so: delete the ``odmdm-connector`` item of that Deploy App there by hand. + +The connector keeps what you set on the page, never the token or the challenge, in +``settings.json`` in its own folder, beside its log: ``%LOCALAPPDATA%\odmdm-connector`` on +Windows, ``~/Library/Application Support/odmdm-connector`` on macOS, ``~/.config/odmdm-connector`` +on Linux (or under ``XDG_CONFIG_HOME``). + +How the page is guarded +----------------------- + +- It listens on this computer only (127.0.0.1), and answers only a request addressed to this + computer (its Host header), so that a web page elsewhere cannot reach it through DNS rebinding. +- Its three files are public code. Everything else answers only a page that carries the key the + address printed at start holds, new at every start. The key is in the address's fragment, after + ``#``, which a browser sends to no server. The page takes it out of the address, keeps it only + once the connector accepts it, so that a page elsewhere cannot put a wrong one in its place, and + sends it with each request in a header of its own, never in a cookie, which a browser would also + send to every other program listening on this computer. +- The address is never on another program's command line, where other users of the computer could + read it: to open the browser, the connector writes a small file that leads on to it into its own + folder, readable by you alone on Linux and macOS and inside your own profile on Windows, and the + browser gets the address through that file. The file is removed when the connector stops; one + left behind by a connector that was killed holds a key that no longer works, and the next start + replaces it. +- The browser keeps exactly one thing, that key, in the page's own storage, so that every tab of + the page has it. It is worthless once the connector stops. Nothing else is ever kept there. A + browser's history may also keep the address you opened, key and all; that matters only while the + connector runs, as the next start makes a new key. +- A request that changes something must come from the page itself (its Origin header). +- **Open in the MDM connector** opens the page and hands it the settings line in a message, never in + the address. The page takes a line only from the page that opened it, and the connector only from + that Deploy App's own pages, ``https://`` or ``https://mtls.``. + +Its limits: + +- The button in Deploy App talks to whatever listens on port 8737 of this computer. On a computer + that other users share, one of them could listen there first and take the settings line: copy the + line by hand instead. A program that listens on port 8737 while the connector is not running can + also send the Deploy App tab that opened it elsewhere. +- Any web page can open the connector and offer a Deploy App of its own: read the Deploy App's name + on the confirm card before pressing the button that adds it. +- Another program on this computer can slow the page down, but without the key it can neither read + nor drive it. A program that runs as you can read the key from your browser's storage, as it can + read anything else of yours. + +A file to download +------------------ + +For an operator who has no Python, the connector is also one self-contained file per system, which +Deploy App's MDM page offers for download when the deployment serves them. Python, the connector, +the MDM built in (Fleet) and keyring are inside, so the token can be kept in the keychain. A +plugin cannot be added to these files: for another MDM, install the connector with uv, or build +the one file for Python with the plugin inside (`Into a network without internet`_). + +Started without a command, as by a double-click, the file opens the page; every command works as +above. Started so again while the page runs, it says the connector may be running already and, in +a terminal window, waits for Enter before the window closes. + +Each release has four such files and one for Python, in one archive (`Building and serving the +files`_): + +- ``odmdm-connector--windows-x64.exe``, as it is; +- ``odmdm-connector--macos-arm64.zip`` for a Mac with Apple Silicon and + ``odmdm-connector--macos-x64.zip`` for one with Intel; +- ``odmdm-connector--linux-x64.tar.gz``, which needs glibc 2.28 or newer; +- ``odmdm-connector-.pyz``, for any system with Python 3.11 or newer: without keyring, + so without a keychain (`Into a network without internet`_). + +The ``.zip`` and ``.tar.gz`` hold one executable named ``odmdm-connector``, and keep it executable +through a browser's download. Beside them, ``connector.json`` says the version, the MDMs built in, +and each file's system, size and SHA-256; Deploy App's page reads it. No file is built for Linux +or Windows on ARM: use the one for Python there, or install with uv (`Install`_). + +The files are NOT SIGNED yet, so Windows and macOS warn at the first start. On macOS it refuses to +open the file: open **System Settings**, **Privacy & Security**, and press **Open Anyway** for +``odmdm-connector``. On Windows, SmartScreen says it protected the PC: press **More info**, then +**Run anyway**; a computer that offers no **Run anyway** does not run unsigned files at all. +Before doing either, compare the file's SHA-256 with its line in the release's ``SHA256SUMS``: +Deploy App's page shows the same SHA-256 beside the download. With the file and ``SHA256SUMS`` in +one folder:: + + sha256sum -c --ignore-missing SHA256SUMS # Linux + shasum -a 256 -c --ignore-missing SHA256SUMS # macOS + Get-FileHash odmdm-connector-*.exe -Algorithm SHA256 # Windows PowerShell: compare by eye + +Building and serving the files +------------------------------ + +Build the file for the computer you are on from a checkout, with PyInstaller, a build tool kept in +a dependency group of its own. ``packaging/build.py`` holds the build and is what CI runs:: + + uv run --locked --group dist python packaging/build.py + +It writes the packed file into ``dist/mdm-connector``. CI builds it on Windows, macOS (Apple +Silicon and Intel) and Linux, starts each, adds the one file for Python, and writes the manifest +into that folder with ``uv run python packaging/manifest.py dist/mdm-connector``: the artifact +``mdm-connector`` is the folder a deployment serves. CI builds the Linux file in AlmaLinux 8 +(glibc 2.28) and starts it there, the keychain included, and in Debian 11. + +Each release carries that folder, built from the release's tag, as one archive that unpacks to +``mdm-connector/``, the archive's SHA-256 beside it, and ``SHA256SUMS``, one line per file of the +folder (``connector.json`` aside), all in the form ``sha256sum -c`` reads:: + + https://github.com/pvarki/python-odmdm-fleet/releases/download/v/mdm-connector.tar.gz + https://github.com/pvarki/python-odmdm-fleet/releases/download/v/mdm-connector.tar.gz.sha256 + https://github.com/pvarki/python-odmdm-fleet/releases/download/v/SHA256SUMS + +The ``+`` in the version is written ``%2B`` in the address, as GitHub writes it: the tag of +1.5.0+261122 is ``v1.5.0%2B261122`` there. Check an archive before unpacking it:: + + sha256sum -c mdm-connector.tar.gz.sha256 + tar -xzf mdm-connector.tar.gz + +Deploy App's UI image fetches the archive of one release, pins its SHA-256 and serves the folder +beside the app: an image refuses to build from an archive with any other SHA-256. A release's +assets are never replaced, so the SHA-256 the MDM page shows for a file is the line for that file in +the release's ``SHA256SUMS``. + +Into a network without internet +------------------------------- + +The connector can be carried in as one file, which needs nothing but Python 3.11 or newer on the +other computer. The file leaves out the connector's one dependency, keyring, and the connector +runs without it: it has no keychain, so the page asks for the MDM token at each start and keeps +it only until the connector stops. The commands read the token from its file, as always. + +Build the file from a checkout, on a computer that has uv. The wheel goes into the file whole, with +its metadata, which is how the connector finds Fleet and any plugin:: + + uv build --wheel --out-dir dist + uv pip install --target build/pyz --no-deps dist/odmdm_connector-*.whl + python3 -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o dist/odmdm-connector.pyz + +A plugin goes into the same file: build its wheel and name it in the same install line, after the +connector's. Its own dependencies are not installed, so a plugin for this file has to run on the +standard library. Start from an empty ``build/pyz`` each time, or what was installed there before +stays in the file. + +Copy ``dist/odmdm-connector.pyz`` across and run it as the command, ``py`` in place of ``python3`` +on Windows:: + + python3 odmdm-connector.pyz --version + python3 odmdm-connector.pyz mdms + python3 odmdm-connector.pyz web -3. Open enrolment in Deploy App (**User management → MDM**) and give Fleet the new challenge:: +Enrolling phones +---------------- - ODMDM_FLEET_CHALLENGE= odmdm-fleet apply --team "Deploy App" +The same work as on the page, by command. Phones enrol into the MDM's group for this Deploy App +before anybody names them, and each gets its certificate once it has a name. First set +``ODMDM_MDM`` to your MDM's name unless it is Fleet (``odmdm-connector mdms`` lists the names), +``ODMDM_DOMAIN`` to the deployment's DNS name, and what your MDM needs (`Configuration`_). -4. In Fleet, transfer the named phones to the ``Deploy App`` team. Each gets its certificate 7 to - 20 minutes later and greets its callsign in Deploy App. +1. Once per deployment, and whenever what the phones need changes. The first time, open enrolment + first, as in step 2, and give that opening's settings line in ``ODMDM_CHALLENGE``: ``apply`` + then hands the MDM that challenge too, and ``challenge`` is for the openings after it:: -Close enrolment when the last phone is in. The next opening makes a new challenge, so step 3 -comes again before the next batch. + odmdm-connector apply -Commands --------- +2. Open enrolment on Deploy App's MDM page (**User Management**, then **MDM**), copy its settings + line or its challenge, and give the MDM the new challenge. The command asks for it, and + changes nothing else:: -.. code-block:: bash + odmdm-connector challenge - odmdm-fleet apply # state what devices need; --force-policy after one joins - odmdm-fleet apply --dry-run # validate the template without touching Fleet - odmdm-fleet plan CALLSIGN # name the one phone waiting to be named - odmdm-fleet reconcile # ask again for phones named after they enrolled; run on a timer +3. Enrol phones into that group in your MDM, as many as you like, in any order. -``reconcile`` is for a single-team setup, where a phone enrols straight into the certificate team -before anyone has named it. That first request fails, Fleet gives up after three, and -``reconcile`` asks again once the phone has a name. +4. Name them, all at once or a few at a time; with Fleet, only once every phone has its apps + (`The order that works`_):: -Configuration -------------- + odmdm-connector name --all OTTER # OTTER1, OTTER2, ... in the order they enrolled + odmdm-connector name 31=OTTER4 32=OTTER5 # the MDM's id of a phone = callsign, the ids being what phones prints -All configuration is via environment variables: + Each phone gets its certificate when it next asks its MDM. ``phones`` shows where each one is. + ``resend`` asks again for a refused phone once the cause is fixed. -``ODMDM_FLEET_URL`` - Base URL of Fleet's API. +Close enrolment once ``phones`` says every phone has its certificate: a request that arrives after +it closes is refused. The next opening makes a new challenge, so step 2 comes again before the +next batch. -``ODMDM_FLEET_TOKEN_FILE`` - A file holding the Fleet API token. Changing the certificate authority's challenge needs a - global admin token, because Fleet keeps certificate authorities outside teams. +A refusal is usually a callsign that is malformed or taken, an enrolment window that has closed, +or an MDM that still has the previous opening's challenge. A callsign is never freed, not even by +removing it in Deploy App: give the phone another. A phone that is renamed after it got its +certificate has two callsigns until the old one is removed in Deploy App, which revokes it; the +connector says which. -``ODMDM_FLEET_TEAM`` - The team whose phones get the certificate. Default ``Deploy App``. +A command the MDM cannot do by API says what to do in the MDM instead, and changes nothing. +`Fleet`_ has Fleet's timing, its team and the same work done by hand in Fleet. -``ODMDM_FLEET_PREP_TEAM`` - The team phones enrol into and are named in. Empty for a single team. +Commands +-------- -``ODMDM_FLEET_TEMPLATE`` - The document saying what to install, see below. +.. code-block:: bash -``ODMDM_FLEET_DOMAIN`` - The deployment's DNS name. + odmdm-connector # the page, as web + odmdm-connector web # the page on this computer; --port N, --no-browser + odmdm-connector apply # state what the phones need; --force-policy sends the policy again + odmdm-connector apply --dry-run # read and check what would be stated, without touching the MDM + odmdm-connector challenge # give the MDM a new opening's challenge, nothing else + odmdm-connector phones # each phone's id, callsign, model, enrolment day and certificate + odmdm-connector name 31=OTTER4 32=OTTER5 # name these phones, and their certificates are asked for + odmdm-connector name --all OTTER # the same for every phone without a name, numbered + odmdm-connector resend [ID ...] # ask again; without ids, every named phone that failed + odmdm-connector mdms # the MDMs installed: fleet built in, and any plugins + +``name --all`` numbers in enrolment order from one above the highest ``OTTER`` among the +phones it sees, or from ``--start N``, 1 or more. It sees only this group's phones, and Deploy App +never gives a callsign out twice: where callsigns were used by phones no longer in the group, give +``--start`` above the highest ever used. ``name`` changes nothing at all if a callsign is +malformed, given twice or already another phone's, or if a phone is not in the group. -``ODMDM_FLEET_CHALLENGE`` - The challenge on Deploy App's MDM page. New for every enrolment window. +Configuration +------------- -``ODMDM_FLEET_KEY_ALIAS`` +The commands are configured by environment variables, which options override for one run. The +page keeps its own settings instead (`The page`_). + +``ODMDM_MDM`` + Which MDM to talk to, as ``--mdm NAME`` before the command. Default ``fleet``; ``mdms`` lists + the names. + +``ODMDM_DOMAIN`` + The deployment's DNS name, as ``--domain`` after ``apply`` and ``challenge``. + +``ODMDM_CHALLENGE`` + The settings line or the bare challenge from Deploy App's MDM page, for ``challenge`` and a + first ``apply``. New for every enrolment window. Without it, ``challenge`` asks at a hidden + prompt. It is never taken as an argument. + +``ODMDM_LOG_LEVEL`` + How much the commands log to stderr, as a whole number: 20 by default, 10 for more. For one + run, ``-vv`` before the command says 10 and ``-v`` 20. The page's own log is always at 20. + +Each MDM has settings of its own, which its plugin names. A setting ```` is read from +``ODMDM_``, or given for one run with ``--set =VALUE`` before the command; a command +says which one is missing. A secret, such as a token, is only ever read from the file that +``ODMDM__FILE`` names. Keep that file outside any checkout, readable only by you: the token +can change every enrolled phone. The tool reads it and never prints, logs or writes it. A default +may name the deployment, the first part of ``ODMDM_DOMAIN`` in lower case. Fleet's settings are +under `Fleet`_. + +The settings line +----------------- + +Deploy App's MDM page copies one line for the connector. It is the same for every MDM, and it +carries no list of names: phones are named in the MDM. Version 1 is exactly four fields +separated by whitespace:: + + ODMDM1 https://unit.example.fi/scep 0123456789abcdef0123456789abcdef 2026-11-21T14:00:00Z + +1. The mark ``ODMDM1``. +2. The SCEP URL, ``https:///`` with a plain DNS host name, and nothing else: no user + name, password, port, query, fragment or backslash. Deploy App writes ``https:///scep``. +3. The challenge: 32 lowercase hex characters. It is a secret: the tool never logs it and never + prints it on the command line. For an MDM that cannot take it by API, the page shows it for + you to copy into that MDM. +4. When the enrolment window closes, in UTC, as ``YYYY-MM-DDTHH:MM:SSZ``. + +Whitespace and line breaks before and after the line are ignored. A line with another mark or +another number of fields, a URL that is not just https, a host and a path, a malformed challenge or +time, or a window that has already closed is refused. A line that a page hands to the connector is +taken only from that Deploy App's own pages, ``https://`` or ``https://mtls.``; one +typed or pasted by hand names no page. The page takes only a whole line. The commands ``apply`` +and ``challenge`` also take a bare challenge, one word, as typed, for ``https:///scep``; +it says nothing of when the window closes. They read a value with whitespace inside it as a line, +never as a bare challenge, so a damaged paste is refused instead of being sent to the MDM, and +they refuse a line whose SCEP URL is not on ``ODMDM_DOMAIN``. ``challenge`` says until when the +window is open, in this computer's time. The line above is the shared test +vector, in ``tests/data/settings-line-v1.txt``; its window closed long ago, so the connector +refuses it as it is. + +Plugins +------- + +Fleet is built in. Another MDM comes as a plugin: a Python package of its own, by convention named +``odmdm-connector-``, that the connector finds through its entry point once it is installed +in the same environment. A plugin is code that sees the MDM token, so installing one means +trusting it as much as the connector itself. Install only one you know the source of. The page +asks before it uses a plugin, once for each package and version, and the commands that use the +MDM say on stderr which package and version it comes from. + +Add one with the same install line and ``--with`` and the plugin's package: its name if it is on a +package index, else its wheel file or its ``git+https://`` address:: + + uv tool install git+https://github.com/pvarki/python-odmdm-fleet --with + +Into a network without internet a plugin goes inside the one file for Python (`Into a network +without internet`_). + +See what is installed, without loading any of it:: + + odmdm-connector mdms + +Choose one with ``--mdm NAME`` before the command, or ``ODMDM_MDM``; the default is ``fleet``. Its +settings are given as `Configuration`_ says. A plugin's MDM may lack something Fleet can do, such +as taking the challenge by API; the command or the page then says what to do instead and changes +nothing. To write one, see `Write a plugin`_. + +Fleet +----- + +Fleet (FleetDM) works as it comes: the connector does in it by API everything `What an MDM +needs`_ lists. Fleet's behaviour as told here was measured on Fleet 4.90, and the menu names are +that version's. + +Fleet needs three things: + +- **Android MDM turned on**: Fleet's **Settings**, **Integrations**, **MDM**. Whoever runs Fleet + connects Android Enterprise there once, for all teams. +- **Fleet Premium**: teams and certificate authorities are part of it. +- **A global admin's API token.** Fleet keeps certificate authorities outside teams, so giving + one a new challenge takes a global admin. **My account**, **Get API token** gives the token of + your own sign-in, which Fleet ends after five days by default, or when you sign out; the + connector then says the token is not accepted. For a connector that stays set up, whoever runs + Fleet makes an API-only user with the role Admin for all of Fleet (**Settings**, **Users**, + **Add user**, **API-only user**), whose token does not end. + +Fleet's settings +~~~~~~~~~~~~~~~~ + +On the page these are its cards; for the commands, each is ``ODMDM_`` or ``--set``. +``--mdm-url``, ``--team`` and ``--template`` after a command that takes them say the same as +``--set mdm_url``, ``team`` and ``template``. + +``ODMDM_MDM_URL`` + The address you open Fleet at, such as ``https://fleet.example.fi``, without an API path. Only + https: the token goes with every request. + +``ODMDM_TOKEN_FILE`` + A file holding the API token. + +``ODMDM_TEAM`` + The team phones enrol into and get the certificate in. Default `` DeployApp``: + ``golden-monkey DeployApp`` for golden-monkey.example.fi. Without ``ODMDM_DOMAIN``, give the + team. A deployment set up with the earlier default keeps its team only when it is given: + ``--set team="Deploy App"``. + +``ODMDM_TEMPLATE`` + The document saying what to install, see `The template`_. Default: the one shipped with the + connector. + +``ODMDM_KEY_ALIAS`` The certificate template's name, which becomes the Android keystore alias. Default ``rmscep``, what the first deployments were set up with. Never change it for a deployment: a second key will not install over an existing alias. +A Fleet whose certificate comes from a private authority is trusted by pointing the +``SSL_CERT_FILE`` environment variable at that authority's certificate file, in PEM form, before +the connector starts. + +What Connect sets up +~~~~~~~~~~~~~~~~~~~~ + +**Connect**, or ``apply``, changes Fleet: it makes the team if it is not there, Deploy App as a +certificate authority, the team's certificate template, its policy, its apps and the **Deploy +App** launcher icon. The launcher is a web app that Google publishes for good (`What Fleet does +that you would not guess`_). Sending the policy again is a repair and makes no team. + +Each phone gets its certificate at its next check-in with Fleet, within about 15 minutes of being +named. One that Fleet has made no certificate request for yet only gets its name, which Fleet +fills in when it makes the request. Name the phones once every phone in the team has its apps: +naming can send the policy to all of them again (`The order that works`_). A phone that already +has its certificate under the name it is given is left alone, and renaming one that has its +certificate says which old callsign to revoke: remove it in Deploy App. + +Several Deploy Apps on one Fleet +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +One Fleet can serve several Deploy Apps. Each has a certificate authority of its own in Fleet and +a team of its own. The connector finds a Deploy App's authority by the address it serves, whatever +it is called, and makes one when there is none: ``ODMDM_`` and the first part of the Deploy App's +host name, in capitals, as ``ODMDM_GOLDEN_MONKEY`` for ``golden-monkey.example.fi``. Two Deploy +Apps whose host names have the same first part, such as ``unit.example.fi`` and +``unit.example.org``, would get the same authority name, the same default team and the same +launcher title, and the second is refused. Give it a team of its own and a template of its own +(`The template`_) that names another authority, ``"authority": "NAME"`` beside the certificate's +``name`` and ``subject``, in letters, digits and underscores, and another ``title`` in its +``link_app``. + +The connector never points an authority that serves one Deploy App at another. An authority made +earlier as ``RMSCEP``, or by hand, is found by its address and kept: the address has to be the +Deploy App's exactly, ``https:///scep`` with no slash after it. Once a team has its +certificate template, a challenge goes only to the authority that template is bound to, and a +team whose template is bound to an authority that serves another address is refused before +anything is changed, with both addresses said. + +The API token is a global admin's, so whoever runs the connector for one Deploy App can change +every team in that Fleet: share a Fleet only among people who trust each other with it. + The template ------------- +~~~~~~~~~~~~ -What to install is a property of the deployment, so it is a document rather than code: the apps, -their managed configuration, the Android Management API device policy, a launcher link, and the -certificate template. ``{domain}``, ``{mtls_url}`` and ``{key_alias}`` are filled in. Keys -beginning with ``_`` are comments and never reach Fleet. +With Fleet, what to install is a property of the deployment, so it is a document rather than +code: the apps, their managed configuration, the Android Management API device policy, a launcher +link, and the certificate template. ``{domain}``, ``{mtls_url}`` and ``{key_alias}`` are filled +in. Keys beginning with ``_`` are comments and never reach Fleet. +The one shipped in the package, ``src/odmdm_connector/template.json`` in the repository, is a +working one for Deploy App, with its reasoning in the comments: copy it from there to change what +a deployment installs, and give your copy as the template. The certificate subject is the contract with the deployment. Its common name becomes the callsign: -3 to 32 letters, digits or hyphens, no hyphen at either end. For named phones:: +3 to 32 letters, digits or hyphens, no hyphen at either end. It is the name ``name`` gives the +phone, optionally followed by Fleet's id for the host:: + CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART +The tool refuses any other subject; it takes ``$FLEET_VAR_HOST_END_USER_IDP_USERNAME`` in place of +the ``_LOCAL_PART`` form, which is the same text for a callsign. The shipped template uses the +first: the id travels in the certificate request, so the deployment can tell later which device a +callsign was issued to. A subject cannot change on a team that has phones, since replacing the +certificate template removes every phone's certificate, so a team set up without the id keeps the +second form in a template of its own. + +A name the phone supplies, such as its serial number, would make a leaked enrolment link enough +for an identity. + +The tool also refuses a policy that lets an app use the key without being named in +``packageNames``, lets the user pick a key for any app (``privateKeySelectionEnabled``), or +allows installs from unknown sources (an ``untrustedAppsPolicy`` that begins ``ALLOW_``, or +``installUnknownSourcesAllowed``). + The order that works --------------------- +~~~~~~~~~~~~~~~~~~~~ -Three facts about managed Android pull against each other. Each was learned by getting it wrong. +Three facts about managed Android and Fleet pull against each other. Each was learned by getting +it wrong. 1. **Apps install at enrolment and at no other time.** The team must carry them before a phone - joins. So both teams carry the **same** launcher package: a transfer to a team with another - package uninstalls the launcher and never installs the other. -2. **A profile is delivered when the profile changes, not when a phone arrives.** One uploaded - before a phone joined is never sent to it, so a first enrolment needs ``--force-policy``. + joins. A phone moved in from a team that has another launcher loses that launcher and never + gets this one. +2. **Fleet can overwrite a new phone's policy moments after sending it.** It sends a phone that + enrols the team's policy, and seconds later can write a bare one over it. It goes on showing + the policy as verified on that phone and never sends it again, so the phone has its certificate + but Chrome may not use it, and Deploy App says "Certificate Authentication Failed". ``name`` + and ``resend`` send the policy again, to every phone in the team, when a phone enrolled after + it was last sent. A phone that enrols again onto its old host keeps its old enrolment time and + is not seen: send the policy again by hand for it. By hand it is **Send the policy again** in + the page's **Settings**, ``apply --force-policy``, or deleting the policy in Fleet and + uploading it again. Sending it again is a repair and makes no team: a team Fleet lacks is + refused before anything is changed. 3. **A policy rewritten while apps are installing stops them installing.** Leave the phones alone until the apps have arrived. What Fleet does that you would not guess ----------------------------------------- - -- **A launcher web app's URL can never change.** Google publishes it permanently and Fleet cannot - delete it. The title carries the deployment's name, so a moved deployment publishes its own - launcher and leaves the old one orphaned. Google refuses a title of 30 characters or more. -- **A web app's display name is unique within a team** (409). A title in a team's setup experience - has to be removed there before it can be removed from the team. -- **A returning phone keeps its old team and its old name.** Transfer it to the preparation team - and name it again, or it asks for a name that is already taken. -- **Renaming a phone that has its certificate gives it a second callsign.** Revoke the old one in - Deploy App. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- **A launcher web app's URL can never change, and its title is taken for good.** Google publishes + it permanently and Fleet cannot delete it. The title carries the first part of the deployment's + host name, so a deployment moved to a host with another first part publishes its own launcher + and leaves the old one orphaned. One moved to a host with the same first part keeps the old + launcher, which still opens the old host: give the template's ``link_app`` another ``title``. + Fleet refuses a title already published, in any team and even in one since deleted. Google + refuses a title of 30 characters or more. +- **A phone enrols before it has a name**, so its first certificate request fails (``does not + have an IDP user``) until it is named, and naming it does not send the request again. ``name`` + resends. A resend is one more attempt, which the phone acts on at its next check-in, every 15 + minutes. +- **A returning phone keeps its old team and its old name.** Transfer it into this team if it was + in another, and give it a new name with ``name``, or it asks for a name that is already taken. It + can also come back as a new device with no name. +- **Replacing a team's certificate template locks its phones out.** Every phone deletes the + certificate it has and asks again, and the deployment refuses a name that is already taken. So + this repository never replaces one to retry a phone: ``resend`` asks for that phone alone. - **A refusal shows only as** ``SCEP enrollment failed ... failInfo: badMessageCheck`` on the - phone's certificate. Usually a bad or taken name, or Fleet still has the previous window's - challenge. Fix it, then transfer the phone out and back. - -Docker ------- - -The ``production`` target runs the CLI:: - - docker build --ssh default --target production -t odmdm-fleet:latest . - docker run --rm -e ODMDM_FLEET_URL -e ODMDM_FLEET_TOKEN_FILE=/run/token \ - -v "$PWD/fleet.token:/run/token:ro" -v "$PWD/template.json:/run/template.json:ro" \ - -e ODMDM_FLEET_TEMPLATE=/run/template.json -e ODMDM_FLEET_DOMAIN \ - odmdm-fleet:latest odmdm-fleet apply - -For the test suite in docker use the ``tox`` target, and for a development shell ``devel_shell``. + phone's certificate. For the causes see `Enrolling phones`_; for an old challenge, ``challenge`` + and then ``resend``. + +By hand in Fleet +~~~~~~~~~~~~~~~~ + +Without the connector, in Fleet's console: open the phone, **Edit user** to give it its callsign, +then under **OS settings** pick the certificate and **Resend**. Naming alone does not send the +request again. Once the phones have enrolled and their apps have arrived, delete the policy in +Fleet and upload it again: Fleet can overwrite a new phone's policy, see `The order that works`_. + +Phones already enrolled in another Fleet team: transfer them into this team in Fleet, then name +them like the rest. Apps install only at enrolment, so a transferred phone gets its certificate but +not this team's apps or launcher. For those, remove its work profile after the transfer and enrol +it again into this team. + +Write a plugin +-------------- + +A plugin makes an MDM that can do what `What an MDM needs`_ lists work with the connector. It is +one class that satisfies ``Mdm`` in ``src/odmdm_connector/mdm.py``, which is standard library +only: + +- Its class attributes are ``API_VERSION = 1``, a ``title``, the ``fields`` it needs and + ``missing``; a class without them is not used. Each field is a ``Field``: mark a token + ``secret``, one that must be given ``required``, and one rarely changed ``advanced``, which the + page shows only under **More settings**. A field's ``key``, in lower case, is its setting: + ``--set key=VALUE``, ``ODMDM_`` in capitals, and ``ODMDM__FILE`` for a secret. A + default may hold ``{deployment}``, which the connector fills in with the deployment's name, the + first label of the Deploy App's host: ``{deployment} DeployApp`` is Fleet's team. Without a + host there is no such default, so make that field ``required``. +- ``missing`` holds, for each of ``setup``, ``set_challenge``, ``ask_again`` and ``send_policy`` + the MDM cannot do, the sentence the operator reads instead; it is an empty mapping when the MDM + can do them all. The connector never calls what is listed there; called anyway, it raises + ``MdmError`` with that sentence, ``send_policy`` being ``setup`` with ``force``. +- ``__init__(values)`` takes the fields' values by key. It does not call the MDM: on a dry run a + required value may still be empty. +- ``setup(window, force, dry_run)`` yields ``Step`` objects, one whose ``done`` is false being a + step left to the operator; ``force`` sends the policy again even if unchanged. + ``set_challenge(window)`` gives the MDM a new challenge and changes nothing else. ``window`` is + the enrolment window: its SCEP URL, its challenge, and when it closes. In ``setup`` the + challenge is empty on a dry run, when none was given and when only the policy is sent again: + the MDM's own is then left as it is. +- ``phones()`` answers ``Phone`` objects, oldest first, each with a ``State``. ``name(names)`` + takes callsigns by phone id, and ``ask_again(ids)`` phone ids, none meaning every named phone + whose certificate failed or was not asked for. Both answer the lines to show, and raise + ``MdmError`` for an id that is not in the group. +- It raises only ``MdmError``. One that stops half-way through ``name`` says in ``named`` which + phones it had already named, and in ``lines`` the lines already due to the operator, such as an + old callsign to remove: the command line prints them before the error, the page lists them + under it. One raised because the MDM does not accept the secret it was given, such as a token + that has ended, sets ``unauthorized``: the page then lets go of that secret, the copy in the + keychain too, and asks for it again. +- Its sentences, in ``missing``, a ``Step``, a ``Phone``'s ``detail``, the lines and an + ``MdmError``, are shown as they are by the command line and the page alike, so they name no + command, option or button, and never hold the challenge or a secret. + +Name the package ``odmdm-connector-``, depending on ``odmdm-connector>=1.4,<2``, the first +release that has everything named above, with the class under the entry point group +``odmdm_connector.mdm``:: + + [project.entry-points."odmdm_connector.mdm"] + = "odmdm_connector_:Mdm" + +The connector ships a test kit: ``odmdm_connector.testing.contract.CHECKS``, the checks every +plugin must pass, and ``odmdm_connector.testing.FakeMdm``, an MDM in memory. Each check is given a +factory: a function that answers your MDM, configured, with at least two phones without a name in +its group, and that takes ``refuse_after=N`` to make it refuse to name any phone after N. Start +from ``examples/odmdm-connector-demo``: a pretend MDM with three phones that cannot take a +challenge by API, its own ``pyproject.toml`` and its contract test. The repository's CI builds it +and the connector, installs both and runs ``odmdm-connector --mdm demo phones``. Development ----------- - install uv: https://docs.astral.sh/uv/getting-started/installation/ -- Install project deps and pre-commit hooks:: +- Install project deps and the hooks, for commits and for commit messages:: uv sync - uv run prek install + uv run prek install --hook-type pre-commit --hook-type commit-msg uv run prek run --all-files -- Run the tests:: +- Run the tests. They fail below 88 % coverage, and they fail a test that starts a process: the + connector starts none, and imports only the standard library, keyring in ``store.py`` alone:: uv run pytest @@ -163,6 +710,6 @@ not hand edit the autogenerated section. .. _config-ci-library: https://github.com/pvarki/config-ci-library -Versioning is handled with bump-my-version_: ``bump-my-version bump ``. +Versioning is handled with bump-my-version_: ``uv run bump-my-version bump ``. .. _bump-my-version: https://github.com/callowayproject/bump-my-version diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..18538b5 --- /dev/null +++ b/conftest.py @@ -0,0 +1,48 @@ +"""Guards for the whole test run""" + +import os +import subprocess +import sys +import webbrowser +from collections.abc import Iterator +from typing import NoReturn + +import pytest + +#: Every way the standard library starts a process, as module and function names. subprocess, +#: os.popen and webbrowser end in Popen._execute_child; multiprocessing in fork_exec or CreateProcess. +STARTERS: tuple[tuple[object, tuple[str, ...]], ...] = ( + (subprocess.Popen, ("_execute_child",)), + (sys.modules.get("_posixsubprocess"), ("fork_exec",)), + (sys.modules.get("_winapi"), ("CreateProcess",)), + (webbrowser, ("open", "open_new", "open_new_tab")), + ( + os, + ( + "system", + "popen", + "fork", + "forkpty", + "posix_spawn", + "posix_spawnp", + "startfile", + *(f"exec{suffix}" for suffix in ("l", "le", "lp", "lpe", "v", "ve", "vp", "vpe")), + *(f"spawn{suffix}" for suffix in ("l", "le", "lp", "lpe", "v", "ve", "vp", "vpe")), + ), + ), +) + + +def _refuse(*args: object, **kwargs: object) -> NoReturn: + raise RuntimeError("A test started a process, and the connector never starts one") + + +@pytest.fixture(autouse=True, scope="session") +def no_process_starts() -> Iterator[None]: + """A process started anywhere, by the connector or by a library, fails the test that did it""" + with pytest.MonkeyPatch.context() as patch: + for module, names in STARTERS: + for name in names: + if module is not None and hasattr(module, name): + patch.setattr(module, name, _refuse) + yield diff --git a/docker/entrypoint-test.sh b/docker/entrypoint-test.sh deleted file mode 100755 index a983925..0000000 --- a/docker/entrypoint-test.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -l -set -e -# shellcheck disable=SC1091 -source /.venv/bin/activate -if [ "$#" -eq 0 ]; then - # Kill cache, pytest complains about it if running local and docker tests in mapped volume - find tests -type d -name '__pycache__' -print0 | xargs -0 rm -rf {} - # Make sure the service itself is installed - uv sync --frozen - # Make sure pre-commit checks were not missed because reasons. Via the init script because - # .git is not in the image and prek needs a repository. - docker/pre_commit_init.sh - # Then run the tests - pytest --junitxml=pytest.xml tests/ - # If prek does not run these, enable them - # mypy src tests - # bandit --skip=B101 -r src -else - exec "$@" -fi diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh deleted file mode 100755 index 22c2644..0000000 --- a/docker/entrypoint.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -l -set -e -if [ "$#" -eq 0 ]; then - exec odmdm-fleet --help -fi -exec "$@" diff --git a/docker/pre_commit_init.sh b/docker/pre_commit_init.sh deleted file mode 100755 index 0dc8161..0000000 --- a/docker/pre_commit_init.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -l -if [ ! -d .git ] -then - git init - git checkout -b precommit_init - git add . -fi -set -e -uv run prek install -uv run prek run --all-files diff --git a/examples/README.rst b/examples/README.rst new file mode 100644 index 0000000..cc4a6b8 --- /dev/null +++ b/examples/README.rst @@ -0,0 +1,9 @@ +======== +Examples +======== + +The example template moved into the package, so an installed connector carries it: +``src/odmdm_connector/template.json``. Copy it from there to change what a deployment installs. + +``odmdm-connector-demo/`` is a plugin, a package of its own: a pretend MDM to start a new plugin +from. See "Write a plugin" in the top-level README. diff --git a/examples/odmdm-connector-demo/README.rst b/examples/odmdm-connector-demo/README.rst new file mode 100644 index 0000000..a74b9ee --- /dev/null +++ b/examples/odmdm-connector-demo/README.rst @@ -0,0 +1,19 @@ +==================== +odmdm-connector-demo +==================== + +A pretend MDM for odmdm-connector, and the starting point for a plugin. Its three phones live in +memory, and it lacks one capability on purpose: it takes no challenge by API, so ``challenge`` +says where to paste one instead. + +Copy this folder, rename the package ``odmdm-connector-`` and the entry point, and replace +the list with calls to your MDM's API. ``tests/test_demo_contract.py`` runs the connector's +contract checks; keep it passing. + +Try it next to the connector:: + + uv build --out-dir dist + uv build --out-dir dist examples/odmdm-connector-demo + uv tool install dist/odmdm_connector-*.whl --with dist/odmdm_connector_demo-*.whl + odmdm-connector mdms + odmdm-connector --mdm demo phones diff --git a/examples/odmdm-connector-demo/pyproject.toml b/examples/odmdm-connector-demo/pyproject.toml new file mode 100644 index 0000000..3bd83b1 --- /dev/null +++ b/examples/odmdm-connector-demo/pyproject.toml @@ -0,0 +1,20 @@ +[project] +name = "odmdm-connector-demo" +version = "1.0.0" +description = "A pretend MDM for odmdm-connector: the starting point for an MDM plugin" +license = "MIT" +readme = "README.rst" +requires-python = ">=3.11,<4.0" +dependencies = [ + "odmdm-connector>=1.4,<2", +] + +[project.entry-points."odmdm_connector.mdm"] +demo = "odmdm_connector_demo:DemoMdm" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/odmdm_connector_demo"] diff --git a/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py new file mode 100644 index 0000000..a2f3a2a --- /dev/null +++ b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py @@ -0,0 +1,83 @@ +"""A pretend MDM for odmdm-connector, its phones in memory + +The starting point for a plugin: every method of the contract, odmdm_connector.mdm.Mdm, with +nothing behind it. A real plugin talks to its MDM's API where this changes a list. Each command +starts afresh, so a name given here is gone by the next command. +""" + +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import replace +from typing import ClassVar + +from odmdm_connector.mdm import SET_CHALLENGE, Field, MdmError, Phone, State, Step +from odmdm_connector.settings import Settings + +#: The states ask_again without ids picks, as the contract says +AGAIN = (State.NOT_ASKED, State.REFUSED, State.UNREACHABLE, State.FAILED) + + +class DemoMdm: + """A pretend MDM with three phones, which cannot be given a challenge by API""" + + # The contract version this plugin was written for + API_VERSION: ClassVar[int] = 1 + title: ClassVar[str] = "Demo MDM" + fields: ClassVar[tuple[Field, ...]] = ( + # Named after the deployment: the connector fills {deployment} in, golden-monkey for golden-monkey.example.fi + Field("group", "Group", default="{deployment} DeployApp", help="The group phones enrol into"), + ) + missing: ClassVar[Mapping[str, str]] = { + SET_CHALLENGE: ( + "The demo MDM takes no challenge by API: paste it in its console under Certificates > SCEP > Challenge" + ), + } + + def __init__(self, values: Mapping[str, str], refuse_after: int | None = None) -> None: + """refuse_after: for tests, the pretend MDM refuses to name more phones than that""" + self.group = values.get("group", "") + self.refuse_after = refuse_after + self.found = [ + Phone("d1", "", "Pretend Phone 7", "2026-11-01T09:00:00+00:00", State.NEEDS_NAME), + Phone("d2", "", "Pretend Phone 7", "2026-11-01T09:05:00+00:00", State.NEEDS_NAME), + Phone("d3", "OTTER1", "Pretend Tablet 2", "2026-11-01T09:10:00+00:00", State.READY), + ] + + def _known(self, ids: Sequence[str]) -> None: + unknown = [phone for phone in ids if phone not in {each.id for each in self.found}] + if unknown: + raise MdmError(f"Phone {unknown[0]} is not in the group {self.group}") + + def _waiting(self, phone: str, callsign: str) -> None: + self.found = [ + replace(each, callsign=callsign, state=State.WAITING) if each.id == phone else each for each in self.found + ] + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step(f"Group {self.group} would enrol at {window.scep_url}", True) + if not dry_run: + yield Step("Certificate template stated", True) + + def set_challenge(self, window: Settings) -> None: + raise MdmError(self.missing[SET_CHALLENGE]) + + def phones(self) -> list[Phone]: + return list(self.found) + + def name(self, names: Mapping[str, str]) -> list[str]: + self._known(list(names)) + named: dict[str, str] = {} + lines: list[str] = [] + for phone, callsign in names.items(): + if self.refuse_after is not None and len(named) >= self.refuse_after: + raise MdmError(f"The demo MDM refused to name phone {phone}", named, lines) + self._waiting(phone, callsign) + named[phone] = callsign + lines.append(f"Phone {phone} is {callsign}") + return lines + + def ask_again(self, ids: Sequence[str]) -> list[str]: + self._known(ids) + again = [each for each in self.found if each.id in ids or (not ids and each.callsign and each.state in AGAIN)] + for each in again: + self._waiting(each.id, each.callsign) + return [f"Phone {each.id}: certificate asked for again" for each in again] diff --git a/examples/odmdm-connector-demo/tests/test_demo_contract.py b/examples/odmdm-connector-demo/tests/test_demo_contract.py new file mode 100644 index 0000000..e88a9fd --- /dev/null +++ b/examples/odmdm-connector-demo/tests/test_demo_contract.py @@ -0,0 +1,16 @@ +"""The demo keeps the contract every MDM plugin keeps""" + +import pytest +from odmdm_connector_demo import DemoMdm + +from odmdm_connector.mdm import Mdm +from odmdm_connector.testing import contract + + +def _demo(refuse_after: int | None = None) -> Mdm: + return DemoMdm({}, refuse_after=refuse_after) + + +@pytest.mark.parametrize("check", contract.CHECKS, ids=lambda check: check.__name__) +def test_the_demo_keeps_the_contract(check: contract.Check) -> None: + check(_demo) diff --git a/packaging/build.py b/packaging/build.py new file mode 100644 index 0000000..6acf41f --- /dev/null +++ b/packaging/build.py @@ -0,0 +1,91 @@ +"""Build the connector as one self-contained file for this computer's system, and pack it + + uv run --group dist python packaging/build.py [OUT] + +PyInstaller, a build tool only, puts Python, the connector and keyring into one executable, +build/pyinstaller/odmdm-connector (.exe on Windows). It is packed into OUT, default +dist/mdm-connector, under the name connector.json gives it: the .exe as it is, otherwise one +executable named odmdm-connector in a .zip (macOS) or .tar.gz (Linux), with its executable bit, +which a browser's download would lose. README.rst and CI both build with this file. +""" + +import platform +import shutil +import sys +import tarfile +import zipfile +from importlib.metadata import version +from pathlib import Path + +import PyInstaller.__main__ +from manifest import file_name + +ROOT = Path(__file__).resolve().parent.parent +BUILD = ROOT / "build" / "pyinstaller" +#: --copy-metadata: the entry points, through which the connector finds Fleet. +#: --collect-submodules: the modules only an entry point names, Fleet's among them. +ARGUMENTS = ( + "--onefile", + "--name", + "odmdm-connector", + "--collect-data", + "odmdm_connector", + "--copy-metadata", + "odmdm-connector", + "--collect-submodules", + "odmdm_connector", + "--noconfirm", + "--clean", + "--distpath", + str(BUILD), + "--workpath", + str(BUILD / "work"), + "--specpath", + str(BUILD), + str(ROOT / "packaging" / "launcher.py"), +) +SYSTEMS = {"win32": "windows", "darwin": "macos", "linux": "linux"} +ARCHITECTURES = {"x86_64": "x64", "amd64": "x64", "arm64": "arm64", "aarch64": "arm64"} + + +def pack(executable: Path, out: Path, release: str, system: str, arch: str) -> Path: + """The executable in OUT under its name in connector.json, packed for its system""" + out.mkdir(parents=True, exist_ok=True) + packed = out / file_name(release, system, arch) + if system == "windows": + shutil.copyfile(executable, packed) + elif system == "macos": + member = zipfile.ZipInfo.from_file(executable, "odmdm-connector") + member.create_system = 3 # Unix, so that unzipping keeps the mode + member.external_attr = 0o100755 << 16 + with zipfile.ZipFile(packed, "w") as archive: + archive.writestr(member, executable.read_bytes()) + else: + with tarfile.open(packed, "w:gz") as archive: + archive.add(executable, "odmdm-connector", filter=_owned_by_nobody) + return packed + + +def _owned_by_nobody(member: tarfile.TarInfo) -> tarfile.TarInfo: + member.uid = member.gid = 0 + member.uname = member.gname = "" + member.mode = 0o755 + return member + + +def main(argv: list[str]) -> int: + """Build and pack for this computer, and say where the file is""" + out = Path(argv[0]) if argv else ROOT / "dist" / "mdm-connector" + system = SYSTEMS.get(sys.platform, "") + arch = ARCHITECTURES.get(platform.machine().lower(), "") + if not system or not arch: + print(f"No file is made for {sys.platform} on {platform.machine()}", file=sys.stderr) + return 1 + PyInstaller.__main__.run(list(ARGUMENTS)) + executable = BUILD / ("odmdm-connector.exe" if system == "windows" else "odmdm-connector") + print(pack(executable, out, version("odmdm-connector"), system, arch)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/packaging/launcher.py b/packaging/launcher.py new file mode 100644 index 0000000..49bc9b8 --- /dev/null +++ b/packaging/launcher.py @@ -0,0 +1,6 @@ +"""What PyInstaller starts: the connector's command line, as the installed odmdm-connector command""" + +from odmdm_connector.console import odmdm_connector_cli + +if __name__ == "__main__": + odmdm_connector_cli() diff --git a/packaging/manifest.py b/packaging/manifest.py new file mode 100644 index 0000000..8badf7c --- /dev/null +++ b/packaging/manifest.py @@ -0,0 +1,95 @@ +"""Write DIR/connector.json for the connector's files in DIR: what Deploy App's MDM page offers + + uv run python packaging/manifest.py DIR + +DIR holds what a deployment serves beside its UI as mdm-connector/: the files packaging/build.py +packed, one per system, and the one-file Python build. The manifest says the connector's version, +the MDMs built into it, read from what the package registers, and each file with its size and +SHA-256, in a fixed order. A file in DIR that is none of these is an error that names it. +""" + +import hashlib +import json +import re +import sys +from importlib.metadata import version +from pathlib import Path + +from odmdm_connector import plugins + +NAME = "connector.json" +#: Each system's file, in the manifest's order: the system, its architecture and the file's extension +FILES = ( + ("windows", "x64", ".exe"), + ("windows", "arm64", ".exe"), + ("macos", "x64", ".zip"), + ("macos", "arm64", ".zip"), + ("linux", "x64", ".tar.gz"), + ("linux", "arm64", ".tar.gz"), + ("any", "any", ".pyz"), +) +#: What Deploy App takes as a file's name: a bare name in the manifest's folder +BARE = re.compile(r"[A-Za-z0-9._+-]{1,120}") + + +class ManifestError(Exception): + """A folder that cannot be described as the contract says""" + + +def file_name(release: str, system: str, arch: str) -> str: + """The name of the connector's file for that system and architecture""" + extension = next(extension for named, machine, extension in FILES if (named, machine) == (system, arch)) + if system == "any": + return f"odmdm-connector-{release}{extension}" + return f"odmdm-connector-{release}-{system}-{arch}{extension}" + + +def built_in() -> list[dict[str, str]]: + """The MDMs built into the connector, name and title, as the package registers them""" + return [ + {"name": plugin.name, "title": plugins.load(plugin.name).title} + for plugin in plugins.installed() + if plugin.built_in + ] + + +def manifest(folder: Path, release: str) -> dict[str, object]: + """The manifest for the files in the folder, connector.json aside""" + known = {file_name(release, system, arch): (system, arch) for system, arch, _ in FILES} + found = {path.name: path for path in folder.iterdir() if path.name != NAME} + for name, path in sorted(found.items()): + if name not in known or not BARE.fullmatch(name) or not path.is_file(): + raise ManifestError(f"{path} is not one of the connector's files of version {release}") + if not found: + raise ManifestError(f"{folder} holds none of the connector's files") + files = [ + { + "os": system, + "arch": arch, + "file": name, + "size": found[name].stat().st_size, + "sha256": hashlib.sha256(found[name].read_bytes()).hexdigest(), + } + for name, (system, arch) in known.items() + if name in found + ] + return {"version": release, "mdms": built_in(), "files": files} + + +def main(argv: list[str]) -> int: + """Write the manifest into the folder named, or say why not""" + if len(argv) != 1 or not Path(argv[0]).is_dir(): + print("Give the folder of the connector's files: manifest.py DIR", file=sys.stderr) + return 2 + folder = Path(argv[0]) + try: + written = manifest(folder, version("odmdm-connector")) + except ManifestError as exc: + print(exc, file=sys.stderr) + return 1 + (folder / NAME).write_text(json.dumps(written, indent=2) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/pyproject.toml b/pyproject.toml index ed44436..80e72e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,25 +1,24 @@ [project] -name = "odmdm-fleet" -version = "0.1.0+261031" -description = "Connects FleetDM to an OpenDefence deployment's SCEP device enrolment" +name = "odmdm-connector" +version = "1.5.0+261122" +description = "Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment" authors = [ { name = "Benjam", email = "benjam@opendefence.fi" }, ] license = "MIT" readme = "README.rst" requires-python = ">=3.11,<4.0" -dependencies = [ - "libadvian>=1.4,<2.0", - "click>=8.1,<9.0", - "httpx>=0.28,<1.0", -] +dependencies = ["keyring>=25.6,<26.0"] [project.urls] homepage = "https://github.com/pvarki/python-odmdm-fleet" repository = "https://github.com/pvarki/python-odmdm-fleet" [project.scripts] -odmdm-fleet = "odmdm_fleet.console:odmdm_fleet_cli" +odmdm-connector = "odmdm_connector.console:odmdm_connector_cli" + +[project.entry-points."odmdm_connector.mdm"] +fleet = "odmdm_connector.fleet_plugin:FleetPlugin" [dependency-groups] dev = [ @@ -35,20 +34,77 @@ dev = [ "tox-uv>=1.0,<2.0", "ruff>=0.15.12", ] +dist = [ + "pyinstaller>=6.22,<7", +] [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [tool.hatch.build.targets.wheel] -packages = ["src/odmdm_fleet"] +packages = ["src/odmdm_connector"] [tool.ruff] line-length = 120 target-version = "py311" +[tool.ruff.lint] +# The connector holds a token that can reach every phone: it starts no process and runs no code +# it was given. S102 and S307 are exec and eval. +extend-select = ["TID251", "S102", "S307"] + +[tool.ruff.lint.per-file-ignores] +# The guard that makes those raise during the tests, and its test +"conftest.py" = ["TID251"] +"tests/test_no_processes.py" = ["TID251"] +# The one exception, decided by the owner: the web command opens the page in the default browser. +# The address goes through a file only the user can read, so the key is in no program's arguments. +# Ruff cannot exempt one API, so this lifts every ban here: tests/test_no_processes.py, not ruff, +# holds the rule inside browser.py: six modules, no os process start, of webbrowser open and Error. +"src/odmdm_connector/browser.py" = ["TID251"] + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"subprocess".msg = "The connector starts no process" +"asyncio.create_subprocess_exec".msg = "The connector starts no process" +"asyncio.create_subprocess_shell".msg = "The connector starts no process" +"multiprocessing".msg = "The connector starts no process" +"pty".msg = "The connector starts no process" +"webbrowser".msg = "Opening a browser starts a process: only browser.py opens the browser" +"os.system".msg = "The connector starts no process" +"os.popen".msg = "The connector starts no process" +"os.fork".msg = "The connector starts no process" +"os.forkpty".msg = "The connector starts no process" +"os.posix_spawn".msg = "The connector starts no process" +"os.posix_spawnp".msg = "The connector starts no process" +"os.startfile".msg = "The connector starts no process" +"os.execl".msg = "The connector starts no process" +"os.execle".msg = "The connector starts no process" +"os.execlp".msg = "The connector starts no process" +"os.execlpe".msg = "The connector starts no process" +"os.execv".msg = "The connector starts no process" +"os.execve".msg = "The connector starts no process" +"os.execvp".msg = "The connector starts no process" +"os.execvpe".msg = "The connector starts no process" +"os.spawnl".msg = "The connector starts no process" +"os.spawnle".msg = "The connector starts no process" +"os.spawnlp".msg = "The connector starts no process" +"os.spawnlpe".msg = "The connector starts no process" +"os.spawnv".msg = "The connector starts no process" +"os.spawnve".msg = "The connector starts no process" +"os.spawnvp".msg = "The connector starts no process" +"os.spawnvpe".msg = "The connector starts no process" +"importlib.import_module".msg = "Only plugins.load imports code, and only the chosen entry point" + [tool.mypy] strict=true +# The demo plugin's tests import it from its source, as pytest does, and the manifest's test from packaging +mypy_path="examples/odmdm-connector-demo/src:packaging" + +# A build tool, in the dist group only, and without type hints +[[tool.mypy.overrides]] +module="PyInstaller.*" +ignore_missing_imports=true [[tool.mypy.overrides]] module="tests.*" @@ -56,7 +112,9 @@ disallow_untyped_decorators=false [tool.pytest.ini_options] junit_family="xunit2" -addopts="--cov=odmdm_fleet --cov-fail-under=65 --cov-branch" +# The demo plugin, a package of its own, runs its contract tests here from its source; and packaging/manifest.py +pythonpath=["examples/odmdm-connector-demo/src", "packaging"] +addopts="--cov=odmdm_connector --cov-fail-under=88 --cov-branch" [tool.coverage.run] omit = ["tests/*"] diff --git a/src/odmdm_connector/__init__.py b/src/odmdm_connector/__init__.py new file mode 100644 index 0000000..ce54fa3 --- /dev/null +++ b/src/odmdm_connector/__init__.py @@ -0,0 +1,3 @@ +"""Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment""" + +__version__ = "1.5.0+261122" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/src/odmdm_connector/__main__.py b/src/odmdm_connector/__main__.py new file mode 100644 index 0000000..4c493b2 --- /dev/null +++ b/src/odmdm_connector/__main__.py @@ -0,0 +1,5 @@ +"""python -m odmdm_connector, the same as the odmdm-connector command""" + +from odmdm_connector.console import odmdm_connector_cli + +odmdm_connector_cli() diff --git a/src/odmdm_connector/app.py b/src/odmdm_connector/app.py new file mode 100644 index 0000000..de8d66d --- /dev/null +++ b/src/odmdm_connector/app.py @@ -0,0 +1,1100 @@ +"""The connector without a command line: what the page shows and does, with no user interface in it + +The App works with several Deploy Apps, each a connection by the host of its SCEP URL, and with one +of them at a time: the active one, whose MDM, enrolment window and phones it holds. + +A view calls an App and renders the plain data it answers: a Banner, Rows, a Form, a Preview, a +Detail and Results. Work that talks to the MDM runs on the App's one worker thread, and its Results +wait in a queue that the view drains on a timer with drain(), which is also where the App takes +them in. The App never touches a user interface and a view never touches the network or the file +system. Time is passed in. + +Every failure the operator meets is one sentence: an AppError raised at once, or a Result's error. +""" + +import datetime +import logging +import math +import queue +import threading +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field, replace +from enum import Enum +from logging.handlers import RotatingFileHandler +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit + +from . import core, plugins, settings, store +from .mdm import ASK_AGAIN, SEND_POLICY, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, Phone, State, Step +from .settings import Settings + +LOGGER = logging.getLogger(__name__) + +#: How long before the window closes the banner warns +CLOSING = datetime.timedelta(minutes=10) +#: A phone that joined this recently may still be installing its apps +RECENT = datetime.timedelta(minutes=10) +#: The states of a phone whose certificate failed, which asking again or another callsign may cure +FAILED = (State.NOT_ASKED, State.REFUSED, State.UNREACHABLE, State.FAILED) + + +class AppError(Exception): + """What the operator asked cannot be done, said in one sentence""" + + +class Level(Enum): + """How the banner reads""" + + #: No enrolment window known yet + NONE = "none" + OPEN = "open" + #: Closing within ten minutes + CLOSING = "closing" + CLOSED = "closed" + + +@dataclass(frozen=True) +class Banner: + level: Level + text: str + #: The same in a few words, beside the Deploy App's name in a list of them + short: str + + +@dataclass(frozen=True) +class DeployApp: + """A connection as the list of them shows it""" + + host: str + #: What the banner would say of it + banner: Banner + active: bool + + +@dataclass(frozen=True) +class Reading: + """What a settings line says, before it is taken""" + + host: str + #: Until when that Deploy App accepts phones, as the banner says it + until: str + #: Whether a connection for that Deploy App is saved already + known: bool + + +@dataclass(frozen=True) +class Row: + """One phone as the table shows it""" + + id: str + #: Empty while nobody has named it + callsign: str + phone: str + joined: str + #: The state's sentence and the plugin's words + certificate: str + #: It has no callsign yet + waiting: bool + #: Its certificate was refused or failed: ask it again, or give it another callsign + failed: bool + #: It has its certificate + ready: bool + #: Asking it again can help, and the MDM can ask + askable: bool + + +@dataclass(frozen=True) +class FieldValue: + """A field of the chosen MDM and its value now; a secret's as typed, or as kept in the keychain""" + + field: Field + value: str + #: A secret kept in this computer's keychain, not only held until the connector stops + remembered: bool = False + + +@dataclass(frozen=True) +class Form: + """What setup asks for the chosen MDM""" + + name: str + title: str + fields: tuple[FieldValue, ...] + + +@dataclass(frozen=True) +class PreviewRow: + id: str + phone: str + joined: str + callsign: str + #: Why this one cannot be named, empty when it can + refusal: str + + +@dataclass(frozen=True) +class Preview: + """What naming would do, and every reason it cannot""" + + rows: tuple[PreviewRow, ...] + #: Why the batch as a whole cannot be named, empty when it can + refusal: str = "" + #: Said before naming, without stopping it + warning: str = "" + + @property + def ok(self) -> bool: + return bool(self.rows) and not self.refusal and not any(row.refusal for row in self.rows) + + @property + def names(self) -> dict[str, str]: + return {row.id: row.callsign for row in self.rows} + + @property + def button(self) -> str: + return f"Name {_count(len(self.rows), 'phone')}" + + +@dataclass(frozen=True) +class Detail: + """One phone, with what the app itself knows""" + + id: str + callsign: str + phone: str + joined: str + #: The state's sentence + state: str + #: The plugin's own words, may be empty + detail: str + #: Whether Deploy App accepts phones now, as the banner says it + window: str + can_ask_again: bool + + +class Job(Enum): + """What the worker was asked to do""" + + SETUP = "setup" + CHALLENGE = "challenge" + PHONES = "phones" + NAME = "name" + ASK_AGAIN = "ask again" + #: Setup again with the policy sent even if unchanged + POLICY = "policy" + + +@dataclass(frozen=True) +class Result: + """A job done; error is its one sentence when it failed""" + + job: Job + error: str = "" + lines: tuple[str, ...] = () + steps: tuple[Step, ...] = () + phones: tuple[Phone, ...] | None = None + #: The phones named, by id, also when naming stopped half-way + named: dict[str, str] = field(default_factory=dict) + #: The Deploy App the job was for, which may no longer be the active one + host: str = "" + #: The MDM did not accept its secret: the operator has to type it again + unauthorized: bool = False + #: The MDM that did the job, so that a refusal of an MDM no longer held drops nothing + by: object = field(default=None, compare=False, repr=False) + + +def _askable(phone: Phone) -> bool: + """Whether asking again can help: it has a callsign, and its certificate failed or is still asked for + + A phone that has its certificate is left alone: asked again under the name it holds, it is refused as taken. + """ + return bool(phone.callsign) and (phone.state in FAILED or phone.state is State.WAITING) + + +def _count(number: int, noun: str) -> str: + return f"{number} {noun}{'' if number == 1 else 's'}" + + +def _sentence(text: str) -> str: + return text if text.endswith(".") else f"{text}." + + +def _banner(host: str, closes: datetime.datetime | None, now: datetime.datetime) -> Banner: + """Whether the Deploy App accepts phones, in the operator's time""" + if closes is None or not host: + return Banner( + Level.NONE, + "On the MDM page of Deploy App, press Open in the MDM connector to let phones enrol.", + "no enrolment window known", + ) + at = closes.astimezone(now.tzinfo).strftime("%H:%M") + if now >= closes: + return Banner( + Level.CLOSED, + f"Enrolment closed at {at}. Open enrolment again on the MDM page of Deploy App, " + "then press Open in the MDM connector there.", + f"enrolment closed at {at}", + ) + if closes - now <= CLOSING: + left = _count(math.ceil((closes - now).total_seconds() / 60), "minute") + return Banner( + Level.CLOSING, + f"Deploy App {host} accepts phones until {at}, {left} from now", + f"enrolment open until {at}, {left} left", + ) + return Banner(Level.OPEN, f"Deploy App {host} accepts phones until {at}", f"enrolment open until {at}") + + +def _admin(host: str) -> str: + """Where the Deploy App's admin pages are, its MDM page among them: the mtls. name of the deployment""" + return f"https://mtls.{host}" + + +def _read(text: str, now: datetime.datetime, sender: str) -> tuple[Settings, str]: + """The line's enrolment window and its Deploy App's host + + sender is the origin of the page that sent the line, such as https://mtls.unit.example.fi, or + empty for a line typed or pasted by hand. A line is taken only from its own Deploy App's pages. + """ + try: + window = settings.parse(text, now) + except settings.SettingsError as exc: + raise AppError(str(exc)) from exc + host = urlsplit(window.scep_url).hostname or "" + if sender and sender not in (f"https://{host}", _admin(host)): + raise AppError( + f"These settings are for Deploy App {host}, but the page that sent them is {sender}: " + "use the button on that Deploy App's own MDM page." + ) + return window, host + + +class Redact(logging.Formatter): + """Formats a log line, tracebacks included, with every secret it was told of blanked out""" + + def __init__(self) -> None: + super().__init__("%(asctime)s %(levelname)s %(name)s: %(message)s") + self.secrets: set[str] = set() + + def add(self, secret: str) -> None: + if secret: + self.secrets.add(secret) + + def scrub(self, text: str) -> str: + """The text with every secret blanked out""" + for secret in self.secrets: + text = text.replace(secret, "[secret]") + return text + + def format(self, record: logging.LogRecord) -> str: + return self.scrub(super().format(record)) + + +def open_log(directory: Path, redact: Redact) -> Path: + """Log to a file in the directory, through redact, and answer its path + + The handlers already there, such as the command line's on stderr, go through redact too. + """ + for handler in logging.getLogger().handlers: + handler.setFormatter(redact) + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + path = directory / "odmdm-connector.log" + handler = RotatingFileHandler(path, maxBytes=1_000_000, backupCount=2, encoding="utf-8") + handler.setFormatter(redact) + logging.getLogger().addHandler(handler) + logging.getLogger().setLevel(logging.INFO) + return path + + +class Worker: + """Runs jobs one at a time, in order, on one thread of its own; their results wait in a queue""" + + def __init__(self) -> None: + self._jobs: queue.Queue[Callable[[], Result] | None] = queue.Queue() + self.results: queue.Queue[Result] = queue.Queue() + threading.Thread(target=self._run, name="odmdm-connector-mdm", daemon=True).start() + + def _run(self) -> None: + while True: + job = self._jobs.get() + try: + if job is None: + return + self.results.put(job()) + finally: + self._jobs.task_done() + + def submit(self, job: Callable[[], Result]) -> None: + """job must not raise""" + self._jobs.put(job) + + def wait(self) -> None: + """Until every job submitted has finished""" + self._jobs.join() + + def stop(self) -> None: + self._jobs.put(None) + + +def _run(job: Job, work: Callable[[], Result], log_path: Path) -> Result: + """The work's result, or its failure as one sentence""" + try: + return work() + except MdmError as exc: + LOGGER.warning("%s failed: %s", job.value, exc) + return Result(job, error=str(exc), lines=tuple(exc.lines), named=exc.named, unauthorized=exc.unauthorized) + except OSError: + LOGGER.exception("%s failed", job.value) + return Result(job, error="Cannot reach the MDM.") + except Exception: # A plugin's bug reaches the operator as a sentence and leaves the worker running + LOGGER.exception("%s failed", job.value) + return Result(job, error=f"The MDM plugin failed; the log says more: {log_path}") + + +def _setup(mdm: Mdm, window: Settings, seen: Callable[[tuple[Step, ...]], None], force: bool = False) -> Result: + """The MDM's setup, each step shown as it is done, with the steps done before it stopped if it did + + force: the policy is sent again even if unchanged, as a POLICY job. + """ + job = Job.POLICY if force else Job.SETUP + steps: list[Step] = [] + try: + for step in mdm.setup(window, force=force): + steps.append(step) + seen(tuple(steps)) + except MdmError as exc: + LOGGER.warning("%s failed: %s", job.value, exc) + return Result(job, error=str(exc), steps=tuple(steps), unauthorized=exc.unauthorized) + return Result(job, steps=tuple(steps)) + + +def _name(mdm: Mdm, wanted: list[tuple[str, str]]) -> Result: + """Check the names against the phones as they are now, then name them""" + refused = core.refusal(mdm.phones(), wanted) + if refused: + return Result(Job.NAME, error=f"Nothing named: {refused}. Refresh and give callsigns again.") + return Result(Job.NAME, lines=tuple(mdm.name(dict(wanted))), named=dict(wanted)) + + +class App: + """The connector for one operator, as the page drives it""" + + def __init__( + self, + settings_store: store.Store, + *, + installed: Callable[[], list[plugins.Plugin]] = plugins.installed, + load: Callable[[str], type[Mdm]] = plugins.load, + redact: Redact | None = None, + log_path: Path = Path("odmdm-connector.log"), + keychain: store.Keychain | None = None, + ) -> None: + self.store = settings_store + #: Where a secret is kept between runs when the operator says remember; none without one + self.keychain = keychain if keychain is not None else store.Keychain(None) + #: The secrets typed, or taken from the keychain, since the start, by Deploy App, MDM and field + self._secrets: dict[tuple[str, str, str], str] = {} + #: Whether the keychain keeps each one, as read once, so that the keychain is asked again only after a + #: change: a keychain may ask the operator before it answers, and every request would wait for that + self._kept: dict[tuple[str, str, str], bool] = {} + self.redact = redact or Redact() + self.log_path = log_path + self._installed = installed + self._load_plugin = load + self.worker = Worker() + #: The last thing to tell the operator + self.status = "" + #: Every line the MDM handed back for the last naming or asking again, while status is about it + self.lines: tuple[str, ...] = () + try: + self.saved = settings_store.load() + except store.StoreError as exc: + self.saved = store.Saved() + self.status = str(exc) + self.mdm: Mdm | None = None + self.mdm_class: type[Mdm] | None = None + #: The enrolment window last pasted, challenge and all, in memory only + self.window: Settings | None = None + self.phones: list[Phone] = [] + #: Whether the MDM held now has listed its phones, so that none means none + self._listed = False + self._passed: dict[str, str] | None = None + #: The steps the setup under way has done so far, as the worker hands them over one by one + self._progress: tuple[Step, ...] = () + self._pending = dict.fromkeys(Job, 0) + # Say at once why the MDM set up before is not connected: its secrets went with the last run + if not self.status: + self.status = self._take_up() + + @classmethod + def default(cls) -> "App": + """The app on this computer: its settings file and log in the connector's own directory, and its keychain""" + redact = Redact() + log_path = open_log(store.directory(), redact) + keychain = store.Keychain(store.platform_backend()) + return cls(store.Store(store.directory()), redact=redact, log_path=log_path, keychain=keychain) + + @property + def keeps(self) -> bool: + """Whether a secret can be kept in this computer's keychain""" + return self.keychain.usable + + def close(self) -> None: + self.worker.stop() + + def _save(self, changed: store.Saved) -> None: + """Write the settings, and only then hold them""" + try: + self.store.save(changed) + except store.StoreError as exc: + raise AppError(str(exc)) from exc + self.saved = changed + + @property + def conn(self) -> store.Connection: + """The active connection, or an empty one when none is active""" + return self.saved.connections.get(self.saved.active, store.Connection()) + + def _save_conn(self, **changes: Any) -> None: + """Write the active connection with the changes""" + if not self.saved.active: + raise AppError("Add the Deploy App first: on its MDM page, press Open in the MDM connector.") + connections = {**self.saved.connections, self.saved.active: replace(self.conn, **changes)} + self._save(replace(self.saved, connections=connections)) + + def _drop(self) -> None: + """Let go of what is held for the active connection: its MDM, its enrolment window and its phones""" + self.mdm = self.mdm_class = self.window = self._passed = None + self.phones, self._listed, self._progress = [], False, () + + def _say(self, sentence: str, *lines: str) -> str: + """Say the sentence, with lines under it; what was said, the lines first""" + self.status, self.lines = sentence, lines + return " ".join([*lines, sentence]) + + # The MDM + + def mdms(self) -> list[plugins.Plugin]: + """The MDMs installed, none of them imported""" + try: + return self._installed() + except plugins.PluginError as exc: + raise AppError(str(exc)) from exc + + def _plugin(self, name: str) -> plugins.Plugin: + for plugin in self.mdms(): + if plugin.name == name: + return plugin + raise AppError(f"No MDM named {name} is installed.") + + def approval(self, name: str) -> str: + """What to ask before the MDM's plugin is used; empty when it is built in or approved as it is""" + plugin = self._plugin(name) + if plugin.built_in or f"{plugin.name} {plugin.package} {plugin.version}" in self.saved.approved: + return "" + return ( + f"The MDM {name} comes from the package {plugin.package} {plugin.version}, not with this app. " + "A plugin is code that sees the MDM token: use it only if you trust where it comes from." + ) + + def approve(self, name: str) -> None: + plugin = self._plugin(name) + others = [each for each in self.saved.approved if each.split()[0] != plugin.name] + self._save(replace(self.saved, approved=[*others, f"{plugin.name} {plugin.package} {plugin.version}"])) + LOGGER.info("Plugin approved: %s %s %s", plugin.name, plugin.package, plugin.version) + + def _class(self, name: str) -> type[Mdm]: + """The MDM's class, importing its plugin and no other, once it is approved""" + if self.approval(name): + raise AppError(f"The MDM {name} is a plugin that has not been approved in this app.") + try: + return self._load_plugin(name) + except plugins.PluginError as exc: + raise AppError(str(exc)) from exc + + @staticmethod + def _account(host: str, name: str, item: Field) -> tuple[str, str, str]: + """Whose secret it is: per Deploy App, so that two never share a token by accident""" + return host, name, item.key + + def _look(self, account: tuple[str, str, str]) -> None: + """Read the account's secret from the keychain, once, and hold it if none is held""" + if account in self._kept: + return + kept = self.keychain.get(":".join(account)) + self._kept[account] = bool(kept) + if kept and not self._secrets.get(account): + self._secrets[account] = kept + + def _secret(self, name: str, item: Field) -> str: + """The active Deploy App's secret: as held since the start, else as kept in the keychain""" + account = self._account(self.saved.active, name, item) + self._look(account) + return self._secrets.get(account, "") + + def _keep(self, name: str, chosen: type[Mdm], remember: bool) -> list[str]: + """Keep the active Deploy App's secrets in the keychain if remember, else remove any kept + + What to say of a secret the keychain did not take. + """ + notices = [] + for item in chosen.fields: + if not item.secret: + continue + account = self._account(self.saved.active, name, item) + secret = self._secrets.get(account, "") + self._kept.pop(account, None) + if not (remember and secret and self.keeps): + self.keychain.forget(":".join(account)) + elif not self.keychain.keep(":".join(account), secret): + notices.append( + f"This computer's keychain cannot be used, so the {item.label} is kept only until the connector " + "stops." + ) + return notices + + def _forget(self, host: str, name: str) -> bool: + """Let go of the secrets of the Deploy App's MDM, held and kept; whether the keychain holds none of them""" + self._secrets = {account: secret for account, secret in self._secrets.items() if account[0] != host} + self._kept = {account: kept for account, kept in self._kept.items() if account[0] != host} + if not name or not self.keeps: + return True + try: + chosen = self._class(name) + except AppError: + return False + accounts = [":".join(self._account(host, name, item)) for item in chosen.fields if item.secret] + left = [account for account in accounts if not self.keychain.forget(account)] + return not left + + def _default(self, item: Field) -> str: + """The field's default for the active Deploy App, the deployment's name filled in""" + return item.default_for(self.saved.active) + + def form(self, name: str) -> Form: + """The MDM's fields with their values: saved ones if it is the active connection's MDM, else the defaults + + Each field's default is the active Deploy App's. + """ + chosen = self._class(name) + saved = self.conn.values if self.conn.mdm == name else {} + fields = [replace(item, default=self._default(item)) for item in chosen.fields] + return Form( + name, + chosen.title, + tuple( + FieldValue(item, self._secret(name, item), self._remembered(name, item)) + if item.secret + else FieldValue(item, saved.get(item.key, item.default)) + for item in fields + ), + ) + + def _remembered(self, name: str, item: Field) -> bool: + """Whether the active Deploy App's secret is kept in the keychain""" + account = self._account(self.saved.active, name, item) + self._look(account) + return self.keeps and self._kept[account] + + def _make(self, name: str, chosen: type[Mdm]) -> Mdm: + """The MDM, made from the saved values and the secrets, and held""" + values = {} + for item in chosen.fields: + values[item.key] = ( + self._secret(name, item) if item.secret else self.conn.values.get(item.key, self._default(item)) + ) + if item.secret: + self.redact.add(values[item.key]) + try: + mdm = chosen(values) + except MdmError as exc: + raise AppError(str(exc)) from exc + self.mdm, self.mdm_class, self._listed = mdm, chosen, False + return mdm + + def _take_up(self) -> str: + """Take up the active connection's MDM, if still approved and its secrets are at hand; why not, or empty""" + name = self.conn.mdm + if not name: + return "" + try: + chosen = self._class(name) + lacking = [item.label for item in chosen.fields if item.secret and not self._secret(name, item)] + if lacking: + kept = "it is" if len(lacking) == 1 else "they are" + if self.keeps: + return f"Type the {' and '.join(lacking)} again to connect: {kept} not kept on this computer." + return f"Type the {' and '.join(lacking)} again to connect: {kept} kept only while the connector runs." + self._make(name, chosen) + except AppError as exc: + return str(exc) + return "" + + def connect(self, name: str, values: Mapping[str, str], remember: bool = True) -> str: + """Use this MDM with these values: secrets held in memory, the rest in the settings file + + A secret is kept in the keychain too if remember and one can be used; not remembered, any + copy kept there is removed. A secret given empty stands for the one held or kept for this + Deploy App and MDM only when every other value given is the one saved for it, so that a kept + secret never goes to an address it was not kept for. + + With an enrolment window held, its setup runs on the worker and its Result carries the steps. + Without one, an MDM already set up for the Deploy App is only connected, so its phones can be + seen on any day; one not set up yet is refused, as setup needs the window. + """ + chosen = self._class(name) + if not self.saved.active: + raise AppError("Add the Deploy App first: on its MDM page, press Open in the MDM connector.") + if self.window is None and self.conn.mdm != name: + raise AppError( + f"To set {chosen.title} up, open enrolment on the MDM page of Deploy App {self.saved.active}, " + "then press Open in the MDM connector there." + ) + plain = {item.key: values.get(item.key, self._default(item)) for item in chosen.fields if not item.secret} + saved = { + item.key: self.conn.values.get(item.key, self._default(item)) for item in chosen.fields if not item.secret + } + same = self.conn.mdm == name and plain == saved + given = dict(plain) + for item in chosen.fields: + if not item.secret: + continue + given[item.key] = values.get(item.key, "") + if not given[item.key].isprintable(): + raise AppError( + f"The {item.label} holds a line break or another character that cannot be part of it: copy it again." + ) + if not given[item.key] and self._secret(name, item): + if not same: + raise AppError(f"Type the {item.label} again: the settings changed.") + given[item.key] = self._secret(name, item) + for item in chosen.fields: + if item.required and not given[item.key].strip(): + raise AppError(f"Fill in {item.label}.") + self._save_conn(mdm=name, values=plain) + for item in chosen.fields: + if item.secret: + self._secrets[self._account(self.saved.active, name, item)] = given[item.key] + mdm, window = self._make(name, chosen), self.window + notices = self._keep(name, chosen, remember) + if window is None: + LOGGER.info("Connected to the MDM %s for Deploy App %s", name, self.saved.active) + return self._say(f"Connected to {chosen.title} for Deploy App {self.saved.active}.", *notices) + LOGGER.info("Connecting to the MDM %s for Deploy App %s", name, self.saved.active) + if SETUP in chosen.missing: + self._submit(Job.SETUP, lambda: Result(Job.SETUP, steps=(Step(chosen.missing[SETUP], False),))) + else: + self._progress = () + self._submit(Job.SETUP, lambda: _setup(mdm, window, self._show)) + return self._say(f"Setting {chosen.title} up for Deploy App {self.saved.active}.", *notices) + + @property + def connected(self) -> bool: + return self.mdm is not None + + def policy_note(self) -> str: + """What sending the policy again does, while the MDM connected can; empty when it cannot""" + if self.mdm is None or SETUP in self.mdm.missing or SEND_POLICY in self.mdm.missing: + return "" + return ( + "For a phone whose browser refuses its certificate: the MDM sends the policy to every phone again. " + "Phones keep their certificates. Not while phones are still installing apps: it stops their installs." + ) + + def send_policy(self) -> str: + """Set the MDM up again with its policy sent even if unchanged, on the worker, as apply --force-policy does + + For a phone whose policy the MDM overwrote. No challenge goes with it, so a window pasted + earlier never takes the place of a newer one, and enrolment need not be open. One at a + time: asked again while it or a setup waits or runs, nothing more is sent, as every send + rewrites the policy and a policy rewritten again and again stops the phones' installs. + """ + if self.mdm is None: + raise AppError("Connect to the MDM first.") + for capability in (SETUP, SEND_POLICY): + if capability in self.mdm.missing: + raise AppError(self.mdm.missing[capability]) + said = f"Sending the policy again for Deploy App {self.saved.active}." + if self._pending[Job.POLICY] or self._pending[Job.SETUP]: + return self._say(said) + mdm = self.mdm + window = Settings(self.window.scep_url if self.window else f"https://{self.saved.active}/scep", "") + self._progress = () + self._submit(Job.POLICY, lambda: _setup(mdm, window, self._show, force=True)) + return self._say(said) + + # The Deploy Apps + + def connections(self, now: datetime.datetime) -> list[DeployApp]: + """The Deploy Apps saved, in the order they were added""" + return [ + DeployApp( + host, + self.banner(now) if host == self.saved.active else _banner(host, store.closes(each), now), + host == self.saved.active, + ) + for host, each in self.saved.connections.items() + ] + + def read_settings(self, text: str, now: datetime.datetime, sender: str = "") -> Reading: + """What the settings line says, taking nothing from it; sender as for paste_settings""" + window, host = _read(text, now, sender) + return Reading(host, _sentence(_banner(host, window.closes, now).text), host in self.saved.connections) + + def _activate(self, host: str, connection: store.Connection) -> bool: + """Save the connection and make it the active one; whether that changed which one is""" + changed = host != self.saved.active + self._save(replace(self.saved, connections={**self.saved.connections, host: connection}, active=host)) + if changed: + self._drop() + LOGGER.info("Working with Deploy App %s", host) + return changed + + def open(self, host: str, now: datetime.datetime) -> str: + """Make the saved connection to the Deploy App the active one, and take up its MDM""" + if host not in self.saved.connections: + raise AppError(f"There is no Deploy App {host} in this app.") + changed = self._activate(host, self.saved.connections[host]) + failed = self._take_up() if changed or self.mdm is None else "" + return self._say(" ".join(filter(None, [_sentence(self.banner(now).text), failed]))) + + def remove(self, host: str) -> str: + """Delete the connection to the Deploy App and its secrets, held and kept; if it was the active one, none is""" + gone = self.saved.connections.get(host) + if gone is None: + raise AppError(f"There is no Deploy App {host} in this app.") + active = host == self.saved.active + connections = {each: kept for each, kept in self.saved.connections.items() if each != host} + self._save(replace(self.saved, connections=connections, active="" if active else self.saved.active)) + if active: + self._drop() + forgotten = self._forget(host, gone.mdm) + LOGGER.info("Deploy App %s removed", host) + if not gone.mdm: + return self._say(f"Deploy App {host} is removed from this app.") + if not forgotten: + return self._say( + f"Deploy App {host} is removed from this app, but its MDM token may still be in this computer's " + f"keychain: delete the odmdm-connector item of {host} there by hand." + ) + return self._say(f"Deploy App {host} is removed from this app, and its MDM token from this computer.") + + # The enrolment window + + def paste_settings(self, text: str, now: datetime.datetime, sender: str = "") -> str: + """Take the settings line Deploy App's MDM page copied, and give the MDM its challenge + + A line for a Deploy App not saved yet adds a connection to it. Its Deploy App becomes the + active one. An MDM that cannot take a challenge by API gets none: challenge_note then says + what to do. sender is the origin of the page that sent the line, empty for one typed or + pasted by hand; a line sent from a page other than its own Deploy App's is refused. + """ + window, host = _read(text, now, sender) + closes = window.closes.isoformat() if window.closes else "" + connection = replace(self.saved.connections.get(host, store.Connection()), closes=closes) + changed = self._activate(host, connection) + failed = self._take_up() if changed or self.mdm is None else "" + self.redact.add(window.challenge) + self.window = window + LOGGER.info("Settings pasted for Deploy App %s, open until %s", host, closes) + until = self.banner(now).text + if self.mdm is None or self.challenge_note(): + return self._say(" ".join(filter(None, [f"{until}.", failed]))) + mdm = self.mdm + + def give() -> Result: + mdm.set_challenge(window) + return Result(Job.CHALLENGE) + + self._submit(Job.CHALLENGE, give) + return self._say(f"{until}. Giving the MDM the new challenge.") + + def challenge_note(self) -> str: + """The plugin's sentence for an MDM that cannot take the challenge by API, when one is held""" + if self.window is None or self.mdm_class is None: + return "" + return self.mdm_class.missing.get(SET_CHALLENGE, "") + + def challenge(self) -> str: + """The challenge, only for an MDM that has to be given it by hand""" + return self.window.challenge if self.window and self.challenge_note() else "" + + def banner(self, now: datetime.datetime) -> Banner: + """Whether the active Deploy App accepts phones, in the operator's time""" + closes = self.window.closes if self.window else store.closes(self.conn) + return _banner(self.saved.active, closes, now) + + @property + def mdm_page(self) -> str: + """The active Deploy App's MDM page, where enrolment is opened; empty while none is active""" + return f"{_admin(self.saved.active)}/mdm" if self.saved.active else "" + + # The phones + + def refresh(self) -> None: + """List the phones again on the worker, unless a listing is under way""" + if self.mdm is None or self._pending[Job.PHONES]: + return + mdm = self.mdm + self._submit(Job.PHONES, lambda: Result(Job.PHONES, phones=tuple(mdm.phones()))) + + @staticmethod + def _joined(phone: Phone, now: datetime.datetime) -> tuple[str, datetime.datetime | None]: + """When it joined, in the operator's time, and as a time if it is one""" + try: + when = datetime.datetime.fromisoformat(phone.joined) + except ValueError: + return phone.joined, None + if when.tzinfo is None: + when = when.replace(tzinfo=datetime.UTC) + return when.astimezone(now.tzinfo).strftime("%Y-%m-%d %H:%M"), when + + def rows(self, now: datetime.datetime) -> list[Row]: + """The table, oldest first as the MDM lists them""" + return [ + Row( + phone.id, + phone.callsign, + phone.model, + self._joined(phone, now)[0], + core.said(phone), + not phone.callsign, + phone.state in FAILED, + phone.state is State.READY, + self._askable(phone), + ) + for phone in self.phones + ] + + def _askable(self, phone: Phone) -> bool: + """Whether asking the phone again can help, with an MDM that can ask""" + return bool(self.mdm and ASK_AGAIN not in self.mdm.missing) and _askable(phone) + + def summary(self) -> str: + """How many phones there are and where they are; empty while no MDM is connected or none is listed yet""" + if self.mdm is None: + return "" + if not self.phones: + return "No phones yet." if self._listed else "" + named = [phone for phone in self.phones if phone.callsign] + ready = sum(phone.state is State.READY for phone in named) + failed = sum(phone.state in FAILED for phone in named) + parts = [ + (ready, "ready"), + (len(named) - ready - failed, "waiting for the phone"), + (failed, "failed"), + (len(self.phones) - len(named), "without a name"), + ] + return f"{_count(len(self.phones), 'phone')}: " + ", ".join(f"{n} {word}" for n, word in parts if n) + + def detail(self, phone_id: str, now: datetime.datetime) -> Detail: + phone = next((each for each in self.phones if each.id == phone_id), None) + if phone is None: + raise AppError(f"Phone {phone_id} is no longer in the MDM's list: refresh.") + return Detail( + phone.id, + phone.callsign, + phone.model, + self._joined(phone, now)[0], + phone.state.value, + phone.detail, + self.banner(now).text, + self._askable(phone), + ) + + # Naming + + def targets(self, selected: Sequence[str]) -> list[str]: + """The phones to name, in table order: the selected ones, or with none, every one without a name""" + chosen = set(selected) + return [phone.id for phone in self.phones if (phone.id in chosen if chosen else not phone.callsign)] + + def first_number(self, prefix: str) -> int: + """The number to start from: one above the highest prefix in use""" + return core.next_number(self.phones, prefix) + + @staticmethod + def numbered(prefix: str, start: int, count: int) -> list[str]: + return [f"{prefix}{start + n}" for n in range(count)] + + @staticmethod + def listed(text: str) -> list[str]: + """A list of callsigns as typed, one per line""" + return [line.strip() for line in text.splitlines() if line.strip()] + + def keep_callsigns(self, prefix: str, callsigns: Sequence[str]) -> None: + """Keep the prefix and the list for the active Deploy App next time, also before any phone has joined""" + self._save_conn(prefix=prefix, callsigns=list(callsigns)) + + def preview(self, ids: Sequence[str], callsigns: Sequence[str], now: datetime.datetime) -> Preview: + """What naming the phones with the callsigns, in order, would do, by the naming rules + + Only a preview that passed can then be named. + """ + found = {phone.id: phone for phone in self.phones} + rows: list[PreviewRow] = [] + fine: list[tuple[str, str]] = [] + for index, phone_id in enumerate(ids): + callsign = callsigns[index] if index < len(callsigns) else "" + phone = found.get(phone_id) + if not callsign: + refused = "no callsign left in the list" + else: + refused = core.refusal(self.phones, [(phone_id, callsign)]) or core.refusal( + self.phones, [*fine, (phone_id, callsign)] + ) + if not refused: + fine.append((phone_id, callsign)) + joined = self._joined(phone, now)[0] if phone else "" + rows.append(PreviewRow(phone_id, phone.model if phone else "", joined, callsign, refused)) + refusal = "" + if not ids: + refusal = "No phone is waiting for a name. To give a phone another callsign, select it first." + elif len(callsigns) < len(ids): + refusal = f"{_count(len(ids), 'phone')} to name, but only {_count(len(callsigns), 'callsign')}." + recent = [phone for phone in self.phones if self._recent(phone, now)] + warning = "" + if len(recent) == 1: + warning = ( + "A phone joined less than 10 minutes ago and may still be installing its apps. Naming now sends " + "the policy to every phone again, which stops apps that are still installing: wait until it has " + "its apps." + ) + elif recent: + warning = ( + f"{len(recent)} phones joined less than 10 minutes ago and may still be installing their apps. " + "Naming now sends the policy to every phone again, which stops apps that are still installing: " + "wait until they have their apps." + ) + result = Preview(tuple(rows), refusal, warning) + self._passed = result.names if result.ok else None + return result + + def _recent(self, phone: Phone, now: datetime.datetime) -> bool: + when = self._joined(phone, now)[1] + return when is not None and now - when < RECENT + + def name(self, names: Mapping[str, str]) -> str: + """Name the phones of the preview that passed last, on the worker""" + if self.mdm is None: + raise AppError("Connect to the MDM first.") + if self._passed is None or dict(names) != self._passed: + raise AppError("Preview the callsigns first: nothing is named without a preview that passed.") + self._passed = None + mdm, wanted = self.mdm, list(names.items()) + self._submit(Job.NAME, lambda: _name(mdm, wanted)) + return self._say(f"Naming {_count(len(wanted), 'phone')}.") + + def ask_again(self, ids: Sequence[str]) -> str: + """Have the phones ask for their certificates again; no ids: every named one that failed""" + if self.mdm is None: + raise AppError("Connect to the MDM first.") + if ASK_AGAIN in self.mdm.missing: + raise AppError(self.mdm.missing[ASK_AGAIN]) + if not ids: + mdm = self.mdm + self._submit(Job.ASK_AGAIN, lambda: Result(Job.ASK_AGAIN, lines=tuple(mdm.ask_again([])))) + return self._say("Asking every named phone whose certificate failed again.") + wanted = set(ids) + chosen = [phone.id for phone in self.phones if phone.id in wanted and _askable(phone)] + if not chosen: + raise AppError( + "Nothing to ask again: the selected phones have their certificates, or have no callsign yet." + ) + mdm, left = self.mdm, len(wanted) - len(chosen) + self._submit(Job.ASK_AGAIN, lambda: Result(Job.ASK_AGAIN, lines=tuple(mdm.ask_again(chosen)))) + if left: + return self._say(f"Asking {_count(len(chosen), 'phone')} again; {_count(left, 'phone')} left alone.") + return self._say("Asking again.") + + # The worker + + def _submit(self, job: Job, work: Callable[[], Result]) -> None: + self._pending[job] += 1 + log_path, host, by = self.log_path, self.saved.active, self.mdm + self.worker.submit(lambda: replace(_run(job, work, log_path), host=host, by=by)) + + def busy(self, job: Job | None = None) -> bool: + """Whether a job, or that kind of job, is under way""" + return bool(self._pending[job]) if job else any(self._pending.values()) + + def drain(self) -> list[Result]: + """The results finished since the last drain, taken in; called on the view's timer""" + done: list[Result] = [] + while True: + try: + result = self.worker.results.get_nowait() + except queue.Empty: + return done + self._pending[result.job] -= 1 + result = self._scrubbed(result) + self._take(result) + done.append(result) + + def _show(self, steps: tuple[Step, ...]) -> None: + """Called on the worker: the steps the setup has done so far""" + self._progress = steps + + @property + def progress(self) -> tuple[Step, ...]: + """The steps the setup under way has done so far, for a view to tick them as they come""" + return self._clean(self._progress) + + def _clean(self, steps: tuple[Step, ...]) -> tuple[Step, ...]: + scrub = self.redact.scrub + return tuple(replace(step, label=scrub(step.label), message=scrub(step.message)) for step in steps) + + def _scrubbed(self, result: Result) -> Result: + """The result with every secret the app was told of blanked out, as an MDM's answer may echo one""" + scrub = self.redact.scrub + return replace( + result, + error=scrub(result.error), + lines=tuple(scrub(line) for line in result.lines), + steps=self._clean(result.steps), + ) + + def _take(self, result: Result) -> None: + """What a result changes in the app, and what the status line says of it + + A result for a Deploy App no longer active changes nothing the app holds, and is still said. + """ + for line in result.lines: + LOGGER.info("%s: %s", result.job.value, line) + current = result.host == self.saved.active + if current and result.unauthorized and result.by is self.mdm is not None: + # The secret is not accepted, so it is let go of, kept copy and all, and the MDM with it, until typed again + self._forget(result.host, self.conn.mdm) + self.mdm, self.phones, self._listed = None, [], False + if current and result.phones is not None and self.mdm is not None: + self.phones, self._listed = list(result.phones), True + if current and result.named and self.conn.callsigns: + used = {callsign.lower() for callsign in result.named.values()} + try: + self._save_conn(callsigns=[each for each in self.conn.callsigns if each.lower() not in used]) + except AppError as exc: + LOGGER.warning("%s", exc) + if current and result.job in (Job.NAME, Job.ASK_AGAIN): + self.refresh() + title = self.mdm_class.title if self.mdm_class else "The MDM" + if result.error: + stopped = "" + if result.named: + done = ", ".join(f"{phone} as {callsign}" for phone, callsign in result.named.items()) + stopped = f" Named before it stopped: {done}." + self._say(result.error + stopped) + elif result.job is Job.SETUP and (any(not step.done for step in result.steps) or self.challenge_note()): + self._say(f"Do the steps by hand to finish setting {title} up for Deploy App {result.host}.") + elif result.job is Job.SETUP: + self._say(f"{title} is set up for Deploy App {result.host}.") + elif result.job is Job.POLICY: + self._say(f"{title} has sent the policy again to the phones of Deploy App {result.host}.") + elif result.job is Job.CHALLENGE: + self._say(f"{title} has the new challenge.") + elif result.job is Job.NAME: + self._say(f"{_count(len(result.named), 'phone')} named.") + elif result.job is Job.ASK_AGAIN: + self._say("Asked again." if result.lines else "No phone needed asking again.") + if result.job in (Job.NAME, Job.ASK_AGAIN): + self.lines = result.lines diff --git a/src/odmdm_connector/browser.py b/src/odmdm_connector/browser.py new file mode 100644 index 0000000..7451ed1 --- /dev/null +++ b/src/odmdm_connector/browser.py @@ -0,0 +1,75 @@ +"""Opening the page in the operator's default browser: the one place the connector starts a process + +The address holds the page's key, and on Linux and macOS a program's arguments can be read by other +users of the computer. So the address is never handed to the system's opener: a small file in the +connector's own directory, which only the user can read, leads on to it, and the opener is given +that file's path alone. The file holds the key while the connector runs and is removed when it stops. +""" + +import html +import logging +import os +import sys +import webbrowser +from pathlib import Path + +LOGGER = logging.getLogger(__name__) + +#: The file in the connector's directory that leads on to the page's address +NAME = "open-page.html" + + +def can_open() -> bool: + """Whether there is a desktop to open a browser on; without one, webbrowser starts a text browser in the terminal""" + if sys.platform in ("win32", "darwin"): + return True + return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")) + + +def _page(address: str) -> str: + escaped = html.escape(address, quote=True) + return ( + "\n" + '\n' + '\n' + f'\n' + "odmdm-connector\n" + f'

Open the connector\'s page

\n' + ) + + +def _write(path: Path, address: str) -> None: + """The file anew, readable only by the user: one left from an earlier start is removed first""" + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + path.unlink(missing_ok=True) + handle = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as written: + written.write(_page(address)) + + +def open_page(address: str, directory: Path) -> bool: + """Ask the default browser to open the address, through a file in the directory; whether it was asked + + Raises nothing that writing the file or starting a browser raises: the connector starts whether + or not a browser opens. + """ + if not can_open(): + return False + path = directory / NAME + try: + _write(path, address) + if webbrowser.open(path.as_uri()): + return True + LOGGER.warning("No browser could be asked to open the page") + except (OSError, ValueError, webbrowser.Error) as exc: + LOGGER.warning("The browser could not be asked to open the page: %s", type(exc).__name__) + remove(directory) + return False + + +def remove(directory: Path) -> None: + """Remove the file, if it is there; never raises""" + try: + (directory / NAME).unlink(missing_ok=True) + except OSError as exc: + LOGGER.warning("The file %s could not be removed: %s", directory / NAME, type(exc).__name__) diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py new file mode 100644 index 0000000..55bcb49 --- /dev/null +++ b/src/odmdm_connector/console.py @@ -0,0 +1,515 @@ +"""CLI entrypoints for odmdm-connector + +Knows the MDM only through the contract in mdm.py, and gets it only through plugins.load: the +chosen MDM is the one entry point of the group odmdm_connector.mdm named by --mdm, Fleet being the +one built in. +""" + +import argparse +import codecs +import datetime +import getpass +import inspect +import logging +import os +import sys +import threading +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path +from urllib.parse import urlparse + +from odmdm_connector import __version__ + +from . import browser, core, plugins, settings, store, web +from .app import App +from .mdm import ASK_AGAIN, SEND_POLICY, SET_CHALLENGE, SETUP, Field, Mdm, MdmError +from .settings import Settings + +#: Said when ODMDM_LOG_LEVEL is not a number +LOG_LEVEL = "ODMDM_LOG_LEVEL must be a whole number, such as 10 for debug or 20 for info: change it, or unset it." +#: Said before the page's address, when the browser is to be asked to open it and when not +OPENING = "The connector's page is opening in your browser. If it does not, open this address:" +OPEN = "Open this address in your browser:" +#: Said when Ctrl+C stops the page while a job is under way +STOPPED_BUSY = "Stopped while the MDM was still being worked with: refresh the phones when the connector runs again." +#: Asked after the page's port was found taken on a start without a command, so its window does not close unread +PRESS_ENTER = "Press Enter to close." + + +class _Usage(Exception): + """A command line the connector cannot act on: said with the command's usage, exit 2""" + + +class _Failed(Exception): + """A sentence on stderr, exit 1""" + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the command line and answer its exit code; a usage error exits 2 through argparse""" + parser = _parser() + given = sys.argv[1:] if argv is None else list(argv) + args = parser.parse_args(given) + if not hasattr(args, "run"): + # Started with no command, as a downloaded file is by a double-click: the page, with web's defaults + args = parser.parse_args([*given, "web"]) + args.alone = True + try: + level = int(os.environ.get("ODMDM_LOG_LEVEL", "20")) + except ValueError: + print(LOG_LEVEL, file=sys.stderr) + return 1 + if args.verbose == 1: + level = logging.INFO + if args.verbose >= 2: + level = logging.DEBUG + logging.basicConfig(stream=sys.stderr, format="%(asctime)s %(levelname)s %(name)s: %(message)s") + logging.getLogger().setLevel(level) + run: Callable[[argparse.Namespace], int] = args.run + try: + for value in args.given: + key, equals, _ = value.partition("=") + if not key or not equals: + raise _Usage("--set takes KEY=VALUE") + return run(args) + except _Usage as exc: + args.parser.error(str(exc)) + except _Failed as exc: + print(exc, file=sys.stderr) + except (KeyboardInterrupt, EOFError): + print("Stopped before the command finished.", file=sys.stderr) + return 1 + + +def odmdm_connector_cli() -> None: + """CLI entrypoint""" + sys.exit(main()) + + +def _chosen(name: str) -> type[Mdm]: + """The class of the MDM of that name, saying first whose code it is when it is not built in""" + try: + plugin = plugins.find(name) + if not plugin.built_in: + print( + f"The MDM {name} is a plugin from {plugin.package} {plugin.version}: code that sees the MDM token", + file=sys.stderr, + ) + return plugins.load(name) + except plugins.NotInstalled as exc: + raise _Usage(str(exc)) from exc + except plugins.PluginError as exc: + raise _Failed(str(exc)) from exc + + +def _values(name: str, fields: tuple[Field, ...], given: Mapping[str, str], host: str) -> dict[str, str]: + """The fields' values: from --set, else ODMDM_, else the default for the deployment on host + + A secret only ever from the file ODMDM__FILE names, so it stays out of shell history and + process environments. No value is ever in a message. + """ + keys = sorted(item.key for item in fields) + unknown = sorted(set(given) - set(keys)) + if unknown: + raise _Usage(f"{name} has no setting {unknown[0]}; it has {', '.join(keys)}") + values: dict[str, str] = {} + for item in fields: + env = f"ODMDM_{item.key.upper()}" + if item.secret: + if item.key in given: + raise _Usage(f"{item.key} is a secret: put it in a file and set {env}_FILE to that file") + path = os.environ.get(f"{env}_FILE", "") + values[item.key] = _secret_file(Path(path), item.label) if path and Path(path).is_file() else "" + if not values[item.key].isprintable(): + raise _Failed( + f"The {item.label} holds a line break or another character that cannot be part of it: copy it again." + ) + else: + values[item.key] = given[item.key] if item.key in given else os.environ.get(env, item.default_for(host)) + return values + + +def _secret_file(path: Path, label: str) -> str: + """A secret's file as text: UTF-16 by its byte order mark, as Windows PowerShell 5.1 writes, else UTF-8 + + Never the bytes in a message: a decoding error quotes them. + """ + try: + data = path.read_bytes() + if data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)): + return data.decode("utf-16").strip() + return data.decode("utf-8-sig").strip() + except (OSError, UnicodeDecodeError): + raise _Failed(f"The file {path} cannot be read as plain text: save the {label} in it as plain text.") from None + + +def _missing(fields: tuple[Field, ...], values: Mapping[str, str]) -> str: + """How to give the first required setting that is empty; empty when none is""" + for item in fields: + if item.required and not values[item.key]: + env = f"ODMDM_{item.key.upper()}" + if item.secret: + return f"{item.label} is missing: put it in a file and set {env}_FILE to that file" + return f"{item.label} is missing: give --set {item.key}=... or set {env}" + return "" + + +def _mdm(args: argparse.Namespace, *capabilities: str, complete: bool = True) -> Mdm: + """The chosen MDM, configured; or the MDM's sentence for lacking one of the capabilities + + The command's own options such as --team are each the same as --set team=... A default that + names the deployment takes it from --domain, else ODMDM_DOMAIN. + complete: every required setting must be given, which a dry run does not need. + """ + given = {key: setting for key, _, setting in (value.partition("=") for value in args.given)} + chosen = _chosen(args.chosen) + for capability in capabilities: + if capability in chosen.missing: + raise _Failed(chosen.missing[capability]) + for key in ("mdm_url", "team", "template"): + if getattr(args, key, None) is not None: + given[key] = getattr(args, key) + host = getattr(args, "domain", None) or os.environ.get("ODMDM_DOMAIN", "") + values = _values(args.chosen, chosen.fields, given, host) + missing = _missing(chosen.fields, values) if complete else "" + if missing: + raise _Failed(missing) + try: + return chosen(values) + except MdmError as exc: + raise _Failed(str(exc)) from exc + + +def _domain(args: argparse.Namespace) -> str: + the_domain: str = args.domain or os.environ.get("ODMDM_DOMAIN", "") + if not the_domain: + raise _Failed("Give --domain or set ODMDM_DOMAIN") + return the_domain + + +def _now() -> datetime.datetime: + """Now, in this computer's time zone, which the times said are in""" + return datetime.datetime.now().astimezone() + + +def _window(value: str, domain: str) -> Settings: + """The enrolment window, from a settings line or a bare challenge, or why not + + A bare challenge says nothing of when the window closes. The challenge is never in a message. + """ + if not settings.is_line(value): + return Settings(f"https://{domain}/scep", value.strip()) + try: + line = settings.parse(value, _now()) + except settings.SettingsError as exc: + raise _Failed(str(exc)) from exc + host = urlparse(line.scep_url).hostname or "" + if host != domain.lower(): + raise _Failed(f"The settings line is for {host}, not {domain}: copy it from this deployment's MDM page") + return line + + +def apply(args: argparse.Namespace) -> int: + """Tell the MDM what this deployment's devices need + + Run it when a deployment is set up and whenever its template changes. A changed policy stops + apps installing on phones that are enrolling at that moment, so a new enrolment window is + `challenge`, not this. + + Order matters and is handled for you. Apps install at ENROLMENT and at no other time, so a + device that has already joined will not pick up a template applied afterwards -- it has to + enrol again, under a callsign that has not been spent. + """ + the_domain = _domain(args) + if args.dry_run: + window = Settings(f"https://{the_domain}/scep", "") + else: + window = _window(os.environ.get("ODMDM_CHALLENGE", ""), the_domain) + capabilities = (SETUP, SEND_POLICY) if args.force_policy else (SETUP,) + mdm = _mdm(args, *capabilities, complete=not args.dry_run) + try: + for step in mdm.setup(window, force=args.force_policy, dry_run=args.dry_run): + print(step.label if step.done else f"{step.label} (not done)") + if step.message: + print(step.message) + except MdmError as exc: + raise _Failed(str(exc)) from exc + return 0 + + +def challenge(args: argparse.Namespace) -> int: + """Give the MDM the challenge of the enrolment window just opened + + Every opening makes a new one. Only the certificate authority changes, so phones still + installing apps are left alone. Taken from ODMDM_CHALLENGE, else asked for, never as an + argument, so it stays out of shell history and the process list. Given the whole settings line, + its SCEP URL must be on this deployment's domain. + """ + the_domain = _domain(args) + mdm = _mdm(args, SET_CHALLENGE) + value = os.environ.get("ODMDM_CHALLENGE", "") + while not value.strip(): + value = getpass.getpass("Settings line or challenge from Deploy App's MDM page: ") + window = _window(value, the_domain) + try: + mdm.set_challenge(window) + except MdmError as exc: + raise _Failed(str(exc)) from exc + until = "" + if window.closes: + until = f". The enrolment window is open until {window.closes.astimezone(_now().tzinfo):%Y-%m-%d %H:%M}" + print(f"{mdm.title} has the new challenge{until}") + return 0 + + +def phones(args: argparse.Namespace) -> int: + """List the team's phones and where each one's certificate is + + One line each: the id that name and resend take, the callsign, the model, the day it + enrolled, and the certificate in plain words. + """ + mdm = _mdm(args) + try: + found = mdm.phones() + except MdmError as exc: + raise _Failed(str(exc)) from exc + for phone in found: + print(f"{phone.id:<5} {phone.callsign or '-':<12} {phone.model:<26} {phone.joined[:10]} {core.said(phone)}") + if not found: + print("No phones in the team") + return 0 + + +def name(args: argparse.Namespace) -> int: + """Name phones, and have the MDM send them certificates + + ID=CALLSIGN for as many phones as you like, in any order, the id being what phones prints. Or + --all PREFIX, which numbers every phone that has no name yet. Each phone gets its certificate + at its next check-in, within about 15 minutes. A phone that already has its certificate under + the name is left alone. + + Nothing is changed if a name is not a callsign, is given twice or belongs to another phone in + the team, or if a phone is not in the team. + + With Fleet, the team's policy is sent again, to every phone in it, if a phone enrolled after it + was last sent, because Fleet can overwrite a new phone's policy. So name phones once every phone in the + team has its apps. + """ + if bool(args.pairs) == bool(args.prefix) or (args.start is not None and not args.prefix): + raise _Usage("Give ID=CALLSIGN for each phone, or --all PREFIX") + try: + wanted = core.pairs(args.pairs) + except ValueError as exc: + raise _Usage(str(exc)) from exc + mdm = _mdm(args) + try: + found = mdm.phones() + if args.prefix: + wanted = core.numbered(found, args.prefix, args.start) + refused = core.refusal(found, wanted) + if refused: + raise _Failed(f"Nothing named: {refused}") + if not wanted: + print("Nothing to name") + return 0 + lines = mdm.name(dict(wanted)) + except MdmError as exc: + for line in exc.lines: + print(line) + print(exc, file=sys.stderr) + if exc.named: + done = " ".join(f"{phone}={callsign}" for phone, callsign in exc.named.items()) + print(f"Already named before it stopped: {done}. phones shows where each is", file=sys.stderr) + return 1 + for line in lines: + print(line) + return 0 + + +def resend(args: argparse.Namespace) -> int: + """Have phones ask for their certificates again + + For a refused phone once the cause is fixed, such as enrolment opened again and its new + challenge given to the MDM. A taken name is not one of those: Deploy App never frees a name, so + give the phone another with name, which sends the request itself. Without ids, every phone + that has a name and whose certificate failed. Each acts on it at its next check-in, within + about 15 minutes. + + An id is asked whatever its state. A phone that has its certificate asks again under the + name it holds and is refused, and reads as refused from then on though that certificate still + works. As with name, the team's policy is sent again if a phone enrolled after it was last sent. + """ + mdm = _mdm(args, ASK_AGAIN) + try: + lines = mdm.ask_again(list(args.ids)) + except MdmError as exc: + for line in exc.lines: + print(line) + raise _Failed(str(exc)) from exc + for line in lines: + print(line) + if not lines: + print("Nothing to resend") + return 0 + + +def mdms(args: argparse.Namespace) -> int: + """List the MDMs installed: the name --mdm takes, the package and its version, built in or a plugin + + Lists them without loading any. A plugin is code that sees the MDM token: install only one you trust. + """ + try: + found = plugins.installed() + except plugins.PluginError as exc: + raise _Failed(str(exc)) from exc + for plugin in found: + kind = "built in" if plugin.built_in else "plugin" + print(f"{plugin.name:<12} {plugin.package:<28} {plugin.version:<16} {kind}") + return 0 + + +def page(args: argparse.Namespace) -> int: + """Serve the connector as a page that only this computer can open, until Ctrl+C + + The page opens in your default browser; if it does not, open the address it prints: it holds a + key that the page needs. + """ + started = App.default() + directory = store.directory() + try: + try: + server = web.Page(started, args.port) + except OSError as exc: + # Deploy App's button reaches the default port only, so another port is not the first advice there + advice = ( + "The connector may be running already: use its page. Another port, given with --port, works " + "for a pasted settings line only, as Deploy App's button reaches this port." + if args.port == web.PORT + else "Give another with --port." + ) + print( + f"The page cannot listen on port {args.port} of this computer: {exc.strerror}. {advice}", + file=sys.stderr, + ) + # Started without a command, as by a double-click, the window would close before it is read + if args.alone and sys.stdin.isatty() and sys.stdout.isatty(): + try: + input(PRESS_ENTER) + except (EOFError, KeyboardInterrupt): + pass + return 1 + asked = args.browser and browser.can_open() + print(f"{OPENING if asked else OPEN} {server.address}") + print("Press Ctrl+C to stop it.", flush=True) + with server: + if asked: + # Some openers wait for the browser, or never return: the page serves meanwhile + threading.Thread(target=browser.open_page, args=(server.address, directory), daemon=True).start() + try: + server.serve_forever() + except KeyboardInterrupt: + if started.busy(): + print(STOPPED_BUSY, file=sys.stderr) + finally: + # Only this run's file: without it, the file may be a connector's that is still running + if asked: + browser.remove(directory) + finally: + started.close() + return 0 + + +def _between(low: int, high: int | None = None) -> Callable[[str], int]: + """An argparse type: a whole number from low, up to high when given""" + + def number(value: str) -> int: + try: + given = int(value) + except ValueError: + given = low - 1 + if given < low or (high is not None and given > high): + upto = f" to {high}" if high is not None else " up" + raise argparse.ArgumentTypeError(f"{value} is not a whole number from {low}{upto}") + return given + + return number + + +#: The options more than one command takes, with their help +SHARED = { + "--mdm-url": "The MDM's address, as --set mdm_url (default: ODMDM_MDM_URL)", + "--team": "The team the phones are in, as --set team (default: ODMDM_TEAM)", + "--template": "What to install, as --set template (default: ODMDM_TEMPLATE)", + "--domain": "The deployment's DNS name (default: ODMDM_DOMAIN)", +} + + +def _parser() -> argparse.ArgumentParser: + """The command line, its defaults read from the environment now""" + parser = argparse.ArgumentParser( + prog="odmdm-connector", + description="Connect an MDM, Fleet built in, to an OpenDefence deployment's device enrolment", + ) + parser.add_argument("--version", action="version", version=f"%(prog)s, version {__version__}") + parser.add_argument("-v", "--verbose", action="count", default=0, help="Shorthand for info/debug loglevel (-v/-vv)") + parser.add_argument( + "--mdm", + dest="chosen", + default=os.environ.get("ODMDM_MDM", "fleet"), + metavar="NAME", + help="The MDM to talk to (default: ODMDM_MDM, else fleet)", + ) + parser.add_argument( + "--set", + dest="given", + action="append", + default=[], + metavar="KEY=VALUE", + help="A setting of the MDM, such as mdm_url; never a secret, which is read from the file ODMDM__FILE names", + ) + commands = parser.add_subparsers( + title="commands", metavar="COMMAND", description="Without a command: web with its defaults" + ) + + def command(called: str, run: Callable[[argparse.Namespace], int], *shared: str) -> argparse.ArgumentParser: + doc = inspect.cleandoc(run.__doc__ or "") + sub = commands.add_parser( + called, + help=doc.splitlines()[0], + description=doc, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + sub.set_defaults(run=run, parser=sub) + for option in shared: + sub.add_argument(option, default=None, help=SHARED[option]) + return sub + + sub = command("apply", apply, "--template", "--mdm-url", "--team", "--domain") + sub.add_argument( + "--force-policy", + action="store_true", + help="Re-upload the policy even if unchanged, to reach a host that just joined", + ) + sub.add_argument("--dry-run", action="store_true", help="Read and validate the template, then stop") + command("challenge", challenge, "--template", "--mdm-url", "--team", "--domain") + command("phones", phones, "--mdm-url", "--team") + sub = command("name", name, "--mdm-url", "--team") + sub.add_argument("pairs", nargs="*", metavar="ID=CALLSIGN") + sub.add_argument( + "--all", dest="prefix", metavar="PREFIX", help="Name every phone that has no name PREFIX, in enrolment order" + ) + sub.add_argument( + "--start", + type=_between(1), + metavar="N", + help="The first n for --all (default: one above the highest in use)", + ) + sub = command("resend", resend, "--mdm-url", "--team") + sub.add_argument("ids", nargs="*", metavar="ID") + command("mdms", mdms) + sub = command("web", page) + sub.set_defaults(alone=False) + sub.add_argument( + "--port", type=_between(1, 65535), default=web.PORT, help="The port on 127.0.0.1 (default: %(default)s)" + ) + sub.add_argument("--no-browser", dest="browser", action="store_false", help="Only print the address") + return parser diff --git a/src/odmdm_connector/core.py b/src/odmdm_connector/core.py new file mode 100644 index 0000000..158c400 --- /dev/null +++ b/src/odmdm_connector/core.py @@ -0,0 +1,72 @@ +"""The rules for naming phones, the same whatever the MDM""" + +import re +from collections.abc import Sequence + +from .mdm import Phone, State + +#: The deployment's rule for a device callsign, checked here only so a typo is refused now rather +#: than as a failed certificate twenty minutes later. The deployment still decides. +CALLSIGN = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{1,30}[A-Za-z0-9]") +#: The states the plugin's words are said beside: the certificate was never asked for, was refused, +#: could not be reached or failed. Waiting for it or having it, the state alone is true: words from +#: an earlier failure would sit beside a request that has not failed. +EXPLAINED = (State.NO_REQUEST, State.NOT_ASKED, State.REFUSED, State.UNREACHABLE, State.FAILED) + + +def pairs(values: Sequence[str]) -> list[tuple[str, str]]: + """ID=CALLSIGN arguments, as ids and callsigns; ValueError saying which one is not""" + found = [] + for value in values: + phone, _, callsign = value.partition("=") + if not phone or not callsign: + raise ValueError(f"{value!r} is not ID=CALLSIGN, the id being what phones prints") + found.append((phone, callsign)) + return found + + +def next_number(phones: Sequence[Phone], prefix: str) -> int: + """One above the highest PREFIX in use, compared without case; 1 when none is""" + used = (re.fullmatch(re.escape(prefix) + r"(\d+)", phone.callsign, re.IGNORECASE) for phone in phones) + return max((int(match.group(1)) for match in used if match), default=0) + 1 + + +def numbered(phones: Sequence[Phone], prefix: str, start: int | None) -> list[tuple[str, str]]: + """PREFIX for every phone without a name, in the order given + + Numbered from start, else from one above the highest PREFIX already in use. + """ + if start is None: + start = next_number(phones, prefix) + waiting = [phone.id for phone in phones if not phone.callsign] + return [(phone, f"{prefix}{start + n}") for n, phone in enumerate(waiting)] + + +def refusal(phones: Sequence[Phone], wanted: Sequence[tuple[str, str]]) -> str: + """Why these names cannot all be given, or empty when they can + + Callsigns are compared without case, as the deployment compares them. + """ + found = {phone.id: phone for phone in phones} + ids: set[str] = set() + callsigns: set[str] = set() + for phone, callsign in wanted: + if phone not in found: + return f"phone {phone} is not in the group" + if phone in ids: + return f"phone {phone} is named twice" + if not CALLSIGN.fullmatch(callsign): + return f"{callsign}: a callsign is 3-32 letters, digits or hyphens, and does not start or end with a hyphen" + if callsign.lower() in callsigns: + return f"{callsign} is given twice" + owner = next((p.id for p in phones if p.id != phone and p.callsign.lower() == callsign.lower()), "") + if owner: + return f"{callsign} already belongs to phone {owner}" + ids.add(phone) + callsigns.add(callsign.lower()) + return "" + + +def said(phone: Phone) -> str: + """Where the phone's certificate is, as the operator reads it: the state, and the words EXPLAINED allows""" + return f"{phone.state.value}: {phone.detail}" if phone.detail and phone.state in EXPLAINED else phone.state.value diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py new file mode 100644 index 0000000..f92be4e --- /dev/null +++ b/src/odmdm_connector/fleet.py @@ -0,0 +1,737 @@ +"""What a deployment needs, said to FleetDM + +Every request shape and every wait in here was measured against a live Fleet, and the comments +say which. None of it mentions a product: what to install arrives in the template. +""" + +import dataclasses +import datetime +import http.client +import json +import logging +import re +import secrets +import ssl +import time +import urllib.error +import urllib.request +from typing import Any +from urllib.parse import urlencode, urlparse + +from . import __version__ +from .icon import launcher_icon +from .template import MdmTemplate + +LOGGER = logging.getLogger(__name__) + +#: A web app is not installable until managed Play has published it, which is not synchronous +WEB_APP_PUBLISH_ATTEMPTS = 12 +WEB_APP_PUBLISH_WAIT = 10.0 + + +def _same_case(url: str) -> str: + """A URL with its scheme and host lower-cased, as they compare without case""" + parts = urlparse(url) + return parts._replace(scheme=parts.scheme.lower(), netloc=parts.netloc.lower()).geturl() + + +class FleetError(RuntimeError): + """Fleet refused, or answered something we cannot use""" + + +class Unauthorized(FleetError): + """Fleet answered 401: it does not accept the token""" + + +class NoTeam(FleetError): + """Fleet has no team of the name given, and none was to be created""" + + +#: The proxy the environment names, and HTTPS with certificates checked: nothing else. Without a +#: redirect handler a redirect comes back as an answer and is never followed, so the token goes +#: nowhere but the MDM URL; without the error handlers an answer of any status comes back as it is. +_OPENER = urllib.request.OpenerDirector() +_OPENER.add_handler(urllib.request.ProxyHandler()) +_OPENER.add_handler(urllib.request.HTTPSHandler(context=ssl.create_default_context())) + + +def _send(method: str, url: str, headers: dict[str, str], body: bytes | None, timeout: float) -> tuple[int, bytes]: + """Send one request to the MDM and return its status and body, whatever the status""" + if urlparse(url).scheme != "https": + # The token goes with every request, so it must not cross the network readable + raise FleetError("the MDM address must start with https://") + try: + request = urllib.request.Request( + url, data=body, headers={**headers, "User-Agent": f"odmdm-connector/{__version__}"}, method=method + ) + with _OPENER.open(request, timeout=timeout) as response: + return int(response.status), response.read() + except ValueError: + # Its text quotes the header it refused, the token with it + raise FleetError("the MDM address or the token holds a character a request cannot carry") from None + except urllib.error.URLError as exc: + raise FleetError(f"could not reach the MDM: {exc.reason}") from exc + except (OSError, http.client.HTTPException) as exc: + raise FleetError(f"could not reach the MDM: {exc}") from exc + + +def _multipart( + fields: dict[str, str], file_field: str, filename: str, payload: bytes, content_type: str +) -> tuple[str, bytes]: + """A multipart/form-data body and its content type: the plain fields, then the file""" + for name in (*fields, file_field, filename, content_type): + if any(character in name for character in '"\r\n'): + raise ValueError(f"{name!r} cannot go in a multipart header") + boundary = secrets.token_hex(16) + parts = [ + f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode() + for name, value in fields.items() + ] + parts.append( + f'--{boundary}\r\nContent-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n' + f"Content-Type: {content_type}\r\n\r\n".encode() + + payload + + b"\r\n" + ) + parts.append(f"--{boundary}--\r\n".encode()) + return f"multipart/form-data; boundary={boundary}", b"".join(parts) + + +#: Said when Fleet answers 401. A token copied from a signed-in account is that sign-in's own, and Fleet ends it +#: with that sign-in, after 5 days by default or at sign-out; an API-only user's token does not end. +UNAUTHORIZED = ( + "the API token is not accepted. A token copied from a signed-in account ends with that sign-in: " + "give a new one, or an API-only user's, which does not end" +) + + +#: Fleet's hosts listing answers in pages; Fleet's page numbers start from 0 +HOSTS_PER_PAGE = 500 + +#: Google refuses a managed web app title of 30 characters or more +MAX_WEB_APP_TITLE = 29 + +#: Named after the responder this was first applied from, and kept: Fleet knows a profile by its +#: name, so a new name would sit next to the old profile on every team instead of replacing it. +POLICY_NAME = "rmscep-policy" + +#: What an authority made here is called: this and the Deploy App's own name, so that one Fleet +#: can serve several Deploy Apps +AUTHORITY_PREFIX = "ODMDM_" +#: The one name the shipped template gave every Deploy App's authority before each had its own. +#: An authority is found by the address it serves, so one of this name is still its Deploy App's. +LEGACY_AUTHORITY = "RMSCEP" + + +def authority_name(scep_url: str) -> str: + """What a Deploy App's authority is called when it is made here: ODMDM_ and the host's first label + + In capitals, with an underscore for anything else: Fleet takes letters, digits and underscores only. + """ + label = (urlparse(scep_url).hostname or "").split(".")[0] + return AUTHORITY_PREFIX + re.sub(r"[^A-Z0-9]", "_", label.upper()) + + +@dataclasses.dataclass(frozen=True) +class Phone: + """A device in the team, and how far its certificate has got""" + + id: int + #: What the certificate's common name becomes: the name Fleet holds up to any "@". Empty while + #: nobody has named the phone. + callsign: str + model: str + enrolled: str + #: The certificate row's status and Fleet's detail on it. No status: nothing was asked for. + status: str + detail: str + + +def _moment(value: str) -> datetime.datetime: + """A time Fleet wrote, as a time + + Fleet writes a profile's created_at to the microsecond and its updated_at and a host's + last_enrolled_at to the second, so as strings "...44Z" sorts after "...44.458685Z". + """ + try: + return datetime.datetime.fromisoformat(value) + except ValueError as exc: + raise FleetError(f"the time {value!r} could not be read") from exc + + +class FleetMdm: + """What this feature needs an MDM to be able to do, in Fleet's words""" + + def __init__(self, base_url: str, token: str, timeout: float = 60.0) -> None: + self.base_url = base_url.rstrip("/") + self._token = token + self.timeout = timeout + + def _call(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]: + headers = {"Authorization": f"Bearer {self._token}"} + data = None + if body is not None: + headers["Content-Type"] = "application/json" + data = json.dumps(body, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8") + status, answer = _send(method, f"{self.base_url}{path}", headers, data, self.timeout) + if status == 401: + raise Unauthorized(UNAUTHORIZED) + if not 200 <= status < 300: + # Enough of the body to keep the reason intact: the retry below matches on it, and + # truncating to a couple of hundred characters cut the phrase off mid-word. + raise FleetError(f"{method} {path} answered {status}: {answer.decode('utf-8', 'replace')[:800]}") + if not answer: + return {} + try: + payload: dict[str, Any] = json.loads(answer) + except ValueError as exc: + raise FleetError(f"{method} {path} did not answer JSON") from exc + return payload + + def _upload( + self, + path: str, + fields: dict[str, str], + filename: str, + payload: bytes, + file_field: str, + content_type: str = "application/json", + ) -> dict[str, Any]: + form_type, form = _multipart(fields, file_field, filename, payload, content_type) + headers = {"Authorization": f"Bearer {self._token}", "Content-Type": form_type} + status, answer = _send("POST", f"{self.base_url}{path}", headers, form, self.timeout) + if status == 401: + raise Unauthorized(UNAUTHORIZED) + if not 200 <= status < 300: + raise FleetError(f"upload to {path} answered {status}: {answer.decode('utf-8', 'replace')[:200]}") + result: dict[str, Any] = json.loads(answer) if answer else {} + return result + + # --- scopes --------------------------------------------------------------- + + def team_id(self, name: str, create: bool = False) -> int: + """The team by name + + Only apply creates a team that is not there. Anywhere else an unknown name is a typo, and + must not leave a team behind. + """ + for team in self._call("GET", "/api/latest/fleet/teams").get("teams", []): + if team.get("name") == name: + return int(team["id"]) + if not create: + raise NoTeam(f"no team named {name}: check the team's name") + created = self._call("POST", "/api/latest/fleet/teams", {"name": name}) + team = created.get("team", created) + LOGGER.info("Created team %s", name) + return int(team["id"]) + + # --- what a device gets --------------------------------------------------- + + def _title_id(self, team: int, package: str) -> int | None: + query = urlencode({"team_id": team, "available_for_install": "true"}) + titles = self._call("GET", f"/api/latest/fleet/software/titles?{query}").get("software_titles", []) + for title in titles: + if (title.get("app_store_app") or {}).get("app_store_id") == package: + return int(title["id"]) + return None + + def assign_apps(self, team: int, packages: list[str], preinstall: list[str]) -> dict[str, int]: + """Make the apps available, and install them at enrolment where that is possible + + Fleet hardcodes AVAILABLE for user-added Android apps -- FORCE_INSTALLED is reserved for + its own agent -- so the setup experience is the only automatic path, and it applies at + ENROLMENT. A host that has already joined will never auto-install; it has to enrol again. + """ + ids: dict[str, int] = {} + for package in packages: + existing = self._title_id(team, package) + if existing: + ids[package] = existing + continue + body = {"app_store_id": package, "platform": "android", "team_id": team} + for attempt in range(WEB_APP_PUBLISH_ATTEMPTS): + try: + created = self._call("POST", "/api/latest/fleet/software/app_store_apps", body) + ids[package] = int(created["software_title_id"]) + break + except FleetError as exc: + # Apostrophes vary; match the part that does not. + if "available in Play Store" not in str(exc) or attempt == WEB_APP_PUBLISH_ATTEMPTS - 1: + raise + LOGGER.info("Waiting for managed Play to publish %s", package) + time.sleep(WEB_APP_PUBLISH_WAIT) + chosen = sorted(ids[p] for p in preinstall if p in ids) + if chosen: + self._call( + "PUT", + "/api/latest/fleet/setup_experience/software", + {"platform": "android", "team_id": team, "software_title_ids": chosen}, + ) + return ids + + def set_app_config(self, team: int, package: str, config: dict[str, Any]) -> None: + title = self._title_id(team, package) + if not title: + raise FleetError(f"{package} is not assigned to team {team}; assign it before configuring it") + self._call( + "PATCH", + f"/api/latest/fleet/software/titles/{title}/app_store_app", + {"team_id": team, "configuration": {"managedConfiguration": config}}, + ) + + def ensure_policy(self, team: int, fragment: dict[str, Any], name: str = POLICY_NAME, force: bool = False) -> None: + """Android configuration profiles carry raw policy JSON + + There is no update in place, so changing one is delete then upload. Re-uploading an + unchanged profile is not free: a policy rewritten on every pass never settles long enough + for Play to finish an install. So Fleet's own copy is what gets compared, because this + runs once per command and has nothing of its own to remember between runs. + + force exists because Fleet can overwrite a newly enrolled phone's policy with a bare one + moments after sending ours, then shows ours as verified and never sends it again. Only a + new upload reaches that phone. resend_policy makes one when a phone enrolled after the + last upload. + """ + profiles = self._call("GET", f"/api/latest/fleet/configuration_profiles?team_id={team}").get("profiles", []) + here = [p for p in profiles if p.get("name") == name] + if len(here) == 1 and not force and self._policy_in_fleet(here[0]["profile_uuid"]) == fragment: + return + try: + for existing in here: + self._call("DELETE", f"/api/latest/fleet/configuration_profiles/{existing['profile_uuid']}") + self._upload( + "/api/latest/fleet/configuration_profiles", + {"team_id": str(team)}, + f"{name}.json", + json.dumps(fragment, indent=2, sort_keys=True).encode("utf-8"), + file_field="profile", + ) + except FleetError as exc: + if not here: + raise + # Between the delete and the upload the team has no policy, and every phone in it loses the settings. + # A token refused meanwhile is still a token refused, which the operator is asked for again. + kind = Unauthorized if isinstance(exc, Unauthorized) else FleetError + raise kind( + f"policy {name} was being replaced in team {team} and may now be missing ({exc}): " + "sending the policy again puts it back" + ) from exc + LOGGER.info("Uploaded policy %s to team %s", name, team) + + def _policy_in_fleet(self, profile_uuid: str) -> dict[str, Any]: + """The policy as Fleet holds it; without alt=media this answers with metadata only""" + return self._call("GET", f"/api/latest/fleet/configuration_profiles/{profile_uuid}?alt=media") + + def resend_policy(self, team: int, phones: list[Phone], name: str = POLICY_NAME) -> int: + """Upload the team's policy again if any of the phones enrolled after it was last sent + + Answers how many did, 0 when nothing was sent. Measured on Fleet 4.90.1: a phone that + enrols is sent our policy, and seconds later Fleet can write one holding only its status + reporting over it. Fleet goes on showing ours as verified there and never sends it again, + so the phone installs its certificate and Chrome is not allowed to use it. The same + policy uploaded again reaches the phone and leaves its certificate and apps alone. + + Fleet's own copy is what goes, so no template is needed. A phone that enrols again onto its + old host keeps its old last_enrolled_at, and is not seen here: apply --force-policy reaches it. + """ + profiles = self._call("GET", f"/api/latest/fleet/configuration_profiles?team_id={team}").get("profiles", []) + profile = next((p for p in profiles if p.get("name") == name), None) + if not profile: + return 0 + sent = _moment(str(profile.get("updated_at") or profile.get("created_at") or "")) + later = [phone for phone in phones if phone.enrolled and _moment(phone.enrolled) > sent] + if later: + self.ensure_policy(team, self._policy_in_fleet(profile["profile_uuid"]), name=name, force=True) + return len(later) + + def ensure_link_app(self, team: int, title: str, url: str) -> str: + """A managed web app, so the deployment has an icon on the launcher + + Looked up before publishing, because publishing twice does not yield one app. Google was + expected to derive the package name from the url and so dedupe a repeat of the same url; + it does not. One url published twice gave two package names, so every re-run left another + launcher on the team and another permanent app in the enterprise, Fleet offering no way + to delete one. + + So the deployment goes in the published title and the title is the identity -- its first + DNS label rather than the whole host, because Google refuses a title of 30 characters or + more; see _published_title. Fleet never hands a web app's url back, and the team does not + identify a deployment either -- the original bug was a new deployment reusing the team + name of the one it replaced, finding "Deploy App" already there, and handing every device + an icon for the decommissioned host. Naming the deployment makes a re-run match and a + move not match, which is exactly the distinction we cannot otherwise draw. + + Fleet lists a web app under its package name until a device reports the title, so apply() + sets the display name straight after assigning it. A run that stops in between leaves an + app this lookup cannot see; the conflict below says how to recover it. + + The icon is required rather than decorative -- without one Google never publishes the app + and every device reports the install as NOT_FOUND. + """ + title = self._published_title(title, url) + published = self._link_app_in_team(team, title) + if published: + LOGGER.info("Launcher web app %s already published to team %s, reusing it", published, team) + return published + try: + created = self._upload( + "/api/latest/fleet/software/web_apps", + {"title": title, "url": url}, + "icon.png", + launcher_icon(), + file_field="icon", + content_type="image/png", + ) + except FleetError as exc: + # A conflict means the name is already published to the enterprise. Re-read the team, + # because publishing is asynchronous and the lookup above can lose that race. + # + # There is nothing else to try. Checked against Fleet 4.90: a web app whose team was + # deleted appears in no listing at all -- not unscoped, not under team_id=0 -- while + # remaining published, because a web app cannot be deleted. So a recreated team + # cannot get its launcher back and the name stays spent. Say so rather than retrying + # somewhere it provably is not. + if "409" not in str(exc) and "already exists" not in str(exc).lower(): + raise + found = self._link_app_in_team(team, title) + if not found: + raise FleetError( + f"the MDM already has a web app named {title!r} but will not show it. A web app cannot be " + "deleted, and it outlives the team it was assigned to, so a team that was deleted and " + "recreated leaves the name taken. First look in this team for a web app with an empty " + "display name: a run that stopped between publishing and naming leaves one, and giving it " + f"the display name {title!r} in the MDM lets this run reuse it. If there is none, the name " + "is spent -- give this deployment a different launcher title, or a host of its own." + ) from exc + LOGGER.info("Launcher web app %s is already published as %r, reusing it", found, title) + return found + + package = str(created.get("app_store_id") or created.get("package_name") or "") + if not package: + raise FleetError(f"the MDM did not name the web app it created: {created}") + LOGGER.info("Launcher web app %s points at %s", package, url) + return package + + @staticmethod + def _published_title(title: str, url: str) -> str: + """The title this deployment publishes under, carrying the deployment's name + + This is what the launcher icon reads on the device, so it is the deployment's name and + not an identifier: one instance per unit means the deployment is the useful half of it. + Its first DNS label, not the whole host, because Google refuses a web app title of 30 + characters or more and a full host rarely fits. + """ + name = (urlparse(url).hostname or "").removeprefix("mtls.").split(".")[0] + room = MAX_WEB_APP_TITLE - len(title) - len(" ()") + if not name or room <= 0: + return title[:MAX_WEB_APP_TITLE] + return f"{title} ({name[:room]})" + + def _link_app_in_team(self, team: int, title: str) -> str: + """This team's published web app of that name, or empty if it has none + + Scoped to the one team on purpose. Searching every team returns another deployment's app, + whose url points at another deployment and cannot be read to find that out. + """ + query = urlencode({"team_id": team, "available_for_install": "true"}) + for existing in self._call("GET", f"/api/latest/fleet/software/titles?{query}").get("software_titles", []): + package = (existing.get("app_store_app") or {}).get("app_store_id", "") + named = title in (existing.get("display_name"), existing.get("name")) + if package.startswith("com.google.enterprise.webapp.") and named: + return str(package) + return "" + + def _authorities(self) -> list[dict[str, Any]]: + """Every certificate authority Fleet has: its id, name and type, not what it serves""" + listed: list[dict[str, Any]] = self._call("GET", "/api/latest/fleet/certificate_authorities").get( + "certificate_authorities", [] + ) + return listed + + def _authority(self, authority_id: int) -> dict[str, Any]: + """One authority in full. The listing does not carry the url, only this does.""" + return self._call("GET", f"/api/latest/fleet/certificate_authorities/{authority_id}") + + def authority_id(self, name: str) -> int: + """An authority that must already be there, by the name a template gives it""" + if not name: + raise FleetError("the template names no certificate authority, and there is no SCEP address to find one by") + authorities = self._authorities() + match = [a for a in authorities if a.get("name") == name] + if not match: + known = ", ".join(sorted(str(a.get("name")) for a in authorities)) or "none" + raise FleetError(f"no certificate authority named {name!r}; the MDM has: {known}") + return int(match[0]["id"]) + + def bound_authority(self, team: int, certificate: str) -> int | None: + """The authority the team's certificate template of that name is bound to; None while the team has none""" + for template in self._call("GET", f"/api/latest/fleet/certificates?team_id={team}").get("certificates", []): + if template.get("name") == certificate: + return int(template.get("certificate_authority_id", 0)) + return None + + def _give_challenge(self, authority_id: int, name: object, scep_url: str, challenge: str) -> None: + """Hand an authority that serves scep_url the window's challenge; without one, leave it as it is""" + if not challenge: + return + # The challenge is never logged. No name in the body: Fleet reads a name on a PATCH as + # a rename and then refuses it as a conflict with the authority's own existing name, + # so sending it turns every update into a 409. + LOGGER.info("Giving certificate authority %s at %s the new challenge", name, scep_url) + self._call( + "PATCH", + f"/api/latest/fleet/certificate_authorities/{authority_id}", + {"custom_scep_proxy": {"url": scep_url, "challenge": challenge}}, + ) + + def ensure_authority(self, scep_url: str, challenge: str, name: str = "", bound: int | None = None) -> int: + """The SCEP CA this Deploy App is, created if the MDM does not have it yet + + Pointing the MDM at a SCEP server is MDM configuration, not protocol, so there is no + standard for it and every MDM words it differently. Fleet happens to expose it, so here + it is one less thing for an operator to get wrong by hand. + + An authority is known by the address it serves, whatever it is called. So every Deploy App + on one Fleet has its own, and one made under the name all of them once shared, or by hand, + is still found. It gets the challenge whenever there is one: RASENMAEHER makes a new one + for every enrolment window, and Fleet never hands the old one back to compare against. + + Only a new one needs a name: the template's, or else authority_name(). A name that serves + another address is refused, never repointed: that would send its phones to this Deploy App. + + bound is the authority the team's certificate template is already bound to: its phones ask + that one and no other, so it gets the challenge or nothing does. If it serves another address, + by a different host or only by a slash, that is refused before anything is changed: a new + authority beside it would take the challenge and leave the team's phones to be refused. + """ + if bound is not None: + held = self._authority(bound) + serves = str(held.get("url") or "") + if _same_case(serves) != _same_case(scep_url): + raise FleetError( + f"the team takes its certificates from authority {held.get('name')}, which serves " + f"{serves or 'another address'}, not {scep_url}, so nothing was changed. If that authority is " + "this Deploy App's, correct its address in Fleet; if not, choose another team." + ) + self._give_challenge(bound, held.get("name"), scep_url, challenge) + return bound + wanted = name or authority_name(scep_url) + # Only a custom SCEP proxy has an address to compare. The likely names are asked first. + proxies = [a for a in self._authorities() if a.get("type", "custom_scep_proxy") == "custom_scep_proxy"] + taken = "" + for listed in sorted(proxies, key=lambda a: a.get("name") not in (wanted, LEGACY_AUTHORITY)): + authority_id = int(listed["id"]) + serves = str(self._authority(authority_id).get("url") or "") + if _same_case(serves) != _same_case(scep_url): + if listed.get("name") == wanted: + taken = serves or "another address" + continue + self._give_challenge(authority_id, listed.get("name"), scep_url, challenge) + return authority_id + if taken: + raise FleetError( + f"certificate authority {wanted} already serves {taken}: give this Deploy App a template that " + "names another authority, or delete that authority in Fleet if the Deploy App moved" + ) + + LOGGER.info("Creating certificate authority %s -> %s", wanted, scep_url) + created = self._call( + "POST", + "/api/latest/fleet/certificate_authorities", + {"custom_scep_proxy": {"name": wanted, "url": scep_url, "challenge": challenge}}, + ) + body = created.get("certificate_authority") or created + return int(body["id"]) + + def ensure_certificate(self, team: int, name: str, subject: str, authority: int) -> int: + """The template the MDM fills in per device, and asks us to sign + + There is no update in place, so a changed subject is delete then create. The name is kept + because it becomes the Android keystore alias, and a device already holding a key under one + alias will not accept a second. + + Refused while the team has devices. Replacing the template makes each of them delete the + certificate it has and ask again, and the deployment refuses a name that is already taken, + so all of them would lose access (measured on Fleet 4.90). + + Refused, devices or none, when the team's template is bound to another authority: a team + takes its certificates from one Deploy App, and replacing the template would enrol that + Deploy App's phones into this one. Fleet keeps an authority while a template is bound to it. + apply() finds that out before it changes anything, through ensure_authority's bound; this + is the same refusal for a caller that names an authority instead. + """ + existing = self._call("GET", f"/api/latest/fleet/certificates?team_id={team}").get("certificates", []) + for template in existing: + if template.get("name") != name: + continue + bound = int(template.get("certificate_authority_id", 0)) + if bound != authority: + other = self._authority(bound) + raise FleetError( + f"team {team} takes its certificates from authority {other.get('name')}, which serves " + f"{other.get('url') or 'another address'}: a team belongs to one Deploy App. Choose another " + "team for this Deploy App." + ) + if template.get("subject_name") == subject: + return int(template["id"]) + devices = len(self._hosts(team)) + if devices: + raise FleetError( + f"replacing certificate template {name} would delete the certificate of {devices} devices in " + f"team {team}, and their names would be refused when they ask again, so the template was left " + "as it is. Use a new team, or empty this one first." + ) + self._call("DELETE", f"/api/latest/fleet/certificates/{template['id']}?team_id={team}") + LOGGER.info("Replacing certificate template %s", name) + + created = self._call( + "POST", + "/api/latest/fleet/certificates", + {"name": name, "team_id": team, "certificate_authority_id": authority, "subject_name": subject}, + ) + LOGGER.info("Certificate template %s asks for %s", name, subject) + return int(created["id"]) + + # --- naming --------------------------------------------------------------- + + def _hosts(self, team: int) -> list[dict[str, Any]]: + """The devices in a team, every page of them""" + found: list[dict[str, Any]] = [] + page = 0 + while True: + query = urlencode({"team_id": team, "page": page, "per_page": HOSTS_PER_PAGE}) + batch = self._call("GET", f"/api/latest/fleet/hosts?{query}").get("hosts") or [] + found.extend(batch) + if len(batch) < HOSTS_PER_PAGE: + return found + page += 1 + + def phones(self, team: int, certificate: str) -> list[Phone]: + """The team's devices in enrolment order, each with its name and its certificate row + + The row is the install of the certificate template called `certificate`. A host can show + an old remove row of the same name beside the new one for a while, and that one is history. + """ + found = [] + for listed in self._hosts(team): + host = self._call("GET", f"/api/latest/fleet/hosts/{listed['id']}").get("host") or {} + users = host.get("end_users") or [] + name = next((str(user["idp_username"]) for user in users if user.get("idp_username")), "") + rows = (host.get("mdm") or {}).get("profiles") or [] + row: dict[str, Any] = next( + (r for r in rows if r.get("name") == certificate and r.get("operation_type") == "install"), {} + ) + found.append( + Phone( + id=int(listed["id"]), + callsign=name.split("@")[0], + model=str(host.get("hardware_model") or ""), + enrolled=str(host.get("last_enrolled_at") or ""), + status=str(row.get("status") or ""), + detail=str(row.get("detail") or ""), + ) + ) + return sorted(found, key=lambda phone: (phone.enrolled, phone.id)) + + def certificate_template(self, team: int, name: str) -> int: + """The id of the team's certificate template of that name""" + for template in self._call("GET", f"/api/latest/fleet/certificates?team_id={team}").get("certificates", []): + if template.get("name") == name: + return int(template["id"]) + raise FleetError(f"team {team} has no certificate template named {name}: set Fleet up first") + + def name_host(self, host: int, callsign: str) -> None: + """Give the host its callsign + + A phone enrols before anybody can name it, so its first request has already failed for + want of a name, and naming it does not send that request again by itself: follow with + resend. Not for a host with no request yet: Fleet has none to send again (404, read in + Fleet 4.90.1's source), and fills the name in when it makes one. + """ + self._call("PUT", f"/api/latest/fleet/hosts/{host}/device_mapping", {"email": callsign, "source": "idp"}) + + def resend(self, host: int, template: int) -> None: + """Have Fleet send the host its certificate request again, for one more attempt + + The phone acts on it at its next check-in. Fleet refuses a request still pending (400), and + that one needs nothing: it is filled in when it goes, with the name the host has by then. + Measured on Fleet 4.90.1. + """ + try: + self._call("POST", f"/api/latest/fleet/hosts/{host}/certificates/{template}/resend") + except FleetError as exc: + if "answered 400" not in str(exc) or "pending" not in str(exc): + raise + + # --- the whole statement -------------------------------------------------- + + def apply( + self, + team_name: str, + template: MdmTemplate, + force_policy: bool = False, + scep_url: str = "", + challenge: str = "", + create_team: bool = True, + ) -> dict[str, Any]: + """State everything the template says, in the order that actually works + + The policy goes in BEFORE the apps: a permission grant only applies to an app that + installs while it is already in force, and the key selection rules are what make the + certificate visible to anything at all. Both have to be true before a device joins, + because that is the only moment apps install. + + Given scep_url, the certificate authority is found by it, or created, so a fresh deployment + needs nothing typed into Fleet by hand. Without it the template must name an authority that + is already there, which is the case for an MDM we cannot create one in. + + Without create_team, a team Fleet lacks is NoTeam before anything is changed. + """ + # Without create_team the team is looked up first, so a team missing leaves Fleet as it was + team = None if create_team else self.team_id(team_name) + # The authority before a team is made: refusing it must leave Fleet as it was, a new team included. + # A team that is there may have its template bound to an authority already: that one is the team's. + authority = 0 + if template.certificate and scep_url: + if team is None: + try: + team = self.team_id(team_name) + except NoTeam: + team = None + bound = self.bound_authority(team, template.certificate.name) if team is not None else None + authority = self.ensure_authority(scep_url, challenge, template.certificate.authority, bound) + elif template.certificate: + authority = self.authority_id(template.certificate.authority) + if team is None: + team = self.team_id(team_name, create=True) + if template.certificate: + self.ensure_certificate(team, template.certificate.name, template.certificate.subject, authority) + self.ensure_policy(team, template.policy, force=force_policy) + + packages = [app.package for app in template.apps] + preinstall = list(template.preinstall_packages) + if template.link_app: + link = self.ensure_link_app(team, template.link_app.title, template.link_app.url) + packages.append(link) + preinstall.append(link) + + assigned = self.assign_apps(team, packages, preinstall) + if template.link_app: + # Fleet lists a new web app under its package name until a device reports it, and the + # lookup that keeps a re-run from publishing another permanent app goes by title. + self._call( + "PATCH", + f"/api/latest/fleet/software/titles/{assigned[link]}/app_store_app", + { + "team_id": team, + "display_name": self._published_title(template.link_app.title, template.link_app.url), + }, + ) + for app in template.apps: + if app.config: + self.set_app_config(team, app.package, app.config) + return { + "team_id": team, + "assigned": sorted(assigned), + "preinstall": sorted(preinstall), + } diff --git a/src/odmdm_connector/fleet_plugin.py b/src/odmdm_connector/fleet_plugin.py new file mode 100644 index 0000000..d6c60c6 --- /dev/null +++ b/src/odmdm_connector/fleet_plugin.py @@ -0,0 +1,264 @@ +"""Fleet behind the MDM contract: the plugin built into the connector + +Registered under the entry point group odmdm_connector.mdm as fleet, as a plugin from another +package would be. What Fleet does on the wire is fleet.FleetMdm's; this turns it into the +contract's phones, states, steps and sentences. +""" + +from collections.abc import Iterator, Mapping, Sequence +from pathlib import Path +from typing import ClassVar +from urllib.parse import urlparse + +from . import template +from .fleet import FleetError, FleetMdm, NoTeam, Unauthorized +from .fleet import Phone as FleetPhone +from .mdm import API_VERSION, Field, MdmError, Phone, State, Step +from .settings import Settings + +#: A phone acts on a request at its next check-in, every 15 minutes +CHECK_IN = "up to 15 minutes" + + +def _state(phone: FleetPhone) -> tuple[State, str]: + """Where the certificate is, and Fleet's words beside it + + The details matched are the ones seen on a live Fleet 4.90.1. After a failure a phone reports, + Fleet asks again by itself up to three times, and that request keeps the failure's detail while + it waits. + """ + if not phone.status: + return State.NO_REQUEST, "" + if phone.status == "verified": + return State.READY, "" + if phone.status == "failed": + return _failure(phone) + if not phone.detail: + return State.WAITING, CHECK_IN + state, detail = _failure(phone) + return State.WAITING, f"{CHECK_IN}; last time: {state.value}{': ' + detail if detail else ''}" + + +def _failure(phone: FleetPhone) -> tuple[State, str]: + """What Fleet's detail on a failed request means""" + if "does not have an IDP user" in phone.detail: + # Naming does not send the request again, so a name beside this detail was given without a resend + return (State.NOT_ASKED, "ask again") if phone.callsign else (State.NEEDS_NAME, "") + if "SCEP enrollment failed" in phone.detail: + return State.REFUSED, "name taken or not allowed, enrolment closed, or Fleet has an old challenge" + if "Network error" in phone.detail: + return State.UNREACHABLE, "" + # Nothing seen on a live Fleet yet: Fleet's own words, as a failure the phone can be asked again after + return State.FAILED, phone.detail + + +def _refused(exc: FleetError, named: Mapping[str, str] | None = None, lines: Sequence[str] = ()) -> MdmError: + """Fleet's refusal as the contract's, marked when Fleet does not accept the token""" + return MdmError(f"Fleet refused: {exc}", named, lines, unauthorized=isinstance(exc, Unauthorized)) + + +class FleetPlugin: + """FleetDM: a team and a certificate authority per Deploy App, any number of them on one Fleet""" + + API_VERSION: ClassVar[int] = API_VERSION + title: ClassVar[str] = "Fleet" + fields: ClassVar[tuple[Field, ...]] = ( + Field("mdm_url", "Fleet address", help="The address you open Fleet at, starting with https://", required=True), + Field( + "token", + "API token", + secret=True, + help=( + "A global admin's API token: in Fleet, My account, Get API token. That one ends with that sign-in, " + "after 5 days by default; an API-only user's does not." + ), + required=True, + ), + Field( + "team", + "Team", + default="{deployment} DeployApp", + help="The team phones enrol into and get the certificate in", + required=True, + ), + Field( + "template", + "Template", + help="A template file; without one, the one shipped with the connector", + advanced=True, + ), + Field( + "key_alias", + "Key alias", + default="rmscep", + help="The certificate template's name, the Android keystore alias. Never change it for a deployment", + advanced=True, + ), + ) + missing: ClassVar[Mapping[str, str]] = {} + + def __init__(self, values: Mapping[str, str]) -> None: + given = {item.key: values.get(item.key) or item.default_for("") for item in self.fields} + self._url = given["mdm_url"] + self._token = given["token"] + self.team = given["team"] + self.template = Path(given["template"]) if given["template"] else template.EXAMPLE + self.key_alias = given["key_alias"] + self._api: FleetMdm | None = None + self._team_id = 0 + + def _fleet(self) -> FleetMdm: + """Fleet's API, checked only once it is needed, so a dry run needs no token""" + if self._api: + return self._api + if not self._url: + raise MdmError("The Fleet address is missing") + if urlparse(self._url).scheme != "https": + raise MdmError( + "The MDM address must start with https://, or the API token would cross the network readable" + ) + if not self._token: + raise MdmError("The Fleet API token is missing") + if not self.team: + raise MdmError("The Fleet team is missing") + self._api = FleetMdm(self._url, self._token) + return self._api + + def _template(self, window: Settings) -> template.MdmTemplate: + """The template with this deployment's values filled in""" + try: + return template.load( + self.template, domain=urlparse(window.scep_url).hostname or "", key_alias=self.key_alias + ) + except template.TemplateError as exc: + raise MdmError(f"Template refused: {exc}") from exc + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + """State what the template says, in the order FleetMdm.apply knows works + + force sends the policy again even if Fleet's copy is unchanged, to reach a phone that just + joined. It is a repair, so it makes no team: a team Fleet lacks is refused before anything + is changed. + """ + wanted = self._template(window) + lines = [f" {app.package}{' (at enrolment)' if app.preinstall else ' (on demand)'}" for app in wanted.apps] + if wanted.link_app: + lines.append(f" launcher link {wanted.link_app.title!r} -> {wanted.link_app.url}") + label = f"Template names {len(wanted.apps)} apps, {len(wanted.preinstall_packages)} installed at enrolment" + yield Step(label, True, "\n".join(lines)) + if dry_run: + return + try: + result = self._fleet().apply( + self.team, + wanted, + force_policy=force, + scep_url=window.scep_url, + challenge=window.challenge, + create_team=not force, + ) + except NoTeam as exc: + raise MdmError( + f"Fleet has no team named {self.team}, so nothing was changed: sending the policy again makes no " + "team. Check the team's name." + ) from exc + except FleetError as exc: + raise _refused(exc) from exc + yield Step(f"Applied to team {self.team} ({result['team_id']}): {len(result['assigned'])} apps assigned", True) + + def set_challenge(self, window: Settings) -> None: + """Give this Deploy App's certificate authority the window's challenge, and change nothing else""" + wanted = self._template(window) + if not wanted.certificate: + raise MdmError("The template states no certificate, so there is no authority to give it to") + api = self._fleet() + try: + # The team's phones ask the authority its certificate template is bound to: that one gets the challenge + try: + bound = api.bound_authority(api.team_id(self.team), wanted.certificate.name) + except NoTeam: + bound = None + api.ensure_authority(window.scep_url, window.challenge, wanted.certificate.authority, bound) + except FleetError as exc: + raise _refused(exc) from exc + + def _phones(self) -> dict[str, FleetPhone]: + """The team's phones by id, read now: never kept between calls, so nothing shown is stale""" + api = self._fleet() + try: + self._team_id = api.team_id(self.team) + return {str(phone.id): phone for phone in api.phones(self._team_id, self.key_alias)} + except FleetError as exc: + raise _refused(exc) from exc + + def phones(self) -> list[Phone]: + return [ + Phone(key, phone.callsign, phone.model, phone.enrolled, *_state(phone)) + for key, phone in self._phones().items() + ] + + def _policy_again(self, found: dict[str, FleetPhone]) -> list[str]: + """Send the policy again if a phone enrolled after it was last sent, as Fleet may have overwritten it there""" + later = self._fleet().resend_policy(self._team_id, list(found.values())) + if not later: + return [] + return [f"Policy sent again: {later} phone{'' if later == 1 else 's'} enrolled after it was last sent"] + + def name(self, names: Mapping[str, str]) -> list[str]: + """Name each host, have Fleet send its certificate request again, then the policy if needed + + A phone that has its certificate under the name is left alone: asked again under the name + it holds, it is refused as taken, and a working phone then shows as refused. + """ + found = self._phones() + unknown = [key for key in names if key not in found] + if unknown: + raise MdmError(f"Nothing named: host {unknown[0]} is not in the team") + api = self._fleet() + lines: list[str] = [] + named: dict[str, str] = {} + try: + certificate = api.certificate_template(self._team_id, self.key_alias) + for key, callsign in names.items(): + old = found[key] + if old.status == "verified" and old.callsign.lower() == callsign.lower(): + lines.append(f"Phone {key} is already {old.callsign}") + continue + api.name_host(old.id, callsign) + named[key] = callsign + if old.status: + api.resend(old.id, certificate) + line = f"Phone {key} is {callsign}" + if not old.status: + line += ". Fleet has no certificate request for it, so nothing was sent" + elif old.status == "verified" and old.callsign: + line += ( + f". It was {old.callsign} and still has that certificate: revoke {old.callsign} in Deploy App." + ) + lines.append(line) + if named: + lines += self._policy_again(found) + except FleetError as exc: + raise _refused(exc, named, lines) from exc + return lines + + def ask_again(self, ids: Sequence[str]) -> list[str]: + """Resend the hosts' certificate requests; no ids: every named phone whose request failed""" + found = self._phones() + unknown = [key for key in ids if key not in found] + if unknown: + raise MdmError(f"Nothing sent: host {unknown[0]} is not in the team") + chosen = list(ids) or [key for key, phone in found.items() if phone.status == "failed" and phone.callsign] + if not chosen: + return [] + api = self._fleet() + lines: list[str] = [] + try: + certificate = api.certificate_template(self._team_id, self.key_alias) + for key in chosen: + api.resend(found[key].id, certificate) + lines.append(f"Phone {key} ({found[key].callsign or 'no name'}): certificate asked for again") + lines += self._policy_again(found) + except FleetError as exc: + raise _refused(exc, lines=lines) from exc + return lines diff --git a/src/odmdm_connector/icon.py b/src/odmdm_connector/icon.py new file mode 100644 index 0000000..7584ff8 --- /dev/null +++ b/src/odmdm_connector/icon.py @@ -0,0 +1,31 @@ +"""A launcher icon, generated rather than shipped + +Google will not publish a managed web app without one, and a web app it has not published is +accepted by the MDM but reports NOT_FOUND on every device that tries to install it. Square and at +least 512x512 are enforced. Generating it avoids carrying a binary in the repository for something +no one will look at twice. +""" + +import struct +import zlib + + +def launcher_icon(size: int = 512) -> bytes: + """A plain square PNG, no dependencies""" + + def chunk(tag: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + + rows = [] + for y in range(size): + pixels = bytearray() + for x in range(size): + inside = abs(x - size // 2) < size // 3 and size // 6 < y < size * 5 // 6 + pixels += bytes((0x0D, 0x47, 0xA1) if inside else (0x10, 0x1A, 0x24)) + rows.append(b"\x00" + bytes(pixels)) + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(b"".join(rows), 9)) + + chunk(b"IEND", b"") + ) diff --git a/src/odmdm_connector/mdm.py b/src/odmdm_connector/mdm.py new file mode 100644 index 0000000..3d1a02d --- /dev/null +++ b/src/odmdm_connector/mdm.py @@ -0,0 +1,187 @@ +"""What the connector needs an MDM to be able to do: the one contract every MDM plugin implements + +Standard library only, so a plugin depends on nothing but this package. A plugin is a class that +satisfies Mdm, published under the entry point group ``odmdm_connector.mdm``. The connector checks +the class's API_VERSION before it uses it. + +Every sentence a plugin hands back, a Step's message, a line from name or ask_again, an MdmError, +is shown to the operator as it is, by the command line and the page alike, so it names no +command, option or button. The SCEP challenge is never in one. +""" + +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import dataclass +from enum import Enum +from typing import ClassVar, Protocol + +from .settings import HOST, Settings + +API_VERSION = 1 + +#: The capabilities an MDM may lack, as named in Mdm.missing +SETUP = "setup" +SET_CHALLENGE = "set_challenge" +ASK_AGAIN = "ask_again" +#: setup with force: the policy sent to the phones again even if unchanged +SEND_POLICY = "send_policy" +CAPABILITIES = (SETUP, SET_CHALLENGE, ASK_AGAIN, SEND_POLICY) +#: In a Field's default, the deployment's name: the first label of its Deploy App's host +DEPLOYMENT = "{deployment}" + + +class State(Enum): + """Where a phone's certificate is, its value being the sentence shown to the operator""" + + NO_REQUEST = "no certificate requested" + NEEDS_NAME = "waiting for a name" + NOT_ASKED = "named, but its certificate was not asked for again" + WAITING = "requested, waiting for the phone" + READY = "has its certificate" + REFUSED = "refused by Deploy App" + UNREACHABLE = "could not reach Deploy App" + #: A failure that is neither a refusal nor Deploy App out of reach + FAILED = "failed" + + +@dataclass(frozen=True) +class Phone: + """A phone in the MDM's group for one Deploy App""" + + #: The MDM's own id for it, opaque to the connector + id: str + #: Empty while nobody has named it + callsign: str + model: str + #: When it joined, as an ISO time + joined: str + state: State + #: The plugin's own extra words for the operator, shown after the state; may be empty + detail: str = "" + + +@dataclass(frozen=True) +class Field: + """A setup value a plugin needs, such as its MDM's address + + A secret is never taken from an option or a plain environment variable, only from a file. + A required one must be given: the page does not connect without it, and the command line + says how to give it. DEPLOYMENT in the default stands for the deployment's name, so that + "{deployment} DeployApp" is "golden-monkey DeployApp" for golden-monkey.example.fi. + """ + + key: str + label: str + secret: bool = False + default: str = "" + help: str = "" + required: bool = False + #: Rarely changed: the page shows it only when asked + advanced: bool = False + + def default_for(self, host: str) -> str: + """The default for the Deploy App on this host; none when it names the deployment and the host is not one + + The host is trimmed and taken in lower case, so the page and the command line give the same + default for the same Deploy App; anything but a plain DNS name, such as an address with its + scheme, gives none. + """ + if DEPLOYMENT not in self.default: + return self.default + host = host.strip().lower() + if not HOST.fullmatch(host): + return "" + return self.default.replace(DEPLOYMENT, host.split(".")[0]) + + +@dataclass(frozen=True) +class Step: + """One step of setup, as it is reported""" + + label: str + done: bool + message: str = "" + + +class MdmError(Exception): + """The one error a plugin raises, its text a sentence for the operator + + named holds the phones a batch had already named when it stopped, by id, so the operator names + only the rest. lines holds the lines already due to the operator when it stopped, such as which + old callsign to revoke, shown before the error. unauthorized says the MDM did not accept the + secret it was given, such as an expired token: the connector then lets go of it and asks for it + again. + """ + + def __init__( + self, + message: str, + named: Mapping[str, str] | None = None, + lines: Sequence[str] = (), + unauthorized: bool = False, + ) -> None: + super().__init__(message) + self.named: dict[str, str] = dict(named or {}) + self.lines: list[str] = list(lines) + self.unauthorized = unauthorized + + +class Mdm(Protocol): + """One MDM, configured for one Deploy App's group of phones""" + + API_VERSION: ClassVar[int] + #: The MDM's name as an operator knows it + title: ClassVar[str] + fields: ClassVar[tuple[Field, ...]] + #: For each capability in CAPABILITIES this MDM lacks, what to tell the operator instead. The + #: command line never calls a capability listed here; called anyway, it raises MdmError. + missing: ClassVar[Mapping[str, str]] + + def __init__(self, values: Mapping[str, str]) -> None: + """values: the fields' values by key""" + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + """Set the MDM up for this Deploy App, first time or again + + Idempotent. Never replaces a certificate template on a group that has phones. dry_run + checks what would be stated and stops before the MDM is changed. force sends the policy to + the phones again even if unchanged, for a phone whose policy the MDM overwrote; the phones + keep their certificates and apps. An MDM that cannot lists SEND_POLICY in missing. + """ + + def set_challenge(self, window: Settings) -> None: + """Give the MDM the challenge of the enrolment window just opened, and change nothing else""" + + def phones(self) -> list[Phone]: + """The group's phones, oldest first""" + + def name(self, names: Mapping[str, str]) -> list[str]: + """Give phones their callsigns, by id, and do what the MDM needs for their certificates + + Answers the lines to show the operator. Raises MdmError for an id not in the group, and with + named filled in when it stopped half-way. + """ + + def ask_again(self, ids: Sequence[str]) -> list[str]: + """Have the phones ask for their certificates again + + No ids means every named phone whose state is NOT_ASKED, REFUSED, UNREACHABLE or FAILED. + Answers the lines to show the operator, none when nothing was asked. + """ + + +__all__ = [ + "API_VERSION", + "ASK_AGAIN", + "CAPABILITIES", + "DEPLOYMENT", + "SEND_POLICY", + "SETUP", + "SET_CHALLENGE", + "Field", + "Mdm", + "MdmError", + "Phone", + "Settings", + "State", + "Step", +] diff --git a/src/odmdm_connector/plugins.py b/src/odmdm_connector/plugins.py new file mode 100644 index 0000000..8eaae42 --- /dev/null +++ b/src/odmdm_connector/plugins.py @@ -0,0 +1,102 @@ +"""The MDM plugins installed, found through the entry point group odmdm_connector.mdm + +Fleet is registered there by this package, exactly as a plugin from another package is. Listing +imports nothing; loading imports the one entry point chosen and no other, because a plugin is code +that sees the MDM token. +""" + +import re +from dataclasses import dataclass, field +from importlib.metadata import EntryPoint, entry_points + +from .mdm import API_VERSION, Mdm + +GROUP = "odmdm_connector.mdm" +#: The distribution whose plugins are built in +CONNECTOR = "odmdm-connector" +#: What a plugin class declares besides its API_VERSION, read before any instance is made +DECLARED = ("title", "fields", "missing") + + +class PluginError(Exception): + """An installed plugin the connector cannot use, said in a sentence for the operator""" + + +class NotInstalled(PluginError): + """No plugin of that name is installed""" + + +@dataclass(frozen=True) +class Plugin: + """One installed MDM plugin, as its package declares it""" + + name: str + #: The distribution that declares it, and its version + package: str + version: str + entry: EntryPoint = field(repr=False, compare=False) + + @property + def built_in(self) -> bool: + """Whether it comes with the connector itself: declared by it, and code of its own package""" + module = self.entry.module + return re.sub(r"[-_.]+", "-", self.package).lower() == CONNECTOR and ( + module == __package__ or module.startswith(f"{__package__}.") + ) + + +def _declared() -> list[Plugin]: + """Every entry point of the group, without importing any; tests replace this""" + return [ + Plugin(entry.name, entry.dist.name if entry.dist else "", entry.dist.version if entry.dist else "", entry) + for entry in entry_points(group=GROUP) + ] + + +def installed() -> list[Plugin]: + """The installed plugins, the built-in ones first; PluginError when two packages claim one name""" + found: dict[str, Plugin] = {} + for plugin in _declared(): + other = found.get(plugin.name) + if other: + raise PluginError( + f"Two packages declare the MDM {plugin.name}: {other.package} {other.version} and " + f"{plugin.package} {plugin.version}. Uninstall one" + ) + found[plugin.name] = plugin + return sorted(found.values(), key=lambda plugin: (not plugin.built_in, plugin.name)) + + +def find(name: str) -> Plugin: + """The installed plugin of that name, not imported; NotInstalled if there is none""" + for plugin in installed(): + if plugin.name == name: + return plugin + raise NotInstalled(f"No MDM named {name} is installed") + + +def load(name: str) -> type[Mdm]: + """The class of the MDM of that name, importing that one entry point and no other + + PluginError when it cannot be imported, speaks another version of the contract, or does not + declare its title, fields and missing. + """ + plugin = find(name) + try: + loaded = plugin.entry.load() + except (ImportError, AttributeError) as exc: + raise PluginError(f"The MDM {name} from {plugin.package} {plugin.version} cannot be loaded: {exc}") from exc + version = getattr(loaded, "API_VERSION", None) + if version != API_VERSION: + raise PluginError( + f"The MDM {name} from {plugin.package} {plugin.version} needs a connector that speaks MDM API " + f"version {version}; this one speaks version {API_VERSION}" + ) + lacking = [attribute for attribute in DECLARED if not hasattr(loaded, attribute)] + if lacking: + raise PluginError( + f"The MDM {name} from {plugin.package} {plugin.version} does not declare {', '.join(lacking)}, " + "so it cannot be used" + ) + chosen: type[Mdm] = loaded + return chosen diff --git a/src/odmdm_fleet/py.typed b/src/odmdm_connector/py.typed similarity index 100% rename from src/odmdm_fleet/py.typed rename to src/odmdm_connector/py.typed diff --git a/src/odmdm_connector/settings.py b/src/odmdm_connector/settings.py new file mode 100644 index 0000000..346c285 --- /dev/null +++ b/src/odmdm_connector/settings.py @@ -0,0 +1,99 @@ +"""The settings line Deploy App's MDM page copies for the connector + +Version 1 is four fields separated by whitespace:: + + ODMDM1 /> + +It is the same for every MDM and carries no names. The challenge is a secret: nothing here puts it +in a message. +""" + +import datetime +import re +from dataclasses import dataclass, field +from urllib.parse import urlsplit + +MARK = "ODMDM1" +CHALLENGE = re.compile(r"[0-9a-f]{32}") +CLOSES = "%Y-%m-%dT%H:%M:%SZ" +#: A plain DNS name: letters, digits and inner hyphens in labels separated by dots, at least two labels +HOST = re.compile(r"[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+") +URL = ( + "The SCEP URL in the settings line must be https:///, with a plain host name and nothing else " + "before the path." +) + + +class SettingsError(ValueError): + """The line is not one the connector can use""" + + +@dataclass(frozen=True) +class Settings: + """What one enrolment window gives the MDM + + closes is None for a bare challenge typed without its line, which says nothing of the window. + """ + + scep_url: str + challenge: str = field(repr=False) + closes: datetime.datetime | None = None + + +def is_line(value: str) -> bool: + """Whether the value is meant as a settings line rather than a bare challenge + + A challenge is one word, so a value with whitespace inside it, or with the mark in any case, + is meant as a line. + """ + return len(value.split()) > 1 or value.strip().upper().startswith("ODMDM") + + +def _scep_url(url: str) -> str: + """The URL with its host in lower case, if it is https:/// and nothing else; else empty + + No user name, password, port, query or fragment, and no backslash anywhere: Python and a browser + read a URL such as https://evil.example\\@unit.example.fi/scep as two different hosts, which is how a + crafted line could pass for a known Deploy App. The host is a plain DNS name, so that no + look-alike letter, percent sign, semicolon or control character makes a name that looks like + a real one. + """ + try: + parts = urlsplit(url) + except ValueError: + return "" + host = parts.hostname or "" + if ( + parts.scheme == "https" + and HOST.fullmatch(host) + and parts.netloc.lower() == host + and parts.path.strip("/") + and not any(mark in url for mark in "\\?#") + ): + return f"https://{host}{parts.path}" + return "" + + +def parse(line: str, now: datetime.datetime) -> Settings: + """The line's values, or SettingsError saying why not + + now is the current time with its time zone, given by the caller; a closing time in a message is + in that time zone. + """ + fields = line.split() + if len(fields) != 4 or fields[0] != MARK: + raise SettingsError(f"This is not a settings line: it has four parts and starts with {MARK}.") + _, given, challenge, closes = fields + url = _scep_url(given) + if not url: + raise SettingsError(URL) + if not CHALLENGE.fullmatch(challenge): + raise SettingsError("The challenge in the settings line must be 32 lowercase hex characters.") + try: + when = datetime.datetime.strptime(closes, CLOSES).replace(tzinfo=datetime.UTC) + except ValueError as exc: + raise SettingsError(f"The closing time {closes!r} is not YYYY-MM-DDTHH:MM:SSZ.") from exc + if when <= now: + at = when.astimezone(now.tzinfo).strftime("%H:%M") + raise SettingsError(f"The enrolment window closed at {at}: open a new one in Deploy App.") + return Settings(scep_url=url, challenge=challenge, closes=when) diff --git a/src/odmdm_connector/static/app.css b/src/odmdm_connector/static/app.css new file mode 100644 index 0000000..6372076 --- /dev/null +++ b/src/odmdm_connector/static/app.css @@ -0,0 +1,1210 @@ +/* Deploy App's dark look: setting up is one card at a time, as its login is; the daily work is the + earlier window's layout across the whole width, with the browser's own dialogs over it */ + +:root { + --page: #1a1a1a; + --text: #ffffff; + --muted: #a3a3a3; + --dim: #808080; + --card: #222222; + --raise: #2a2a2a; + --table: #1e1e1e; + --line: #333333; + --line-strong: #444444; + --field: #1c1c1c; + --main: #ff6b1a; + --main-press: #e85d10; + --main-done: #a14a17; + --amber: #f5a524; + --red: #ff6b6b; + --green: #4cc38a; + color-scheme: dark; +} + +* { + box-sizing: border-box; +} + +html { + background: var(--page); +} + +body { + margin: 0; + background: var(--page); + color: var(--text); + font-family: "Geist Mono", ui-monospace, Menlo, Consolas, monospace; + font-size: 15px; + line-height: 1.45; +} + +button { + font: inherit; + color: inherit; + cursor: pointer; +} + +button:disabled { + cursor: default; +} + +p { + margin: 0 0 16px; + overflow-wrap: anywhere; +} + +h1 { + font-size: 18px; + margin: 0 0 6px; + overflow-wrap: anywhere; +} + +/* A Deploy App's name in a title: whole on its line, broken only when wider than the line */ +.name { + display: inline-block; + max-width: 100%; + overflow-wrap: anywhere; +} + +h2 { + font-size: 15px; + margin: 8px 0 8px; +} + +h3 { + font-size: 15px; + margin: 0 0 10px; + overflow-wrap: anywhere; +} + +.muted { + color: var(--muted); +} + +.error { + color: var(--red); +} + +.warn { + color: var(--amber); +} + +[hidden] { + display: none !important; +} + +input[type="text"]:focus-visible, +textarea:focus-visible { + outline: none; + box-shadow: 0 0 0 1px var(--main); +} + +button:focus-visible, +input[type="checkbox"]:focus-visible, +summary:focus-visible, +a:focus-visible, +tr:focus-visible { + outline: 2px solid var(--main); + outline-offset: 2px; +} + +/* Buttons */ + +.main, +.second { + display: block; + width: 100%; + min-height: 56px; + border-radius: 10px; + font-weight: 700; + margin: 0 0 12px; + padding: 8px 16px; +} + +.main { + background: var(--main); + color: #ffffff; + border: 1px solid var(--main); +} + +.main:hover:not(:disabled) { + background: var(--main-press); +} + +.main:disabled { + opacity: 0.45; +} + +.main.plain { + background: transparent; + border-color: var(--line-strong); +} + +.main.danger { + background: transparent; + color: var(--red); + border-color: var(--red); +} + +.second { + background: transparent; + border: 1px solid var(--line-strong); +} + +.second:hover:not(:disabled), +.choice:hover, +.tool:hover:not(:disabled) { + border-color: var(--main); +} + +.back { + background: none; + border: 0; + padding: 0; + color: var(--muted); + text-decoration: underline; + text-underline-offset: 3px; +} + +.back:hover { + color: var(--text); +} + +.choice { + display: block; + width: 100%; + min-height: 56px; + background: var(--field); + border: 1px solid var(--line); + border-radius: 10px; + text-align: left; + padding: 12px 16px; + margin: 0 0 12px; +} + +.choice strong { + display: block; + overflow-wrap: anywhere; +} + +.choice span { + color: var(--muted); + font-size: 13px; +} + +.closing { + color: var(--amber); +} + +.closed { + color: var(--red); +} + +/* Inputs */ + +label { + display: block; + margin: 0 0 8px; +} + +input[type="text"], +textarea { + display: block; + width: 100%; + min-height: 48px; + background: var(--field); + color: var(--text); + border: 1px solid var(--line); + border-radius: 10px; + padding: 12px; + font: inherit; + margin: 0 0 20px; +} + +input[type="text"]:focus, +textarea:focus { + border-color: var(--main); +} + +input::placeholder, +textarea::placeholder { + color: #6b6b6b; +} + +/* A secret is plain text to the browser, so that no password manager offers to keep it, and masked here */ +.secret { + -webkit-text-security: disc; +} + +textarea { + resize: vertical; + line-height: 1.3; +} + +input[type="checkbox"] { + width: 18px; + height: 18px; + margin: 0; + accent-color: var(--main); +} + +.check { + display: flex; + gap: 10px; + align-items: center; + margin: -6px 0 22px; +} + +.hint { + font-size: 13px; + margin: -12px 0 20px; +} + +/* ---------- Setting up: one card, one thing ---------- */ + +body.cards { + min-height: 100vh; + padding: 64px 16px 48px; +} + +.brand { + text-align: center; + color: var(--muted); + font-size: 14px; + letter-spacing: 0.04em; + margin-bottom: 28px; + overflow-wrap: anywhere; +} + +.card { + max-width: 28rem; + margin: 0 auto; + background: var(--card); + border: 1px solid var(--line); + border-radius: 16px; + padding: 24px; +} + +.lead { + color: var(--muted); + margin: 0 0 22px; +} + +.topline { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + font-size: 13px; + color: var(--muted); + margin-bottom: 12px; +} + +/* How far a first set-up is: three parts, each named under its line */ +.progress { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 6px; + list-style: none; + margin: 0 0 24px; + padding: 0; +} + +.progress li { + border-top: 4px solid var(--line-strong); + padding-top: 6px; + font-size: 12px; + color: var(--dim); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.progress li.done { + border-color: var(--main-done); + color: var(--muted); +} + +.progress li.now { + border-color: var(--main); + color: var(--text); + font-weight: 700; +} + +/* A picture of the button on Deploy App's page: nothing here to press */ +.lookfor { + border: 1px dashed #4a4a4a; + border-radius: 12px; + padding: 14px 16px 16px; + margin: 0 0 18px; + text-align: center; + pointer-events: none; + user-select: none; +} + +.lookfor small { + display: block; + color: var(--muted); + font-size: 12px; + margin-bottom: 10px; +} + +.lookfor span { + display: inline-block; + border-radius: 8px; + background: var(--main); + color: #ffffff; + font-weight: 700; + font-size: 14px; + padding: 10px 16px; +} + +.waiting { + display: flex; + align-items: center; + gap: 10px; + color: var(--muted); + margin: 0; +} + +.pulse { + flex: none; + width: 9px; + height: 9px; + border-radius: 50%; + background: var(--main); + animation: pulse 1.6s ease-in-out infinite; +} + +@keyframes pulse { + 50% { + box-shadow: 0 0 0 5px rgba(255, 107, 26, 0.25); + opacity: 0.6; + } +} + +@media (prefers-reduced-motion: reduce) { + .pulse { + animation: none; + } +} + +.or { + display: flex; + align-items: center; + gap: 12px; + color: var(--muted); + font-size: 11px; + margin: 20px 0; +} + +.or::before, +.or::after { + content: ""; + flex: 1; + border-top: 1px solid var(--line); +} + +.athand { + border-top: 1px solid var(--line); + margin-top: 8px; + padding-top: 14px; + font-size: 13px; + color: var(--muted); +} + +.athand strong { + color: var(--text); +} + +.athand ul { + margin: 6px 0 0; + padding-left: 18px; +} + +.box { + background: var(--field); + border: 1px solid var(--line); + border-radius: 10px; + padding: 12px; + margin: 0 0 16px; + color: var(--muted); + font-size: 13px; + overflow-wrap: anywhere; +} + +.note { + border: 1px solid var(--amber); + border-radius: 10px; + padding: 12px 16px; + margin: 0 0 20px; +} + +.note p { + margin: 0 0 8px; +} + +.note p:last-child { + margin: 0; +} + +details.more { + border-top: 1px solid var(--line); + padding-top: 12px; + margin: 0 0 20px; +} + +details.more summary { + color: var(--muted); + cursor: pointer; + margin-bottom: 14px; +} + +/* The setup's steps as the connector reports them */ +ul.run { + list-style: none; + margin: 0 0 20px; + padding: 0; +} + +ul.run li { + display: grid; + grid-template-columns: 22px 1fr; + padding: 6px 0; + overflow-wrap: anywhere; +} + +ul.run li::before { + grid-row: span 3; +} + +ul.run li.done::before { + content: "✓"; + color: var(--green); +} + +ul.run li.now::before { + content: "◌"; + color: var(--amber); +} + +ul.run li.hand::before { + content: "→"; + color: var(--amber); +} + +/* What a step adds under its label: one line of it per line */ +ul.run li > span { + color: var(--muted); + font-size: 14px; + white-space: pre-line; +} + +.copyrow { + display: flex; + gap: 8px; + margin-top: 8px; +} + +.copyrow input[type="text"] { + flex: 1; + min-width: 0; + min-height: 40px; + margin: 0; + padding: 8px 10px; + font-size: 13px; +} + +/* ---------- The phones: the earlier window, dark, across the width ---------- */ + +body.app #view { + display: flex; + flex-direction: column; + min-height: 100vh; +} + +.top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 10px 24px; + border-bottom: 1px solid var(--line); + font-size: 14px; + color: var(--muted); +} + +.top .name { + white-space: nowrap; +} + +.picker { + display: inline-flex; + align-items: baseline; + gap: 8px; + min-width: 0; + min-height: 36px; + padding: 7px 12px; + background: var(--card); + border: 1px solid var(--line); + border-radius: 8px; + white-space: nowrap; +} + +.picker small { + color: var(--muted); + font-size: 13px; +} + +.picker strong { + font-weight: 400; + overflow: hidden; + text-overflow: ellipsis; +} + +.picker:hover { + border-color: var(--main); +} + +.work { + flex: 1; + display: flex; + flex-direction: column; + min-height: 0; + padding: 16px 24px 0; +} + +.app-form { + flex: 1; + display: flex; + flex-direction: column; + min-height: 0; +} + +.window { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 14px; + font-weight: 700; + font-size: 16px; + margin: 0 0 14px; +} + +.window .said { + flex: 0 1 auto; + min-width: 0; + overflow-wrap: anywhere; +} + +.window .dot { + margin-right: 10px; +} + +.window.closing { + color: var(--amber); +} + +.window.closed { + color: var(--red); +} + +.window.none { + color: var(--muted); +} + +.window .tool { + min-height: 34px; + padding: 4px 12px; + font-size: 14px; + font-weight: 400; + color: var(--text); +} + +.out { + line-height: 20px; + color: var(--red); + font-size: 14px; + border: 1px solid var(--line-strong); + border-radius: 8px; + padding: 6px 12px; + text-decoration: none; + white-space: nowrap; +} + +.window.none .out { + color: var(--text); +} + +.out:hover { + border-color: var(--main); +} + +.tools, +.select { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-bottom: 12px; +} + +.tool { + display: inline-block; + width: auto; + min-height: 40px; + margin: 0; + padding: 6px 16px; + border-radius: 8px; + background: var(--card); + border: 1px solid var(--line-strong); + font-weight: 400; + white-space: nowrap; +} + +.tool.go { + background: var(--main); + border-color: var(--main); + color: #ffffff; + font-weight: 700; +} + +.tool:disabled { + opacity: 0.4; +} + +.tool.small { + min-height: 34px; + padding: 4px 12px; + font-size: 14px; +} + +.tool.push { + margin-left: auto; +} + +.select { + font-size: 14px; +} + +.select .count { + margin-left: auto; + color: var(--muted); +} + +/* The table fills what is left of the window and scrolls inside it */ +.table { + flex: 1 1 0; + min-height: 14rem; + overflow: auto; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--table); +} + +.table.settling { + opacity: 0.5; +} + +table { + border-collapse: collapse; + width: 100%; + font-size: 14px; +} + +th, +td { + text-align: left; + vertical-align: top; + padding: 9px 12px; + border-bottom: 1px solid var(--line); + white-space: nowrap; +} + +th { + position: sticky; + top: 0; + z-index: 1; + background: var(--card); + color: var(--muted); + font-weight: 400; +} + +td.cert, +th.cert { + width: 100%; + white-space: normal; + min-width: 10rem; +} + +td.pick, +th.pick { + width: 1%; + padding-right: 0; +} + +.pick input { + vertical-align: -3px; +} + +tbody tr { + cursor: pointer; +} + +tbody tr:hover td { + background: var(--raise); +} + +tr.sel td { + background: #2c2118; +} + +tr.bad td.cert { + color: var(--red); +} + +td.nocall { + color: var(--dim); +} + +tbody tr:hover td.empty { + background: none; +} + +td.empty { + text-align: center; + color: var(--muted); + padding: 72px 16px; + white-space: normal; + border-bottom: 0; + cursor: default; +} + +.dot { + display: inline-block; + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 8px; + vertical-align: 1px; + background: var(--dim); +} + +.dot.ok, +.window.open .dot { + background: var(--green); +} + +.dot.on, +.window.closing .dot { + background: var(--amber); +} + +.dot.bad, +.window.closed .dot { + background: var(--red); +} + +.status { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 10px 24px 12px; + font-size: 13px; + color: var(--muted); +} + +.status > div { + flex: 1; + min-width: 0; +} + +.status .updated { + flex: none; + white-space: nowrap; +} + +.status p { + margin: 0; +} + +.status ul { + margin: 4px 0 0; + padding-left: 18px; +} + +/* The Deploy Apps, under the picker */ +.menu { + position: fixed; + inset: 52px 24px auto auto; + width: 25rem; + max-width: calc(100vw - 32px); + margin: 0; + padding: 6px; + background: var(--card); + color: var(--text); + border: 1px solid var(--line-strong); + border-radius: 12px; + box-shadow: 0 16px 48px rgba(0, 0, 0, 0.55); +} + +.menu .item { + display: grid; + grid-template-columns: 22px 1fr; + width: 100%; + padding: 10px 12px; + background: none; + border: 0; + border-radius: 8px; + text-align: left; +} + +.menu .item:hover, +.menu .item.now { + background: var(--raise); +} + +.menu .item strong { + display: block; + font-weight: 400; + overflow-wrap: anywhere; +} + +.menu .item small { + display: block; + color: var(--muted); + font-size: 13px; +} + +.menu .item small.closing { + color: var(--amber); +} + +.menu .item small.closed { + color: var(--red); +} + +.menu .mark { + color: var(--main); +} + +.menu .act { + display: block; + padding-left: 34px; +} + +.menu .danger { + color: var(--red); +} + +.menu hr { + border: 0; + border-top: 1px solid var(--line); + margin: 6px 0; +} + +/* ---------- Dialogs ---------- */ + +dialog { + width: calc(100% - 32px); + max-width: 760px; + max-height: calc(100vh - 64px); + margin: 48px auto auto; + padding: 0; + background: var(--card); + color: var(--text); + border: 1px solid var(--line-strong); + border-radius: 16px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); +} + +dialog::backdrop { + background: rgba(0, 0, 0, 0.62); +} + +dialog header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + padding: 18px 24px 0; +} + +dialog h2 { + margin: 0; + font-size: 18px; + overflow-wrap: anywhere; +} + +.x { + background: none; + border: 0; + color: var(--muted); + font-size: 22px; + line-height: 1; + padding: 4px 6px; +} + +.x:hover { + color: var(--text); +} + +dialog .body { + padding: 18px 24px 4px; +} + +dialog .body > .error:empty { + display: none; +} + +dialog .body .second { + display: inline-block; + width: auto; + min-height: 40px; + padding: 6px 16px; + font-weight: 400; +} + +dialog footer { + display: flex; + flex-wrap: wrap; + gap: 10px; + align-items: center; + justify-content: flex-end; + padding: 16px 24px 20px; + border-top: 1px solid var(--line); + margin-top: 8px; +} + +dialog footer .main, +dialog footer .second { + width: auto; + min-height: 48px; + margin: 0; + padding: 8px 22px; +} + +dialog footer .check { + margin: 0 auto 0 0; +} + +/* Numbered or from a list */ +.mode { + display: inline-flex; + border: 1px solid var(--line-strong); + border-radius: 10px; + overflow: hidden; + margin-bottom: 16px; +} + +.mode button { + background: none; + border: 0; + padding: 9px 18px; + min-height: 40px; + color: var(--muted); +} + +.mode button[aria-pressed="true"] { + background: var(--raise); + color: var(--text); + box-shadow: inset 0 -3px 0 var(--main); +} + +.inline { + display: flex; + gap: 12px 20px; +} + +.inline .grow { + flex: 0 1 14rem; + min-width: 0; +} + +.inline .num { + flex: 0 0 9rem; +} + +dialog label { + font-size: 13px; + color: var(--muted); + margin-bottom: 6px; +} + +dialog .check { + font-size: 15px; + color: var(--text); + margin-bottom: 0; +} + +dialog h3 { + font-size: 13px; + color: var(--muted); + font-weight: 400; + margin: 0 0 8px; +} + +dialog h3.sect { + color: var(--text); + font-size: 15px; + font-weight: 700; + margin-bottom: 12px; +} + +dialog h3.sect ~ h3.sect { + border-top: 1px solid var(--line); + padding-top: 16px; + margin-top: 4px; +} + +dialog .table.preview { + flex: none; + min-height: 0; + margin-bottom: 12px; +} + +.preview td.will { + font-weight: 700; +} + +.preview tr.bad td { + color: var(--red); +} + +.preview td.why, +.preview th.why { + width: 100%; + white-space: normal; + min-width: 9rem; +} + +.preview tbody tr { + cursor: default; +} + +.preview tbody tr:last-child td { + border-bottom: 0; +} + +dl.facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 8px 18px; + margin: 0 0 16px; +} + +dl.facts dt { + color: var(--muted); +} + +dl.facts dd { + margin: 0; + overflow-wrap: anywhere; +} + +dd.bad { + color: var(--red); +} + +dialog .copyrow { + margin: 0 0 12px; +} + +/* Half a screen: the button rows wrap, the count goes under them and Joined leaves the tables */ +@media (max-width: 720px) { + body.cards { + padding: 32px 16px; + } + + .top, + .work, + .status { + padding-left: 16px; + padding-right: 16px; + } + + .menu { + inset: 52px 16px auto auto; + } + + .select .count { + margin-left: 0; + flex-basis: 100%; + } + + .joined { + display: none; + } + + /* The page scrolls rather than the table, which shows every phone */ + .table { + flex: none; + min-height: 0; + } + + dialog { + margin-top: 16px; + max-height: calc(100vh - 32px); + } + + dialog header, + dialog .body, + dialog footer { + padding-left: 16px; + padding-right: 16px; + } + + .inline .grow { + flex: 1 1 auto; + } + + dialog footer .check { + flex-basis: 100%; + } +} + +/* A phone's width: Callsign and Certificate stay readable without scrolling sideways */ +@media (max-width: 480px) { + .phone, + .picker small { + display: none; + } + + .card { + padding: 20px 16px; + } + + .inline .num { + flex-basis: 7.5rem; + } + + th, + td { + padding: 8px; + } + + td.cert { + min-width: 0; + } + + dialog footer .main, + dialog footer .second { + flex: 1 1 auto; + } + + dl.facts { + grid-template-columns: 1fr; + gap: 2px; + } + + dl.facts dd { + margin-bottom: 10px; + } + + /* The sentence keeps the width, and when the phones were listed goes under it */ + .status { + flex-direction: column; + gap: 4px; + } +} diff --git a/src/odmdm_connector/static/app.js b/src/odmdm_connector/static/app.js new file mode 100644 index 0000000..024a1e1 --- /dev/null +++ b/src/odmdm_connector/static/app.js @@ -0,0 +1,1243 @@ +"use strict"; +// The page: asks the connector for its state and draws it. Setting up is a row of cards, one thing +// each, like a setup wizard; the daily work is one view of the phones with a few dialogs. Every +// sentence shown comes from the connector; this file adds labels, headings and the sentences for a +// connector that refuses this browser or does not answer. Data never becomes markup: the page is +// built with createElement and text nodes. The browser keeps one thing, the page's key, and nothing else. + +const view = document.getElementById("view"); +const dialog = document.getElementById("dialog"); +const menu = document.getElementById("menu"); +// After naming or asking again, the table waits for the listing that follows +const SETTLING = ["name", "ask again", "phones"]; + +let S = null; // the last state +let screen = ""; // a card's name, or "app" for the phones +let problem = ""; // the last refusal, shown in the view +let notice = ""; // the last answer's sentence, shown on the next card +let timer = 0; +let selected = new Set(); // the phones ticked in the table, by id +let settling = false; // the table is from before a naming or an asking again +let submit = null; // what the main button of the form being drawn does +let arriving = null; // a settings line Deploy App's page sent, {line, from}, until it is read +const flow = {}; // what the cards carry from one to the next, in memory only + +// Building blocks + +function el(tag, props, ...children) { + const node = document.createElement(tag); + for (const [key, value] of Object.entries(props || {})) { + if (value === false || value === null || value === undefined) continue; + if (key === "class") node.className = value; + else if (key === "value" || key === "checked" || key === "indeterminate") node[key] = value; + else if (key.startsWith("on")) node.addEventListener(key.slice(2), value); + else node.setAttribute(key, value === true ? "" : value); + } + // A string becomes a text node, never markup + for (const child of children.flat(Infinity)) if (child !== null && child !== undefined && child !== "") node.append(child); + return node; +} + +const h1 = (text) => el("h1", {}, text); +// A Deploy App's name in a title, kept whole with the punctuation after it: it moves to the next line +// as one, and breaks inside only when it is wider than the line by itself +const named = (name, after = "") => el("span", { class: "name" }, name, after); +const lead = (text) => (text ? el("p", { class: "lead" }, text) : null); +// A button is known by its text, so that it keeps the focus when the view is drawn again +const button = (props, text) => { + const node = el("button", props, text); + node.dataset.key = text; + return node; +}; +// The form's main button submits it, so Enter in a field presses it +const main = (text, action, disabled = false, tone = "") => { + submit = action; + return button({ class: `main ${tone}`, type: "submit", disabled }, text); +}; +const second = (text, onclick, disabled = false) => button({ class: "second", type: "button", onclick, disabled }, text); +const tool = (text, onclick, disabled = false, tone = "") => button({ class: `tool ${tone}`, type: "button", onclick, disabled }, text); +const link = (text, onclick) => el("button", { class: "back", type: "button", onclick }, text); +const choice = (title, sub, onclick, tone = "") => + el("button", { class: "choice", type: "button", onclick }, el("strong", {}, title), sub ? el("span", { class: tone }, sub) : null); +const count = (n, noun) => `${n} ${noun}${n === 1 ? "" : "s"}`; +// Text a password manager must not take: masked by the style, never a password field +const typed = (props) => el("input", { type: "text", autocomplete: "off", spellcheck: "false", ...props }); +// Where a phone's certificate is, as a dot's colour +const tone = (row) => (!row ? "" : row.failed ? "bad" : row.waiting ? "none" : row.ready ? "ok" : "on"); + +function field(id, label, input) { + input.id = id; + input.dataset.key = id; + return [el("label", { for: id }, label), input]; +} + +function check(label, checked, onchange) { + return el( + "label", + { class: "check" }, + el("input", { type: "checkbox", checked, onchange: (event) => onchange(event.target.checked) }), + label, + ); +} + +function copy(text) { + navigator.clipboard?.writeText(text).catch(() => {}); +} + +// A text to copy, shown in a field of its own that keeps a long one on one line +function copyable(text, label, masked = false) { + const value = typed({ class: masked ? "secret" : null, value: text, readonly: true, "aria-label": label }); + value.dataset.key = label; + return value; +} + +// The page's key, which the connector printed in the address's fragment: no server is sent a +// fragment, so it reaches this page alone. It is kept in this browser's storage for this port, which +// another port cannot read, so that every tab of the page has it; without storage, in this tab only. +const KEPT = "odmdm-key"; +let key = ""; +try { + key = localStorage.getItem(KEPT) || ""; +} catch {} + +// Take the key from the address, if it holds one, and take it out of the address; whether it did. +// Any web page can send the browser here with a key of its own, so a key is kept, and so passed to the +// other tabs, only once the connector accepts it; another one leaves the kept key as it is. +async function takeKey() { + const found = new URLSearchParams(location.hash.slice(1)).get("key"); + if (!found) return false; + history.replaceState(null, "", location.pathname); + // The answer is read to its end, so that the request is not left open + const accepted = await fetch("/api/state", { cache: "no-store", headers: { "X-ODMDM-Key": found } }).then( + (response) => response.text().then(() => response.ok), + () => false, + ); + if (!accepted) return false; + key = found; + try { + localStorage.setItem(KEPT, found); + } catch {} + return true; +} + +// Talking to the connector + +async function call(path, body) { + const headers = { "X-ODMDM-Key": key }; + const options = + body === undefined + ? { cache: "no-store", headers } + : { method: "POST", headers: { ...headers, "Content-Type": "application/json" }, body: JSON.stringify(body) }; + const response = await fetch(path, options); + const json = (response.headers.get("Content-Type") || "").startsWith("application/json"); + const answer = json ? await response.json() : { error: await response.text() }; + if (!response.ok) throw Object.assign(new Error(answer.error || response.statusText), { status: response.status }); + return answer; +} + +// Ask, take the state that follows, then go on; a refusal is said by fail, in the view by default +async function act(path, body, then, fail = say) { + problem = ""; + let answer; + try { + answer = await call(path, body); + } catch (error) { + if (error.status && error.status !== 403) fail(error.message); + else away(error); + return; + } + notice = answer.said || ""; + if (await refresh(false)) then(answer); +} + +function say(text) { + problem = text; + draw(false); +} + +const overlaid = () => dialog.open || menu.matches(":popover-open"); + +function closeOverlays() { + if (menu.matches(":popover-open")) menu.hidePopover(); + if (dialog.open) dialog.close(); +} + +// The cards that hold nothing typed yet, which follow another tab's adding, opening or connecting +const FOLLOWING = ["add", "choose", "mdm"]; + +// Whether the state came; the views that show it are drawn again, and follow it where it moved on +async function refresh(redraw = true) { + const before = S; + try { + S = await call("/api/state"); + } catch (error) { + away(error); + return false; + } + const moved = + before && (S.active !== before.active || S.connected !== before.connected || S.connections.length > before.connections.length); + if (settling && !S.busy.some((job) => SETTLING.includes(job))) settling = false; + if (!screen || screen === "away") begin(); + else if (!redraw) return true; + else if (screen === "app" && !S.connected) { + closeOverlays(); + home(); + } else if (screen === "connecting") checklist(); + else if (screen === "app" && !overlaid()) draw(false); + else if (FOLLOWING.includes(screen) && moved) begin(); + return true; +} + +// The connector refuses this browser, having no key yet or a new one since a restart, or does not answer +function away(error) { + closeOverlays(); + flow.away = { status: error.status || 0, text: error.message }; + screen = "away"; + problem = ""; + draw(false); +} + +function schedule() { + clearTimeout(timer); + timer = setTimeout(tick, S && S.busy.length ? 1000 : 3000); +} + +async function tick() { + if (document.visibilityState === "visible") await refresh(); + schedule(); +} + +// Moving between views + +function show(name) { + screen = name; + problem = ""; + draw(true); +} + +function go(name) { + notice = ""; + show(name); +} + +function draw(fresh) { + const focused = document.activeElement?.dataset?.key; + const scroller = view.querySelector(".table"); + const at = scroller ? [scroller.scrollTop, scroller.scrollLeft] : null; + submit = null; + const built = screen === "app" ? phones() : frame(CARDS[screen]()); + document.body.className = screen === "app" ? "app" : "cards"; + view.replaceChildren(...built); + const table = view.querySelector(".table"); + if (table && at && !fresh) [table.scrollTop, table.scrollLeft] = at; + const again = fresh ? null : [...view.querySelectorAll("[data-key]")].find((node) => node.dataset.key === focused); + const card = view.querySelector(".card"); + const first = card ? starting(card) : null; + (again || ((fresh || document.activeElement === document.body) && first) || null)?.focus(); +} + +// Where the focus starts: a button marked to start on, else the first field shown, else the main +// button, so that typing or Enter works at once +function starting(root) { + const fields = root.querySelectorAll("input:not([type=checkbox]):not([readonly]), textarea"); + return root.querySelector("[autofocus]") || [...fields].find((node) => !node.closest("[hidden]")) || root.querySelector("button.main:enabled"); +} + +// Cancel, to start on where a stray Enter must not remove something or take something in +const cancel = (onclick) => { + const node = second("Cancel", onclick); + node.autofocus = true; + return node; +}; + +// The form of a view: its main button submits it +function form(parts, cls) { + const action = submit; + return el( + "form", + { + class: cls, + onsubmit: (event) => { + event.preventDefault(); + action?.(); + }, + }, + parts, + ); +} + +// A card: the brand line, a link back and a corner, how far a first set-up is, then the card's own parts +function frame({ parts, step = null, back = null, corner = "", host = false }) { + // The MDM's own title once its fields are asked for; a plugin is not imported before it is approved + const chosen = screen === "field" || screen === "connecting" ? flow.form.title : "MDM"; + const names = ["Deploy App", chosen, "Connect"]; + const bar = + step === null + ? null + : el( + "ol", + { class: "progress", "aria-label": "Set-up" }, + names.map((name, index) => + el("li", { class: index < step ? "done" : index === step ? "now" : "", "aria-current": index === step ? "step" : null }, name), + ), + ); + const top = back || corner ? el("div", { class: "topline" }, back ? link(`‹ ${back.text}`, back.action) : el("span"), corner) : null; + const body = parts.flat(Infinity).filter(Boolean); + // A refusal goes under the heading and the lead, where it is read first + let at = body.findIndex((node) => node.tagName === "H1") + 1; + while (body[at]?.matches?.("p.lead, p.muted")) at += 1; + if (problem) body.splice(at, 0, el("p", { class: "error", role: "alert" }, problem)); + return [ + el("header", { class: "brand" }, host && S?.active ? `ODMDM connector · ${S.active}` : "ODMDM connector"), + el("main", { class: "card" }, form([top, bar, body])), + ]; +} + +function begin() { + problem = notice = ""; + if (!arriving) return home(); + closeOverlays(); + const { line, from } = arriving; + arriving = null; + // Nothing else moves the view on while the line is read: it goes to the confirming card, or to Add + screen = "reading"; + readLine(line, from); +} + +// Where a Deploy App's work goes on: its phones, else what its MDM still needs, and why. The last +// answer's sentence stays, for a card to say. +function home() { + flow.renew = flow.change = flow.again = flow.policy = false; + flow.back = null; + if (!S.active) show(S.connections.length ? "choose" : "add"); + else if (S.connected) show("app"); + else if (S.needs === "secret") chooseMdm(S.mdm, S.status, true); + else if (S.mdms.length === 1) chooseMdm(S.mdms[0].name); + else go("mdm"); +} + +// Add a Deploy App, or new settings for the active one; Back returns to the phones +function adding(renew) { + closeOverlays(); + flow.renew = renew; + flow.back = () => go("app"); + go("add"); +} + +// from is the origin of the page that sent the line, empty for one typed or pasted here +function readLine(line, from) { + act( + "/api/read", + { line, from }, + (reading) => { + flow.line = { line, from }; + flow.reading = reading; + show("confirm"); + }, + (text) => { + if (screen !== "add") show("add"); + say(text); + }, + ); +} + +// A secret kept goes only with the settings it was kept for: it stands in while the rest are as loaded +const unchanged = () => flow.form.fields.every((each) => each.secret || (flow.values[each.key] || "") === (flow.loaded[each.key] || "")); +const held = (each) => each.secret && each.kept && unchanged(); +const filled = (each) => Boolean((flow.values[each.key] || "").trim() || held(each)); + +// The MDM's fields one at a time; with only, just the first it lacks. why is said above that field. +function chooseMdm(name, why = "", only = false) { + act("/api/form", { mdm: name }, (answer) => { + if (answer.approval) { + flow.approval = { name, text: answer.approval }; + show("approve"); + return; + } + flow.form = answer; + flow.values = Object.fromEntries(answer.fields.map((each) => [each.key, each.value])); + flow.loaded = { ...flow.values }; + flow.remember = true; + flow.why = why; + const lacking = only ? answer.fields.findIndex((each) => !each.advanced && (each.required || each.secret) && !filled(each)) : -1; + flow.only = lacking >= 0; + flow.index = flow.only ? answer.fields.filter((each) => !each.advanced).indexOf(answer.fields[lacking]) : 0; + show("field"); + }); +} + +// After Connect: the setup's steps while it runs or leaves something to say, else the phones. With +// the token typed again, a setup that ends with nothing to say goes straight on to the phones. After +// Send the policy again (flow.policy), the same card shows that job's steps and stays to say how it ended. +function checklist() { + const busy = S.busy.includes(flow.policy ? "policy" : "setup"); + const said = S.setup_error || S.challenge || S.steps.some((step) => !step.done) || (S.steps.length && !flow.again); + if (!busy && (!S.connected || !said)) home(); + else if (screen === "connecting") draw(false); + else show("connecting"); +} + +// The challenge, for an MDM that is given it by hand: masked until shown +function challenge() { + return el( + "div", + { class: "copyrow" }, + copyable(S.challenge, "Challenge", !flow.showChallenge), + tool(flow.showChallenge ? "Hide" : "Show", () => { + flow.showChallenge = !flow.showChallenge; + draw(false); + }), + tool("Copy", () => copy(S.challenge)), + ); +} + +// The cards of a first set-up, and of the few things that interrupt the work + +const CARDS = { + away() { + const { status, text } = flow.away; + const kept = arriving ? el("p", { class: "muted" }, "The settings from Deploy App are kept here until then.") : null; + if (status === 403) + return { + parts: [ + h1("Open the connector's address"), + lead(text), + el("div", { class: "box" }, "It looks like this:", el("br"), `http://127.0.0.1:${location.port}/#key=…`), + kept, + ], + }; + if (status) return { parts: [h1("The connector failed"), el("p", { class: "error" }, text)] }; + return { + parts: [h1("The connector has stopped"), lead("Start it again on this computer, then open the address it prints."), kept], + }; + }, + + add() { + const renew = flow.renew && S.active; + const input = typed({ class: "secret", placeholder: "ODMDM1 …" }); + let button; + input.addEventListener("input", () => { + button.disabled = !input.value.trim(); + }); + input.addEventListener("paste", (event) => { + event.preventDefault(); + readLine(event.clipboardData.getData("text"), ""); + }); + button = main("Continue", () => readLine(input.value, ""), true); + return { + step: renew ? null : 0, + back: S.connections.length ? { text: "Back", action: flow.back || home } : null, + parts: [ + h1(renew ? ["New settings for Deploy App ", named(S.active)] : "Add your Deploy App"), + notice ? el("p", { class: "muted" }, notice) : null, + lead("On Deploy App's MDM page, press this button:"), + // A picture of Deploy App's button, which the sentence above names: nothing to press here + el("div", { class: "lookfor", "aria-hidden": "true" }, el("small", {}, "on Deploy App"), el("span", {}, "Open in the MDM connector")), + // Only a tab that Deploy App's button opened waits for its message; the button opens a new tab otherwise + window.opener + ? el("p", { class: "waiting" }, el("span", { class: "pulse" }), "Waiting for Deploy App…") + : el("p", { class: "waiting" }, "It opens the connector in a new tab."), + el("div", { class: "or" }, "OR"), + field("line", "Paste its settings line:", input), + button, + S.connections.length + ? null + : el( + "div", + { class: "athand" }, + el("strong", {}, "Have at hand:"), + el( + "ul", + {}, + ["Deploy App's MDM page, open as an admin", "your MDM's address", "an API token for your MDM"].map((each) => el("li", {}, each)), + ), + ), + ], + }; + }, + + confirm() { + const { host, until, known } = flow.reading; + const leave = () => { + flow.line = null; + home(); + }; + const take = () => + act("/api/add", flow.line, () => { + flow.line = null; + home(); + }); + return { + step: known ? null : 0, + parts: [ + h1(known ? ["New settings for Deploy App ", named(host)] : ["Add Deploy App ", named(host, "?")]), + lead(until), + main(known ? "Use the new settings" : `Add ${host}`, take), + // Any web page can bring this card up for a Deploy App of its own + known ? second("Cancel", leave) : cancel(leave), + ], + }; + }, + + choose() { + return { + parts: [ + h1("Which Deploy App?"), + notice ? lead(notice) : null, + S.connections.map((each) => + choice(each.host, each.short, () => act("/api/open", { host: each.host }, home), each.level), + ), + second("Add a Deploy App", () => { + flow.renew = false; + flow.back = () => go("choose"); + go("add"); + }), + ], + }; + }, + + mdm() { + return { + step: 1, + host: true, + back: S.connections.length > 1 ? { text: "Other Deploy Apps", action: () => go("choose") } : null, + parts: [ + h1("Which MDM?"), + S.mdms.map((each) => + choice(each.name, each.built_in ? "Comes with the connector" : `Plugin: ${each.package} ${each.version}`, () => + chooseMdm(each.name), + ), + ), + ], + }; + }, + + approve() { + const { name, text } = flow.approval; + return { + step: 1, + host: true, + back: { text: "Back", action: () => go("mdm") }, + parts: [ + h1("Use this plugin?"), + lead(text), + main("Use it", () => act("/api/approve", { mdm: name }, () => chooseMdm(name))), + ], + }; + }, + + field() { + const form = flow.form; + const steps = form.fields.filter((each) => !each.advanced); + const shown = steps[flow.index]; + const last = flow.only || flow.index >= steps.length - 1; + const advanced = flow.only ? [] : form.fields.filter((each) => each.advanced); + // A required field left empty holds the button back; a secret kept from before counts as filled + const ready = () => (last ? [shown, ...advanced] : [shown]).every((each) => !each || !each.required || filled(each)); + let button; + const input = (each) => { + const kept = each.remembered ? "Kept on this computer" : "Kept while the connector runs"; + const node = typed({ + class: each.secret ? "secret" : null, + value: flow.values[each.key], + placeholder: held(each) ? kept : each.default, + oninput: (event) => { + flow.values[each.key] = event.target.value; + button.disabled = !ready(); + }, + }); + return field(`field-${each.key}`, each.label, node); + }; + // The card's title is the field's label, so the input is named by it rather than shown it again + const alone = (each) => { + const node = input(each)[1]; + node.setAttribute("aria-label", each.label); + return node; + }; + const connect = () => + act( + "/api/connect", + { mdm: form.name, values: flow.values, remember: S.keeps && flow.remember }, + () => { + flow.values = {}; + flow.again = flow.only; + flow.policy = false; + checklist(); + }, + // A kept secret left empty after the settings changed is asked for again on its own card + (text) => { + const again = steps.findIndex((each) => each.secret && each.kept && !unchanged() && !(flow.values[each.key] || "").trim()); + if (again >= 0 && !flow.only) { + flow.index = again; + show("field"); + } + say(text); + }, + ); + const next = () => { + flow.index += 1; + show("field"); + }; + const back = () => { + if (flow.index > 0 && !flow.only) { + flow.index -= 1; + show("field"); + } else if (flow.change) go("app"); + else go(flow.only ? "choose" : "mdm"); + }; + const backward = flow.change || (flow.only ? S.connections.length > 1 : flow.index > 0 || S.mdms.length > 1); + const backText = flow.only ? "Other Deploy Apps" : flow.index > 0 ? "Back" : flow.change ? "Back to the phones" : "Back"; + button = main(last ? "Connect" : "Next", last ? connect : next, !ready()); + return { + step: flow.only ? null : 1, + corner: flow.only ? "" : `${flow.index + 1} of ${steps.length}`, + back: backward ? { text: backText, action: back } : null, + host: true, + parts: [ + h1(shown.label), + lead(shown.help), + flow.why ? el("p", { class: "note" }, flow.why) : null, + alone(shown), + // Said once: without a keychain the reason above already says the token is not kept + shown.secret + ? S.keeps + ? check("Remember on this computer", flow.remember, (on) => { + flow.remember = on; + }) + : flow.why + ? null + : el("p", { class: "muted hint" }, "Kept only until the connector stops.") + : null, + last && advanced.length + ? el( + "details", + { class: "more" }, + el("summary", {}, "More settings"), + advanced.map((each) => [input(each), each.help ? el("p", { class: "muted hint" }, each.help) : null]), + ) + : null, + button, + ], + }; + }, + + connecting() { + const title = flow.form.title; + const policy = flow.policy; + const busy = S.busy.includes(policy ? "policy" : "setup"); + const done = S.steps.filter((step) => step.done); + const todo = S.steps.filter((step) => !step.done); + const item = (cls, step) => el("li", { class: cls }, step.label, step.message ? el("span", {}, step.message) : null); + // Steps left to the operator are what the card is about once the setup has run + const given = S.challenge && !policy; + const hand = !busy && !S.setup_error && (todo.length || given); + const heading = policy + ? busy + ? "Sending the policy again" + : S.setup_error + ? "The policy was not sent" + : hand + ? "Do these by hand" + : "The policy is sent again" + : busy + ? `Connecting ${title}` + : S.setup_error + ? `${title} is not set up` + : hand + ? "Do these by hand" + : `${title} is connected`; + return { + step: flow.again || policy ? null : 2, + host: true, + parts: [ + h1(heading), + // The connector's sentence only where it says more than the heading + hand ? lead(S.status) : null, + busy ? S.lines.map((line) => el("p", { class: "note" }, line)) : null, + hand + ? el( + "ul", + { class: "run" }, + todo.map((step) => item("hand", step)), + given ? el("li", { class: "hand" }, S.challenge_note, challenge()) : null, + ) + : null, + el( + "ul", + { class: "run" }, + done.map((step) => item("done", step)), + busy ? el("li", { class: "now" }, "…") : null, + ), + S.setup_error ? el("p", { class: "error" }, S.setup_error) : null, + S.setup_error && !policy + ? main("Change the settings", () => { + flow.change = false; + chooseMdm(S.mdm); + }) + : main("Show the phones", home, busy), + ], + }; + }, +}; + +// The phones: the window's line, one row of buttons, the selection, the table and what was said last + +function phones() { + const rows = S.rows; + const ids = new Set(rows.map((row) => row.id)); + selected = new Set([...selected].filter((id) => ids.has(id))); + const picked = rows.filter((row) => selected.has(row.id)); + const pick = (test) => { + selected = new Set(rows.filter(test).map((row) => row.id)); + draw(false); + }; + const flip = (id) => { + if (selected.has(id)) selected.delete(id); + else selected.add(id); + draw(false); + }; + const waiting = rows.some((row) => row.waiting); + const askable = selected.size ? picked.some((row) => row.askable) : rows.some((row) => row.askable && row.failed); + const level = S.banner.level; + const renew = level === "closed" || level === "none"; + + const picker = el( + "button", + { class: "picker", type: "button", popovertarget: "menu", "aria-haspopup": "true" }, + el("small", {}, "Deploy App"), + el("strong", {}, S.active), + " ▾", + ); + picker.dataset.key = "picker"; + const all = el("input", { + type: "checkbox", + "aria-label": "Select all", + checked: rows.length > 0 && selected.size === rows.length, + indeterminate: selected.size > 0 && selected.size < rows.length, + disabled: !rows.length, + onchange: (event) => pick(() => event.target.checked), + }); + all.dataset.key = "all"; + const body = rows.map((row) => { + const box = el("input", { + type: "checkbox", + checked: selected.has(row.id), + "aria-label": `Select ${row.callsign || row.id}`, + onchange: () => flip(row.id), + }); + box.dataset.key = `pick-${row.id}`; + const line = el( + "tr", + { + class: `${row.failed ? "bad" : ""} ${selected.has(row.id) ? "sel" : ""}`, + tabindex: "0", + onclick: (event) => { + if (!event.target.closest(".pick")) flip(row.id); + }, + ondblclick: () => detail(row.id), + onkeydown: (event) => { + if (event.target !== event.currentTarget) return; + if (event.key === "Enter") { + event.preventDefault(); + detail(row.id); + } else if (event.key === " ") { + event.preventDefault(); + flip(row.id); + } + }, + }, + el("td", { class: "pick" }, box), + el("td", {}, row.id), + el("td", { class: row.callsign ? "call" : "call nocall" }, row.callsign || "—"), + el("td", { class: "phone" }, row.phone), + el("td", { class: "joined" }, row.joined), + el("td", { class: "cert" }, el("span", { class: `dot ${tone(row)}` }), row.certificate), + ); + line.dataset.key = `row-${row.id}`; + return line; + }); + const empty = el("tr", {}, el("td", { class: "empty", colspan: "6" }, S.summary || "…")); + + return [ + el("header", { class: "top" }, el("span", { class: "name" }, "ODMDM connector"), picker), + el( + "main", + { class: "work" }, + form( + [ + el( + "div", + { class: `window ${level}` }, + el("span", { class: "said" }, el("span", { class: "dot" }), S.banner.text), + renew && S.mdm_page + ? el("a", { class: "out", href: S.mdm_page, target: "_blank", rel: "noopener noreferrer" }, "Open Deploy App ↗") + : null, + ), + S.challenge_note + ? el("div", { class: "note" }, el("p", {}, S.challenge_note), S.challenge ? challenge() : null) + : null, + el( + "div", + { class: "tools" }, + main("Give callsigns", () => giveCallsigns([...selected]), settling || !(selected.size || waiting), "tool go"), + tool("Ask again", () => askAgain([...selected]), settling || !askable), + tool("Details", () => detail([...selected][0]), settling || selected.size !== 1), + tool("Refresh", () => act("/api/refresh", {}, () => draw(false))), + tool("New settings", () => adding(true)), + tool("Settings", settings, false, "push"), + ), + el( + "div", + { class: "select" }, + el("span", { class: "muted" }, "Select:"), + tool("Waiting for a name", () => pick((row) => row.waiting), !waiting, "small"), + tool("Refused or failed", () => pick((row) => row.failed), !rows.some((row) => row.failed), "small"), + selected.size ? [el("span", { class: "muted" }, `${selected.size} selected`), link("Clear", () => pick(() => false))] : null, + rows.length ? el("span", { class: "count" }, S.summary) : null, + ), + el( + "div", + { class: settling ? "table settling" : "table", "aria-busy": settling ? "true" : null }, + el( + "table", + {}, + el( + "thead", + {}, + el( + "tr", + {}, + el("th", { class: "pick" }, all), + el("th", {}, "ID"), + el("th", {}, "Callsign"), + el("th", { class: "phone" }, "Phone"), + el("th", { class: "joined" }, "Joined"), + el("th", { class: "cert" }, "Certificate"), + ), + ), + el("tbody", {}, rows.length ? body : empty), + ), + ), + ], + "app-form", + ), + ), + el( + "footer", + { class: "status" }, + el( + "div", + { "aria-live": "polite" }, + problem ? el("p", { class: "error", role: "alert" }, problem) : el("p", {}, S.status), + S.lines.length ? el("ul", {}, S.lines.map((line) => el("li", {}, line))) : null, + ), + S.updated ? el("span", { class: "updated" }, `Updated ${S.updated}`) : null, + ), + ]; +} + +function askAgain(ids) { + settling = true; + act("/api/again", { ids }, () => draw(false), (text) => { + settling = false; + say(text); + }); +} + +// The Deploy Apps, in the menu under the picker: open one, add one, or remove the one open + +menu.addEventListener("beforetoggle", (event) => { + if (event.newState !== "open") return; + const pick = (action) => () => { + menu.hidePopover(); + action(); + }; + menu.replaceChildren( + ...S.connections.map((each) => + el( + "button", + { + class: each.active ? "item now" : "item", + type: "button", + "aria-current": each.active ? "true" : null, + onclick: pick(() => (each.active ? null : act("/api/open", { host: each.host }, home))), + }, + el("span", { class: "mark" }, each.active ? "●" : ""), + el("span", {}, el("strong", {}, each.host), el("small", { class: each.level }, each.short)), + ), + ), + el("hr"), + el("button", { class: "item act", type: "button", onclick: pick(() => adding(false)) }, "+ Add a Deploy App"), + el("button", { class: "item act danger", type: "button", onclick: pick(remove) }, `Remove ${S.active}…`), + ); +}); + +menu.addEventListener("toggle", (event) => { + if (event.newState === "closed" && screen === "app" && !dialog.open) draw(false); +}); + +// The dialogs: the browser's own, which bring the backdrop, Escape and the keyboard kept inside. Each +// is a form; parts is what it holds, and its main button submits it. + +function open(title, parts, foot) { + const opener = document.activeElement?.dataset?.key; + dialog.dataset.opener = opener || ""; + const say = el("p", { class: "error", role: "alert" }); + const built = form( + [ + el("header", {}, el("h2", { id: "dialog-title" }, title), el("button", { class: "x", type: "button", "aria-label": "Close", onclick: () => dialog.close() }, "×")), + el("div", { class: "body" }, parts, say), + el("footer", {}, foot), + ], + "", + ); + dialog.setAttribute("aria-labelledby", "dialog-title"); + dialog.replaceChildren(built); + if (!dialog.open) dialog.showModal(); + // Never on the close mark, which the browser would choose + (starting(built.querySelector(".body")) || starting(built.querySelector("footer")))?.focus(); + return (text) => { + say.textContent = text; + }; +} + +dialog.addEventListener("close", () => { + // The event comes a moment later: a dialog opened in its place since then stays + if (dialog.open) return; + dialog.replaceChildren(); + if (screen !== "app") return; + draw(false); + const opener = [...view.querySelectorAll("[data-key]")].find((node) => node.dataset.key === dialog.dataset.opener); + opener?.focus(); +}); + +// A click on the backdrop, outside the dialog's box, closes it +dialog.addEventListener("click", (event) => { + if (event.target === dialog) dialog.close(); +}); + +function detail(id) { + act("/api/detail", { id }, (phone) => { + const row = S.rows.find((each) => each.id === phone.id); + const pair = (term, value, cls) => (value ? [el("dt", {}, term), el("dd", { class: cls }, value)] : null); + submit = null; + const give = phone.callsign ? "Give another callsign" : "Give a callsign"; + const giving = () => { + dialog.close(); + giveCallsigns([phone.id]); + }; + const foot = phone.can_ask_again + ? [ + second(give, giving), + main("Ask again", () => { + dialog.close(); + askAgain([phone.id]); + }), + ] + : [main(give, giving)]; + open( + phone.callsign || `Phone ${phone.id}`, + [ + el( + "dl", + { class: "facts" }, + pair("Phone", phone.phone ? `${phone.phone}, ID ${phone.id}` : `ID ${phone.id}`), + pair("Joined", phone.joined), + [el("dt", {}, "Certificate"), el("dd", { class: tone(row) }, el("span", { class: `dot ${tone(row)}` }), phone.state)], + pair("The MDM says", phone.detail), + ), + el("p", { class: "muted" }, phone.window), + ], + foot, + ); + }); +} + +// One dialog for naming: numbered or from a list, and the preview the connector makes of it, asked a +// moment after the typing stops. One preview is asked at a time and the last one asked is the one +// shown, as the connector names only its last; Name waits for it, and names exactly what it showed. +function giveCallsigns(ids) { + const n = ids.length || S.rows.filter((row) => row.waiting).length; + // The rest of a list kept from last time is where the next callsigns come from + const naming = { how: S.callsigns.length ? "list" : "numbered", prefix: S.prefix, first: "", list: S.callsigns.join("\n"), save: true }; + let found = null; + let refused = ""; + let asking = false; + let again = false; + let wait = 0; + const later = (key) => (event) => { + naming[key] = event.target.value; + tell(""); + clearTimeout(wait); + wait = setTimeout(ask, 400); + shown(); + }; + const prefix = typed({ value: naming.prefix, placeholder: "OTTER", oninput: later("prefix") }); + const first = typed({ inputmode: "numeric", value: "", oninput: later("first") }); + const list = el("textarea", { spellcheck: "false", rows: "6", oninput: later("list") }); + list.value = naming.list; + const numbered = el("div", { class: "inline" }, el("div", { class: "grow" }, field("prefix", "Prefix", prefix)), el("div", { class: "num" }, field("first", "First number", first))); + const listed = el("div", {}, field("list", "One callsign per line", list)); + const keep = check("Keep the rest of the list for next time", naming.save, (on) => { + naming.save = on; + }); + const switches = ["numbered", "list"].map((how) => + el( + "button", + { + type: "button", + "aria-pressed": "false", + onclick: () => { + naming.how = how; + tell(""); + ask(); + }, + }, + how === "numbered" ? "Numbered" : "From a list", + ), + ); + const preview = el("div", { class: "preview-part" }); + const name = () => { + const names = Object.fromEntries(found.rows.map((row) => [row.id, row.callsign])); + const { how, list: text, save } = naming; + act( + "/api/name", + { names, how, prefix: naming.prefix, list: text, save }, + () => { + selected = new Set(); + settling = true; + dialog.close(); + }, + // The connector may hold another preview, from another tab: ask again, so the dialog shows what it would + // name; the reason stays until the operator changes something + (text) => { + tell(text); + ask(); + }, + ); + }; + submit = null; + const button = main("Name", name, true); + shown(); + const tell = open( + `Give callsigns to ${count(n, "phone")}`, + [el("div", { class: "mode", role: "group", "aria-label": "How" }, switches), numbered, listed, preview], + [keep, second("Cancel", () => dialog.close()), button], + ); + + // What the dialog shows now: the way chosen, and the preview with the button, held back while one is asked + function shown() { + const list = naming.how === "list"; + switches.forEach((each, index) => each.setAttribute("aria-pressed", String(index === (list ? 1 : 0)))); + numbered.hidden = list; + listed.hidden = !list; + keep.hidden = !list; + if (found) first.placeholder = String(found.first || ""); + const busy = asking || again || Boolean(wait); + const rows = found ? found.rows : []; + const problems = rows.some((row) => row.refusal); + const cell = (cls, text) => el("td", { class: cls }, text); + const parts = [ + found || refused ? el("h3", {}, "Preview") : null, + found + ? [ + el( + "div", + { class: busy ? "table preview settling" : "table preview", "aria-busy": busy ? "true" : null }, + el( + "table", + {}, + el( + "thead", + {}, + el( + "tr", + {}, + el("th", {}, "ID"), + el("th", { class: "phone" }, "Phone"), + el("th", { class: "joined" }, "Joined"), + el("th", {}, "Callsign"), + problems ? el("th", { class: "why" }, "Problem") : null, + ), + ), + el( + "tbody", + {}, + rows.map((row) => + el( + "tr", + { class: row.refusal ? "bad" : "" }, + cell("", row.id), + cell("phone", row.phone), + cell("joined", row.joined), + cell("will", row.callsign || "—"), + problems ? cell("why", row.refusal) : null, + ), + ), + ), + ), + ), + found.refusal ? el("p", { class: "error" }, found.refusal) : null, + found.warning ? el("p", { class: "warn" }, found.warning) : null, + ] + : null, + refused ? el("p", { class: "error" }, refused) : null, + !found && !refused && busy ? el("p", { class: "muted" }, "…") : null, + ]; + preview.replaceChildren(...parts.flat(Infinity).filter(Boolean)); + button.textContent = found ? found.button : "Name"; + button.disabled = busy || refused !== "" || !found?.ok; + } + + async function ask() { + clearTimeout(wait); + wait = 0; + if (!preview.isConnected) return; + // A numbered batch with neither a prefix nor a first number has nothing typed to preview yet + if (naming.how === "numbered" && !naming.prefix.trim() && !naming.first.trim()) { + found = null; + refused = ""; + shown(); + return; + } + if (asking) { + again = true; + return; + } + asking = true; + again = false; + shown(); + try { + found = await call("/api/preview", { ids, ...naming }); + refused = ""; + } catch (error) { + if (!error.status || error.status === 403) { + away(error); + return; + } + found = null; + refused = error.message; + } finally { + asking = false; + } + if (again) ask(); + else shown(); + } + + ask(); +} + +function settings() { + act("/api/form", { mdm: S.mdm }, (answer) => { + // Its steps on the card a setup shows them on; a refusal before it starts is said here. The button + // is disabled as it is pressed, so a second press sends nothing + const resend = (event) => { + const pressed = event.currentTarget; + pressed.disabled = true; + act( + "/api/policy", + {}, + () => { + dialog.close(); + flow.form = answer; + flow.again = false; + flow.policy = true; + checklist(); + }, + (text) => { + pressed.disabled = false; + tell(text); + }, + ); + }; + const said = (each) => + each.secret + ? each.remembered + ? "kept on this computer" + : each.kept + ? "kept until the connector stops" + : "not given" + : each.value; + const change = () => { + dialog.close(); + flow.change = true; + chooseMdm(S.mdm); + }; + submit = null; + const close = main("Close", () => dialog.close(), false, "plain"); + const tell = open( + "Settings", + [ + el("h3", { class: "sect" }, `${answer.title} for `, named(S.active)), + el( + "dl", + { class: "facts" }, + answer.fields.filter((each) => said(each)).map((each) => [el("dt", {}, each.label), el("dd", {}, said(each))]), + ), + second(`Change the ${answer.title} settings`, change), + S.policy ? [el("h3", { class: "sect" }, "Policy"), el("p", { class: "muted" }, S.policy), second("Send the policy again", resend, S.busy.includes("policy") || S.busy.includes("setup"))] : null, + el("h3", { class: "sect" }, "Log"), + el("div", { class: "copyrow" }, copyable(S.log, "Log"), tool("Copy", () => copy(S.log))), + el("p", { class: "muted" }, `odmdm-connector ${S.version}`), + ], + [close], + ); + }); +} + +function remove() { + const host = S.active; + submit = null; + const removing = () => + act( + "/api/remove", + { host }, + () => { + dialog.close(); + home(); + }, + (text) => tell(text), + ); + const button = main("Remove", removing, false, "danger"); + const tell = open( + ["Remove Deploy App ", named(host, "?")], + [ + el( + "p", + {}, + "The connector forgets this Deploy App and its MDM token on this computer. Nothing changes in Deploy App, the MDM or the phones.", + ), + ], + [cancel(() => dialog.close()), button], + ); +} + +// A settings line from Deploy App's page arrives by message, only from the page that opened this one. +// Once it has, this page lets go of that one: holding it would let this page send it elsewhere. +window.addEventListener("message", (event) => { + if (!window.opener || event.source !== window.opener || typeof event.data?.add !== "string") return; + window.opener = null; + arriving = { line: event.data.add, from: event.origin }; + if (screen === "away") draw(false); + else if (S && screen) begin(); +}); + +document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") tick(); +}); + +// The address opened in a tab that shows the page already changes only its fragment, and reloads nothing +window.addEventListener("hashchange", async () => { + if (await takeKey()) tick(); +}); + +// Another tab of the page took a key: a tab that waits for one goes on by itself +window.addEventListener("storage", (event) => { + if (event.key !== KEPT || !event.newValue) return; + key = event.newValue; + tick(); +}); + +// The word is no secret: it only tells Deploy App's page that this one listens +window.opener?.postMessage("odmdm-ready", "*"); +takeKey().then(tick); diff --git a/src/odmdm_connector/static/index.html b/src/odmdm_connector/static/index.html new file mode 100644 index 0000000..29ddba0 --- /dev/null +++ b/src/odmdm_connector/static/index.html @@ -0,0 +1,22 @@ + + + + + + + ODMDM connector + + + + +
+
ODMDM connector
+
+

Loading…

+ +
+
+ + + + diff --git a/src/odmdm_connector/store.py b/src/odmdm_connector/store.py new file mode 100644 index 0000000..44feaec --- /dev/null +++ b/src/odmdm_connector/store.py @@ -0,0 +1,254 @@ +"""What the connector keeps between runs: a settings file without secrets, beside its log, and the keychain + +The settings file holds the plugins approved and, for each Deploy App connected by its host, the MDM +chosen, the MDM's fields that are not secret, when its last enrolment window closes and the +operator's callsigns for next time, and which Deploy App was worked with last. Never a secret, never +the challenge. A field marked secret, the MDM token, goes only to the operating system's keychain, +through keyring's one back end for the system, fixed here so that neither PYTHON_KEYRING_BACKEND, +keyring's configuration file nor another back end installed can choose where it goes. keyring is +the connector's one dependency and is imported here alone: without it, as in the one-file build, +there is no keychain and the App holds a secret until the connector stops. Never a plaintext fallback. +""" + +import datetime +import json +import logging +import os +import sys +import tempfile +from collections.abc import Callable +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any, Protocol + +LOGGER = logging.getLogger(__name__) + +#: The name of the directory the settings file and the log go in, and the keychain service of the secrets +APP = "odmdm-connector" +#: The settings file's format +VERSION = 1 + + +class StoreError(Exception): + """The settings file cannot be read or written, said in a sentence for the operator""" + + +def directory() -> Path: + """Where the settings file and the log live: the user's own application directory, named, not created""" + if sys.platform == "win32": + return Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") / APP + if sys.platform == "darwin": + return Path.home() / "Library" / "Application Support" / APP + return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / APP + + +@dataclass +class Connection: + """One Deploy App, by the host of its SCEP URL, and the MDM set up for it""" + + #: The MDM chosen, by its plugin name + mdm: str = "" + #: The chosen MDM's fields that are not secret, by key + values: dict[str, str] = field(default_factory=dict) + #: When the last enrolment window pasted closes, as an ISO time, so the banner survives a restart + closes: str = "" + #: The callsign prefix last used, and the list of callsigns still to give + prefix: str = "" + callsigns: list[str] = field(default_factory=list) + + +@dataclass +class Saved: + """The settings file's contents""" + + #: The plugins approved by the operator, each as "name package version"; asked again when it changes + approved: list[str] = field(default_factory=list) + #: The Deploy Apps connected, by the host of their SCEP URL + connections: dict[str, Connection] = field(default_factory=dict) + #: The host of the Deploy App worked with last, or empty + active: str = "" + + +def _typed(key: str, value: Any, default: Any) -> Any: + """The value, if it is of its default's type: a string, a list of strings or a mapping of strings""" + if isinstance(default, dict): + if not isinstance(value, dict) or not all(isinstance(v, str) for v in value.values()): + raise TypeError(f"{key} is not a mapping of strings") + elif isinstance(default, list): + if not isinstance(value, list) or not all(isinstance(v, str) for v in value): + raise TypeError(f"{key} is not a list of strings") + elif not isinstance(value, str): + raise TypeError(f"{key} is not a string") + return value + + +def _connection(host: str, raw: Any) -> Connection: + if not isinstance(raw, dict): + raise TypeError(f"connection {host} is not a mapping") + return Connection( + **{ + key: _typed(f"{host} {key}", raw.get(key, default), default) + for key, default in asdict(Connection()).items() + } + ) + + +def _checked(raw: Any) -> Saved: + """The file's values, each of the type it must be; TypeError otherwise""" + if not isinstance(raw, dict) or raw.get("version") != VERSION: + raise TypeError("not a version 1 settings file") + connections = raw.get("connections", {}) + if not isinstance(connections, dict): + raise TypeError("connections is not a mapping") + found = Saved( + approved=_typed("approved", raw.get("approved", []), []), + connections={host: _connection(host, each) for host, each in connections.items()}, + active=_typed("active", raw.get("active", ""), ""), + ) + if found.active and found.active not in found.connections: + raise TypeError("active is not a connection") + return found + + +class Store: + """The settings file in one directory, written whole and readable only by the user""" + + def __init__(self, directory: Path) -> None: + self.path = directory / "settings.json" + + def load(self) -> Saved: + """The saved settings; empty ones when there is no file yet""" + try: + text = self.path.read_text(encoding="utf-8") + except FileNotFoundError: + return Saved() + except OSError as exc: + raise StoreError(f"The settings file {self.path} cannot be read: {exc.strerror}.") from exc + try: + return _checked(json.loads(text)) + except (ValueError, TypeError) as exc: + LOGGER.warning("Settings file %s refused: %s", self.path, exc) + raise StoreError(f"The settings file {self.path} is damaged, so the app starts without it.") from exc + + def save(self, saved: Saved) -> None: + """Write the file whole: a new file beside it, readable only by the user, then renamed over it""" + text = json.dumps({"version": VERSION, **asdict(saved)}, indent=2) + try: + self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + handle, name = tempfile.mkstemp(dir=self.path.parent, prefix=".settings-", suffix=".json") + try: + with os.fdopen(handle, "w", encoding="utf-8") as written: + written.write(text) + written.flush() + os.fsync(written.fileno()) + os.replace(name, self.path) + except BaseException: + Path(name).unlink(missing_ok=True) + raise + except OSError as exc: + raise StoreError(f"The settings file {self.path} cannot be written: {exc.strerror}.") from exc + + +def closes(connection: Connection) -> datetime.datetime | None: + """When the Deploy App's last enrolment window pasted closes, if one was""" + try: + return datetime.datetime.fromisoformat(connection.closes) if connection.closes else None + except ValueError: + return None + + +class Backend(Protocol): + """The part of a keyring back end the connector uses""" + + def get_password(self, service: str, username: str) -> str | None: ... + + def set_password(self, service: str, username: str, password: str) -> None: ... + + def delete_password(self, service: str, username: str) -> None: ... + + +def platform_backend() -> Backend | None: + """The system's keychain, or None when keyring is not installed or the keychain cannot be used here + + The one back end per system is named here and set as keyring's, so keyring never looks at + PYTHON_KEYRING_BACKEND, its configuration file or the other back ends installed. + """ + try: + import keyring + from keyring.backend import KeyringBackend + + if sys.platform == "win32": + from keyring.backends.Windows import WinVaultKeyring as Chosen + elif sys.platform == "darwin": + from keyring.backends.macOS import Keyring as Chosen + else: + from keyring.backends.SecretService import Keyring as Chosen + except ImportError: + LOGGER.debug("keyring is not installed, so no keychain is used") + return None + if not Chosen.viable: + LOGGER.warning("The keychain back end %s cannot be used here", Chosen.__name__) + return None + # keyring leaves the back ends' constructors unannotated + make: Callable[[], KeyringBackend] = Chosen + backend = make() + keyring.set_keyring(backend) + return backend + + +class KeychainError(Exception): + """The keychain did not answer; it says only the kind of what the back end raised, never a value""" + + +def _asked(backend: Backend, call: Callable[[Backend], str | None]) -> str | None: + """The back end's answer + + A back end raises kinds of its own besides keyring's, D-Bus's and Windows' among them, so any + exception means the keychain did not answer, and becomes a KeychainError that names its kind. + """ + try: + return call(backend) + except Exception as exc: + raise KeychainError(type(exc).__name__) from exc + + +class Keychain: + """Secrets by account, under the service APP, in the system's keychain; no back end is no keychain""" + + def __init__(self, backend: Backend | None) -> None: + self.backend = backend + + @property + def usable(self) -> bool: + return self.backend is not None + + def _call(self, call: Callable[[Backend], str | None]) -> tuple[bool, str]: + """Whether the keychain answered, and its answer; when it did not, that is logged by its kind only""" + if self.backend is None: + return False, "" + try: + return True, _asked(self.backend, call) or "" + except KeychainError as exc: + LOGGER.warning("The keychain did not answer: %s", exc) + return False, "" + + def get(self, account: str) -> str: + """The secret kept, empty when there is none or the keychain did not answer""" + return self._call(lambda backend: backend.get_password(APP, account))[1] + + def keep(self, account: str, secret: str) -> bool: + """Keep the secret; whether the keychain took it""" + return self._call(lambda backend: backend.set_password(APP, account, secret))[0] + + def forget(self, account: str) -> bool: + """Remove the secret; whether the keychain no longer holds it, which is so without a keychain + + Deleting what is not there raises, so the keychain is read first, and again after deleting to tell. + """ + if self.backend is None: + return True + answered, left = self._call(lambda backend: backend.get_password(APP, account)) + if answered and left: + self._call(lambda backend: backend.delete_password(APP, account)) + answered, left = self._call(lambda backend: backend.get_password(APP, account)) + return answered and not left diff --git a/src/odmdm_connector/template.json b/src/odmdm_connector/template.json new file mode 100644 index 0000000..10ce4b2 --- /dev/null +++ b/src/odmdm_connector/template.json @@ -0,0 +1,80 @@ +{ + "_comment": [ + "What a Deploy App deployment's phones need. apply states this one unless given another: copy it,", + "change what to install, and apply it with", + " odmdm-connector apply --template template.json --domain ", + "", + "Placeholders filled in at apply time: {domain}, {mtls_url}, {key_alias}.", + "", + "APPS INSTALL AT ENROLMENT AND AT NO OTHER TIME on managed Android. A phone that has already", + "joined will not pick up a change here; it has to enrol again, under a callsign that has not", + "been spent." + ], + "apps": [ + { + "_comment": "The browser is installed, not assumed: a work profile does not inherit the personal profile's copy, and the launcher link below is a browser shortcut, so without it that install fails and takes the rest of the enrolment burst with it.", + "config": { + "AutoSelectCertificateForUrls": [ + "{\"pattern\":\"{mtls_url}\",\"filter\":{}}" + ], + "_comment": "choosePrivateKeyRules in the policy settles WHICH key may be used. The browser still decides whether to send one at all, and with no matching entry here it declines rather than prompting, which the server answers as mtls_fail and looks exactly like a missing certificate. Both halves are needed. The value is a list of JSON strings, which is the schema, not a mistake." + }, + "package": "com.android.chrome", + "preinstall": true + }, + { + "_comment": "ATAK-CIV. Large, and Play unpacks the enrolment set together, so on a device short of space the whole burst can fail.", + "package": "com.atakmap.app.civ", + "preinstall": true + }, + { + "_comment": "Element Classic rather than Element X: X accepts no managed configuration at all, so its homeserver cannot be pushed and the user would type it once per device.", + "config": { + "im.vector.app.serverConfigDefaultHomeserverUrlString": "https://synapse.{domain}" + }, + "package": "im.vector.app", + "preinstall": true + } + ], + "certificate": { + "_comment": [ + "The template Fleet fills in per phone. Its common name becomes the phone's callsign: 3-32", + "letters, digits or inner hyphens. This is the name `odmdm-connector name` gives a phone, and", + "the connector refuses any other common name: one the phone supplies, such as its serial", + "number, would make a leaked enrolment link enough for an identity. Fleet's id for the phone", + "follows it as OU, so the deployment can tell later which device a callsign was issued to;", + "leave the OU out only for a team that already has phones under a subject without it.", + "The name becomes the Android keystore alias, so it is per deployment.", + "No certificate authority is named: the connector finds this Deploy App's in the MDM by the", + "address it serves, and makes one when there is none, called ODMDM_ and the first part of the", + "Deploy App's host name.", + "So one MDM can serve several Deploy Apps. \"authority\": \"NAME\" here gives a new one that name." + ], + "name": "{key_alias}", + "subject": "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID" + }, + "link_app": { + "_comment": "A launcher icon so nobody has to know where the server lives. It is a browser shortcut, so it only works alongside the browser and the certificate.", + "title": "Deploy App", + "url": "{mtls_url}/" + }, + "policy": { + "_comment_key": "urlPattern is a java.util.regex pattern matched against the WHOLE string the app passes. Chrome passes host:port with no scheme (mtls.example.fi:443), so a pattern starting https:// matches nothing, the device offers no key, and the server answers mtls_fail exactly as if no certificate existed. This one takes both forms and still only the mTLS host.", + "_comment_safety": "Only the named apps may use the key, the user cannot hand it to another app, nothing installs from unknown sources, and apps ask for their permissions as usual. The connector refuses a template that loosens the first three.", + "advancedSecurityOverrides": { + "untrustedAppsPolicy": "DISALLOW_INSTALL" + }, + "choosePrivateKeyRules": [ + { + "packageNames": [ + "com.android.chrome", + "com.atakmap.app.civ", + "im.vector.app" + ], + "privateKeyAlias": "{key_alias}", + "urlPattern": "(https://)?mtls\\.{domain}(:443)?(/.*)?" + } + ], + "privateKeySelectionEnabled": false + } +} diff --git a/src/odmdm_connector/template.py b/src/odmdm_connector/template.py new file mode 100644 index 0000000..a2151f1 --- /dev/null +++ b/src/odmdm_connector/template.py @@ -0,0 +1,206 @@ +"""What a deployment's devices need, read from a file rather than known here + +This module deliberately contains no package name, no managed-configuration key and no product +of any kind. What a deployment installs is a property of that deployment, not of the connector, +so the whole answer arrives as a document an operator supplies and this module only validates it +and fills in the deployment's own values. + +The placeholders are the only vocabulary shared with the document: + +``{domain}`` the deployment's DNS name +``{mtls_url}`` where a client certificate is expected, ``https://mtls.`` +``{key_alias}`` the Android keystore alias the certificate lands under, which is the name of the + MDM certificate template, because installing a second key under an existing alias + fails +""" + +import json +import logging +import re +from dataclasses import dataclass, field +from importlib import resources +from importlib.resources.abc import Traversable +from typing import Any + +LOGGER = logging.getLogger(__name__) + +#: The template shipped with the package: what a Deploy App deployment's phones need. Read through +#: importlib.resources, so that it is found also when the package runs from inside a zip file. +EXAMPLE = resources.files(__package__).joinpath("template.json") + + +class TemplateError(ValueError): + """The document is not something we can act on""" + + +#: The callsign as the common name, from the name the operator gives the phone, and optionally the +#: MDM's own device id beside it. Anything the phone or the enrolment link supplies, a serial +#: number for one, would let whoever holds a leaked enrolment link pick an identity. +SUBJECT = re.compile(r"CN=\$FLEET_VAR_HOST_END_USER_IDP_USERNAME(_LOCAL_PART)?(\s*,\s*OU=\$FLEET_VAR_HOST_UUID)?") + + +def _unsafe(policy: dict[str, Any], certificate: dict[str, Any] | None) -> str: + """Why this policy and certificate would hand out more than the deployment means to, or empty + + Shapes and a few safety rules only. Which apps are named is the template's business. + """ + if certificate is not None and not SUBJECT.fullmatch(str(certificate.get("subject", ""))): + return ( + "the certificate subject must be CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, optionally " + "followed by OU=$FLEET_VAR_HOST_UUID, so the callsign is the name the operator gave the phone" + ) + rules = policy.get("choosePrivateKeyRules", []) + if not isinstance(rules, list): + return "choosePrivateKeyRules must be a list" + for rule in rules: + names = rule.get("packageNames") if isinstance(rule, dict) else None + if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names): + return "every choosePrivateKeyRules entry must name its apps in packageNames, or any app may use the key" + if policy.get("privateKeySelectionEnabled") is True: + return "privateKeySelectionEnabled must not be true, or the user can hand the key to any app" + overrides = policy.get("advancedSecurityOverrides") or {} + untrusted = str(overrides.get("untrustedAppsPolicy", "")) if isinstance(overrides, dict) else "" + if untrusted.startswith("ALLOW_") or policy.get("installUnknownSourcesAllowed") is True: + return "the policy must not allow installs from unknown sources (untrustedAppsPolicy DISALLOW_INSTALL)" + return "" + + +@dataclass(frozen=True) +class App: + """One application the deployment wants on its devices""" + + package: str + #: Install it as part of enrolment rather than leaving it available on demand. On managed + #: Android this is the only automatic path, and it applies at enrolment only. + preinstall: bool = True + #: Managed configuration for the app, already substituted + config: dict[str, Any] = field(default_factory=dict) + + +@dataclass(frozen=True) +class Certificate: + """The certificate the MDM asks us for on a device's behalf + + ``subject`` is identity configuration, not cosmetics: its common name becomes the device's + callsign. It lives here so it is reviewed and deployed like everything else, rather than typed + into a console once and forgotten. + + ``name`` becomes the Android keystore alias, and installing a second key under an existing + alias fails, so it is per deployment rather than per device. + """ + + name: str + subject: str + #: The MDM's certificate authority by name. Without one the MDM plugin finds the Deploy App's + #: own by the address it serves, and makes it when there is none. + authority: str = "" + + +@dataclass(frozen=True) +class LinkApp: + """A managed web app, so the deployment has an icon on the launcher""" + + title: str + url: str + + +@dataclass(frozen=True) +class MdmTemplate: + """Everything to state to an MDM about one deployment""" + + apps: tuple[App, ...] + policy: dict[str, Any] + link_app: LinkApp | None = None + certificate: Certificate | None = None + + @property + def preinstall_packages(self) -> tuple[str, ...]: + return tuple(app.package for app in self.apps if app.preinstall) + + +def _strip_comments(value: Any) -> Any: + """Drop keys beginning with an underscore, at any depth + + The document carries the reasoning for what it asks for, because the reasoning is the part + that was expensive to learn. None of it is for the MDM: an annotation left in an app's + configuration would be pushed to the device as a real setting. + """ + if isinstance(value, dict): + return {key: _strip_comments(item) for key, item in value.items() if not str(key).startswith("_")} + if isinstance(value, list): + return [_strip_comments(item) for item in value] + return value + + +def _substitute(value: Any, values: dict[str, str]) -> Any: + """Fill the placeholders wherever they appear, at any depth""" + if isinstance(value, str): + for key, replacement in values.items(): + value = value.replace("{" + key + "}", replacement) + return value + if isinstance(value, dict): + return {key: _substitute(item, values) for key, item in value.items()} + if isinstance(value, list): + return [_substitute(item, values) for item in value] + return value + + +def load(path: Traversable, domain: str, key_alias: str) -> MdmTemplate: + """Read the document and fill in this deployment's values + + Raises TemplateError rather than letting a malformed document reach the MDM, because a half + applied template is worse than none: apps install at enrolment only, so a device that joins + against a broken one has to be enrolled again. + """ + try: + raw = json.loads(path.read_text(encoding="utf-8")) + except OSError as exc: + raise TemplateError(f"cannot read {path}: {exc}") from exc + except ValueError as exc: + raise TemplateError(f"{path} is not valid JSON: {exc}") from exc + if not isinstance(raw, dict): + raise TemplateError(f"{path} must contain an object") + + values = {"domain": domain, "mtls_url": f"https://mtls.{domain}", "key_alias": key_alias} + raw = _strip_comments(_substitute(raw, values)) + + apps: list[App] = [] + for entry in raw.get("apps", []): + if not isinstance(entry, dict) or not entry.get("package"): + raise TemplateError(f"every app needs a package, got {entry!r}") + config = entry.get("config", {}) + if not isinstance(config, dict): + raise TemplateError(f"config for {entry['package']} must be an object") + apps.append(App(package=str(entry["package"]), preinstall=bool(entry.get("preinstall", True)), config=config)) + if not apps: + raise TemplateError("the template installs nothing; at least one app is required") + + policy = raw.get("policy", {}) + if not isinstance(policy, dict): + raise TemplateError("policy must be an object") + + link = None + if raw.get("link_app"): + entry = raw["link_app"] + if not isinstance(entry, dict) or not entry.get("title") or not entry.get("url"): + raise TemplateError("link_app needs a title and a url") + link = LinkApp(title=str(entry["title"]), url=str(entry["url"])) + + LOGGER.info( + "Template names %s apps, %s of them installed at enrolment", len(apps), len([a for a in apps if a.preinstall]) + ) + certificate = None + if raw.get("certificate"): + entry = raw["certificate"] + missing = [key for key in ("name", "subject") if not entry.get(key)] + if not isinstance(entry, dict) or missing: + raise TemplateError(f"certificate needs name and subject; missing {missing}") + certificate = Certificate( + name=str(entry["name"]), subject=str(entry["subject"]), authority=str(entry.get("authority") or "") + ) + + unsafe = _unsafe(policy, raw.get("certificate") or None) + if unsafe: + raise TemplateError(unsafe) + + return MdmTemplate(apps=tuple(apps), policy=policy, link_app=link, certificate=certificate) diff --git a/src/odmdm_connector/testing/__init__.py b/src/odmdm_connector/testing/__init__.py new file mode 100644 index 0000000..63e0e40 --- /dev/null +++ b/src/odmdm_connector/testing/__init__.py @@ -0,0 +1,5 @@ +"""A kit for MDM plugin authors: FakeMdm to drive the command line, contract to check a plugin""" + +from .fake import FakeMdm + +__all__ = ["FakeMdm"] diff --git a/src/odmdm_connector/testing/contract.py b/src/odmdm_connector/testing/contract.py new file mode 100644 index 0000000..eaa57e8 --- /dev/null +++ b/src/odmdm_connector/testing/contract.py @@ -0,0 +1,192 @@ +"""The checks every MDM plugin must pass, for its own tests + +Each check takes a factory and raises AssertionError saying what is wrong. With pytest:: + + import pytest + from odmdm_connector.testing import contract + + @pytest.mark.parametrize("check", contract.CHECKS, ids=lambda check: check.__name__) + def test_the_contract(check: contract.Check) -> None: + check(my_factory) + +The factory answers a configured MDM whose group holds at least two phones without a name. Given +refuse_after, that MDM refuses to name any phone after that many, as an MDM failing half-way +through a batch would. Plain asserts are not used, so the checks hold under python -O too. +""" + +import datetime +import re +from collections.abc import Callable +from typing import Protocol + +from ..mdm import ( + API_VERSION, + ASK_AGAIN, + CAPABILITIES, + SEND_POLICY, + SET_CHALLENGE, + SETUP, + Mdm, + MdmError, + Phone, + State, + Step, +) +from ..settings import Settings + +#: An enrolment window to hand the MDM; the challenge is not a real one +WINDOW = Settings( + "https://unit.example.fi/scep", "contract-check-challenge", datetime.datetime(2099, 1, 1, tzinfo=datetime.UTC) +) +#: A key has to fit an environment variable name, ODMDM_ +KEY = re.compile(r"[a-z][a-z0-9_]*") + + +class Factory(Protocol): + """Makes the MDM under test""" + + def __call__(self, refuse_after: int | None = None) -> Mdm: ... + + +Check = Callable[[Factory], None] + + +def _require(condition: object, message: str) -> None: + if not condition: + raise AssertionError(message) + + +def _unnamed(mdm: Mdm) -> list[str]: + ids = [phone.id for phone in mdm.phones() if not phone.callsign] + _require(len(ids) >= 2, "the factory's MDM must hold at least two phones without a name") + return ids + + +def _lines(lines: list[str], call: str) -> None: + _require(isinstance(lines, list), f"{call} must answer a list of lines") + _require(all(isinstance(line, str) and line for line in lines), f"{call}'s lines must be non-empty strings") + + +def _raises(call: Callable[[], object], message: str) -> None: + try: + call() + except MdmError: + return + raise AssertionError(message) + + +def _lacking(mdm: Mdm, capability: str, call: Callable[[], object]) -> bool: + """Whether the MDM lacks the capability, having checked that calling it then raises its sentence""" + if capability not in mdm.missing: + return False + try: + call() + except MdmError as exc: + _require(str(exc) == mdm.missing[capability], f"{capability}, lacking, must raise MdmError with its sentence") + return True + raise AssertionError(f"{capability} is listed as missing but did not raise MdmError") + + +def declares_the_contract_version(factory: Factory) -> None: + mdm = factory() + _require(mdm.API_VERSION == API_VERSION, f"API_VERSION must be {API_VERSION}") + _require(isinstance(mdm.title, str) and mdm.title, "title must be the MDM's name") + + +def declares_its_fields(factory: Factory) -> None: + fields = factory().fields + _require(isinstance(fields, tuple), "fields must be a tuple of Field") + keys = [item.key for item in fields] + labels = [item.label for item in fields] + _require(all(KEY.fullmatch(key) for key in keys), "a field's key is lower case letters, digits and _") + _require(len(set(keys)) == len(keys), "field keys must be unique") + _require(all(labels) and len(set(labels)) == len(labels), "field labels must be given and unique") + + +def says_what_it_lacks(factory: Factory) -> None: + missing = factory().missing + _require(set(missing) <= set(CAPABILITIES), f"missing names only capabilities among {', '.join(CAPABILITIES)}") + _require(all(isinstance(text, str) and text for text in missing.values()), "each lacking capability has a sentence") + + +def lists_its_phones(factory: Factory) -> None: + found = factory().phones() + _require(isinstance(found, list), "phones must answer a list") + for phone in found: + _require(isinstance(phone, Phone), "phones must answer Phone objects") + _require(isinstance(phone.id, str) and phone.id, "a phone's id is a non-empty string") + _require(isinstance(phone.state, State), "a phone's state is a State") + _require(isinstance(phone.callsign, str) and isinstance(phone.detail, str), "callsign and detail are strings") + try: + datetime.datetime.fromisoformat(phone.joined) + except ValueError as exc: + raise AssertionError(f"phone {phone.id} joined {phone.joined!r}, not an ISO time") from exc + + +def names_phones(factory: Factory) -> None: + mdm = factory() + first = _unnamed(mdm)[0] + _lines(mdm.name({first: "CONTRACT1"}), "name") + callsigns = {phone.id: phone.callsign for phone in mdm.phones()} + _require(callsigns.get(first) == "CONTRACT1", "a phone named must show its callsign in phones") + + +def refuses_an_unknown_id(factory: Factory) -> None: + mdm = factory() + before = mdm.phones() + _raises(lambda: mdm.name({"no-such-phone": "CONTRACT9"}), "name of an id not in the group must raise MdmError") + _raises(lambda: mdm.ask_again(["no-such-phone"]), "ask_again of an id not in the group must raise MdmError") + _require(mdm.phones() == before, "an id not in the group must change nothing") + + +def says_what_a_batch_stopped_half_way_named(factory: Factory) -> None: + mdm = factory(refuse_after=1) + first, second = _unnamed(mdm)[:2] + try: + mdm.name({first: "CONTRACT1", second: "CONTRACT2"}) + except MdmError as exc: + _require(exc.named == {first: "CONTRACT1"}, f"MdmError.named must be the phones named, not {exc.named}") + return + raise AssertionError("name must raise MdmError when the MDM refuses a phone half-way") + + +def asks_again(factory: Factory) -> None: + mdm = factory() + if not _lacking(mdm, ASK_AGAIN, lambda: mdm.ask_again([])): + _lines(mdm.ask_again([]), "ask_again") + + +def sets_the_challenge(factory: Factory) -> None: + mdm = factory() + if not _lacking(mdm, SET_CHALLENGE, lambda: mdm.set_challenge(WINDOW)): + mdm.set_challenge(WINDOW) + + +def sets_up(factory: Factory) -> None: + mdm = factory() + if not _lacking(mdm, SETUP, lambda: list(mdm.setup(WINDOW, dry_run=True))): + steps = list(mdm.setup(WINDOW, dry_run=True)) + _require(steps and all(isinstance(step, Step) for step in steps), "setup must report Steps") + + +def sends_the_policy_again(factory: Factory) -> None: + mdm = factory() + if SETUP in mdm.missing or _lacking(mdm, SEND_POLICY, lambda: list(mdm.setup(WINDOW, force=True, dry_run=True))): + return + steps = list(mdm.setup(WINDOW, force=True, dry_run=True)) + _require(steps and all(isinstance(step, Step) for step in steps), "setup with force must report Steps") + + +CHECKS: tuple[Check, ...] = ( + declares_the_contract_version, + declares_its_fields, + says_what_it_lacks, + lists_its_phones, + names_phones, + refuses_an_unknown_id, + says_what_a_batch_stopped_half_way_named, + asks_again, + sets_the_challenge, + sets_up, + sends_the_policy_again, +) diff --git a/src/odmdm_connector/testing/fake.py b/src/odmdm_connector/testing/fake.py new file mode 100644 index 0000000..a3d9f18 --- /dev/null +++ b/src/odmdm_connector/testing/fake.py @@ -0,0 +1,109 @@ +"""FakeMdm: an MDM in memory, implementing the whole contract, for tests""" + +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import replace +from typing import ClassVar + +from ..mdm import API_VERSION, ASK_AGAIN, SEND_POLICY, SET_CHALLENGE, SETUP, Field, MdmError, Phone, State, Step +from ..settings import Settings + +#: The group's phones when a test gives none: two waiting for a name, one with its certificate +PHONES = ( + Phone("a1", "", "Pretend Phone 7", "2026-11-01T09:00:00+00:00", State.NEEDS_NAME), + Phone("a2", "", "Pretend Phone 7", "2026-11-01T09:05:00+00:00", State.NEEDS_NAME), + Phone("a3", "OTTER1", "Pretend Tablet 2", "2026-11-01T09:10:00+00:00", State.READY), +) + +#: The states ask_again without ids picks, as the contract says +AGAIN = (State.NOT_ASKED, State.REFUSED, State.UNREACHABLE, State.FAILED) + + +class FakeMdm: + """An MDM whose group is a list in memory + + calls records what it was asked, by method name. refuse_after makes name refuse the phone + after that many were named, as an MDM failing half-way through a batch does. lacking() gives a + class without some capabilities. + """ + + API_VERSION: ClassVar[int] = API_VERSION + title: ClassVar[str] = "Fake MDM" + fields: ClassVar[tuple[Field, ...]] = ( + Field("group", "Group", default="Deploy App", help="The group phones enrol into"), + Field("password", "Password", secret=True, help="Read from the file ODMDM_PASSWORD_FILE names"), + ) + missing: ClassVar[Mapping[str, str]] = {} + + def __init__( + self, values: Mapping[str, str], phones: Sequence[Phone] = PHONES, refuse_after: int | None = None + ) -> None: + self.values = dict(values) + self.group = list(phones) + self.refuse_after = refuse_after + self.calls: list[str] = [] + #: The challenge last given, kept so a test can see it arrived + self.challenge = "" + + @classmethod + def lacking(cls, *capabilities: str) -> type["FakeMdm"]: + """A FakeMdm class without these capabilities, each with a sentence saying so""" + missing = {capability: f"The fake MDM cannot {capability}" for capability in capabilities} + return type("LackingFakeMdm", (cls,), {"missing": missing}) + + def _able(self, capability: str) -> None: + self.calls.append(capability) + if capability in self.missing: + raise MdmError(self.missing[capability]) + + def _ids(self, ids: Sequence[str]) -> None: + known = {phone.id for phone in self.group} + unknown = [phone for phone in ids if phone not in known] + if unknown: + raise MdmError(f"Phone {unknown[0]} is not in the group") + + def _waiting(self, phone: str, callsign: str | None = None) -> None: + """The phone, under its new callsign if given, now waits for its certificate""" + self.group = [ + replace(each, callsign=each.callsign if callsign is None else callsign, state=State.WAITING) + if each.id == phone + else each + for each in self.group + ] + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + self._able(SETUP) + if force: + self._able(SEND_POLICY) + yield Step(f"Group {self.values.get('group', 'Deploy App')} enrols at {window.scep_url}", True) + if dry_run: + return + yield Step("Certificate template stated", True, "forced" if force else "") + + def set_challenge(self, window: Settings) -> None: + self._able(SET_CHALLENGE) + self.challenge = window.challenge + + def phones(self) -> list[Phone]: + self.calls.append("phones") + return list(self.group) + + def name(self, names: Mapping[str, str]) -> list[str]: + self.calls.append("name") + self._ids(list(names)) + named: dict[str, str] = {} + lines: list[str] = [] + for phone, callsign in names.items(): + if self.refuse_after is not None and len(named) >= self.refuse_after: + raise MdmError(f"The fake MDM refused phone {phone}", named, lines) + self._waiting(phone, callsign) + named[phone] = callsign + lines.append(f"Phone {phone} is {callsign}") + return lines + + def ask_again(self, ids: Sequence[str]) -> list[str]: + self._able(ASK_AGAIN) + self._ids(ids) + again = list(ids) or [phone.id for phone in self.group if phone.callsign and phone.state in AGAIN] + for phone in again: + self._waiting(phone) + return [f"Phone {phone}: certificate asked for again" for phone in again] diff --git a/src/odmdm_connector/web.py b/src/odmdm_connector/web.py new file mode 100644 index 0000000..6350bcf --- /dev/null +++ b/src/odmdm_connector/web.py @@ -0,0 +1,427 @@ +"""The connector as a page served on this computer, the second face of App beside the command line + +A standard library HTTP server on 127.0.0.1 only, a thread per connection, so that a connection a +browser opens and leaves idle holds nothing up; the App is called by one of them at a time. It +serves three fixed files and JSON answers; every decision is App's, and the page draws what they say. + +A request is answered only when it names this computer's address in its Host header, which stops +a page elsewhere from reaching this one through DNS rebinding. The three files are public code and +need nothing more. Everything under /api/ carries the header X-ODMDM-Key, holding the key made at +start that the address printed hands the page in its fragment, which no server is sent: so another +user or program on the computer cannot drive the page. A cookie would not do, as a browser sends a +cookie for 127.0.0.1 to every port of it. A POST must come from the page itself, by its Origin +header. No answer and +no log line holds the MDM token or the settings line; the challenge is in an answer only when the +MDM has to be given it by hand. +""" + +import datetime +import json +import logging +import secrets +import sys +import threading +import time +from collections.abc import Callable, Mapping +from dataclasses import asdict +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib import resources +from typing import Any +from urllib.parse import urlsplit + +from . import __version__ +from .app import App, AppError, Banner, Job, Result + +LOGGER = logging.getLogger(__name__) + +PORT = 8737 +#: The largest request body taken +LIMIT = 64 * 1024 +#: The request header that carries the page's key +KEY = "X-ODMDM-Key" +#: Seconds between listings of the phones while the page asks for its state +REFRESH = 60.0 +#: Seconds a connection may stay silent before it is dropped +TIMEOUT = 5 +#: The only files served, by request path: no path from a request reaches the file system +STATIC = { + "/": ("index.html", "text/html; charset=utf-8"), + "/app.css": ("app.css", "text/css; charset=utf-8"), + "/app.js": ("app.js", "text/javascript; charset=utf-8"), +} +HEADERS = { + "Cache-Control": "no-store", + "Content-Security-Policy": "default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", +} +FORBIDDEN = "Open the address that the connector printed when it started. This page then goes on by itself." + +Body = dict[str, Any] + + +def _now() -> datetime.datetime: + return datetime.datetime.now().astimezone() + + +def _text(body: Body, key: str) -> str: + value = body.get(key, "") + if not isinstance(value, str): + raise AppError(f"The page sent {key} as something other than text.") + return value + + +def _texts(body: Body, key: str) -> list[str]: + value = body.get(key, []) + if not isinstance(value, list) or not all(isinstance(each, str) for each in value): + raise AppError(f"The page sent {key} as something other than a list of text.") + return value + + +def _banner(banner: Banner) -> dict[str, str]: + return {"level": banner.level.value, "text": banner.text} + + +class Page(ThreadingHTTPServer): + """The page's server: on this computer only, with a key made at start, and the App called under one lock""" + + # On Windows the option lets another program bind the same port and take the page's requests + allow_reuse_address = sys.platform != "win32" + daemon_threads = True + + def __init__( + self, + app: App, + port: int = PORT, + now: Callable[[], datetime.datetime] = _now, + clock: Callable[[], float] = time.monotonic, + ) -> None: + super().__init__(("127.0.0.1", port), Handler) + self.app, self.now, self.clock = app, now, clock + self.port: int = self.server_address[1] + self.key = secrets.token_urlsafe(32) + #: Held around every call into the App, so that it sees one caller at a time + self.lock = threading.Lock() + self.hosts = {f"127.0.0.1:{self.port}", f"localhost:{self.port}"} + self.origins = {f"http://{host}" for host in self.hosts} + #: The steps of the last setup or sending of the policy, as its result brought them, and its error + self.steps: list[dict[str, Any]] = [] + self.setup_error = "" + #: When the phones were last asked for, by clock; None before the first time + self.listed: float | None = None + #: The Deploy App whose phones arrived last, and the hour and minute they did, in the operator's time + self.updated = ("", "") + + @property + def address(self) -> str: + """Where the operator opens the page: the key in the fragment, which the browser sends to no server""" + return f"http://127.0.0.1:{self.port}/#key={self.key}" + + def handle_error(self, request: Any, client_address: Any) -> None: + """A request that failed outside the answers goes to the log, not the terminal + + A connection the browser dropped or left silent is one line naming its kind. + """ + failure = sys.exception() + if isinstance(failure, OSError): + LOGGER.info("A connection to the page ended: %s", type(failure).__name__) + else: + LOGGER.exception("The page could not answer a request") + + def _take(self, results: list[Result], now: datetime.datetime) -> None: + for result in results: + if result.job in (Job.SETUP, Job.POLICY): + self.steps, self.setup_error = [asdict(step) for step in result.steps], result.error + elif result.job is Job.PHONES and result.phones is not None: + self.updated = (result.host, now.strftime("%H:%M")) + + def _list(self) -> None: + """Ask for the phones, when an MDM is connected""" + if self.app.connected: + self.app.refresh() + self.listed = self.clock() + + def state(self) -> Body: + """Everything the page draws, after taking in the worker's results + + The phones are asked for again once REFRESH seconds have passed, so they are listed only + while a page is open and asking. + """ + app, now = self.app, self.now() + self._take(app.drain(), now) + if self.listed is None or self.clock() - self.listed >= REFRESH: + self._list() + conn = app.conn + return { + "version": __version__, + # Each Deploy App with a few words on its enrolment window, for the list of them + "connections": [ + {"host": each.host, "level": each.banner.level.value, "short": each.banner.short, "active": each.active} + for each in app.connections(now) + ], + "active": app.saved.active, + "banner": _banner(app.banner(now)), + # Where the operator opens enrolment again, in a tab of its own + "mdm_page": app.mdm_page, + "mdm": conn.mdm, + "connected": app.connected, + # Whether a secret can be kept in this computer's keychain, so the page offers to remember it + "keeps": app.keeps, + # What stops the MDM being connected: none chosen yet, or its secret not at hand + "needs": "" if app.connected or not app.saved.active else ("secret" if conn.mdm else "mdm"), + "mdms": [ + {"name": each.name, "package": each.package, "version": each.version, "built_in": each.built_in} + for each in app.mdms() + ], + # What sending the policy again does, empty when the MDM cannot + "policy": app.policy_note(), + # While a setup runs, the steps it has done so far; after it, the steps its result brought + "steps": self.steps or [asdict(step) for step in app.progress], + "setup_error": self.setup_error, + "summary": app.summary(), + "rows": [asdict(row) for row in app.rows(now)], + "status": app.status, + # When the phones of the active Deploy App were last listed, as HH:MM; empty before the first time + "updated": self.updated[1] if self.updated[0] == app.saved.active and app.connected else "", + "lines": list(app.lines), + "busy": [job.value for job in Job if app.busy(job)], + "challenge_note": app.challenge_note(), + "challenge": app.challenge(), + "prefix": conn.prefix, + "callsigns": conn.callsigns, + "log": str(app.log_path), + } + + # The answers to the page's POSTs, each from its JSON body + + def read(self, body: Body) -> Body: + return asdict(self.app.read_settings(_text(body, "line"), self.now(), _text(body, "from"))) + + def add(self, body: Body) -> Body: + said = self.app.paste_settings(_text(body, "line"), self.now(), _text(body, "from")) + self._list() + return {"said": said} + + def open(self, body: Body) -> Body: + said = self.app.open(_text(body, "host"), self.now()) + self._list() + return {"said": said} + + def remove(self, body: Body) -> Body: + return {"said": self.app.remove(_text(body, "host"))} + + def form(self, body: Body) -> Body: + """The question before a plugin is used, or the MDM's fields with their values, never a secret's""" + name = _text(body, "mdm") + question = self.app.approval(name) + if question: + return {"approval": question} + form = self.app.form(name) + return { + "name": form.name, + "title": form.title, + "fields": [ + { + **asdict(each.field), + "value": "" if each.field.secret else each.value, + "kept": each.field.secret and bool(each.value), + "remembered": each.remembered, + } + for each in form.fields + ], + } + + def approve(self, body: Body) -> Body: + self.app.approve(_text(body, "mdm")) + return {} + + def connect(self, body: Body) -> Body: + """Connect with the values typed; a secret left empty is the one kept, as App.connect allows + + remember keeps the secrets in this computer's keychain; without it, any kept copy is removed. + """ + name = _text(body, "mdm") + given, remember = body.get("values", {}), body.get("remember", False) + if not isinstance(given, dict) or not all(isinstance(each, str) for each in given.values()): + raise AppError("The page sent the values as something other than text.") + if not isinstance(remember, bool): + raise AppError("The page sent remember as something other than yes or no.") + self.steps, self.setup_error = [], "" + said = self.app.connect(name, given, remember) + self._list() + return {"said": said} + + def refresh(self, body: Body) -> Body: + self._list() + return {} + + def policy(self, body: Body) -> Body: + """Send the policy again, its steps shown as a setup's""" + said = self.app.send_policy() + self.steps, self.setup_error = [], "" + return {"said": said} + + def preview(self, body: Body) -> Body: + """What naming the phones chosen would do, and the first number a numbered batch starts from""" + app = self.app + ids = app.targets(_texts(body, "ids")) + if _text(body, "how") == "list": + found, start = app.preview(ids, app.listed(_text(body, "list")), self.now()), 0 + else: + prefix, first = _text(body, "prefix").strip(), _text(body, "first").strip() + if first and not first.isdigit(): + raise AppError("The first number must be a whole number.") + start = int(first) if first else app.first_number(prefix) + found = app.preview(ids, app.numbered(prefix, start, len(ids)), self.now()) + return {**asdict(found), "ok": found.ok, "button": found.button, "first": start} + + def name(self, body: Body) -> Body: + """Name what the preview shown held, which the App takes only if it is the preview that passed last + + The callsigns are kept for next time too: a numbered batch's prefix, and a list if asked to save it. + """ + names, save = body.get("names"), body.get("save", False) + if not isinstance(names, dict) or not all(isinstance(each, str) for each in names.values()): + raise AppError("The page sent the names as something other than text.") + if not isinstance(save, bool): + raise AppError("The page sent save as something other than yes or no.") + app = self.app + said = app.name(names) + if _text(body, "how") == "list": + if save: + app.keep_callsigns(app.conn.prefix, app.listed(_text(body, "list"))) + else: + app.keep_callsigns(_text(body, "prefix").strip(), app.conn.callsigns) + return {"said": said} + + def again(self, body: Body) -> Body: + return {"said": self.app.ask_again(_texts(body, "ids"))} + + def detail(self, body: Body) -> Body: + return asdict(self.app.detail(_text(body, "id"), self.now())) + + +#: The POST answers by path +ACTIONS: Mapping[str, Callable[[Page, Body], Body]] = { + "/api/read": Page.read, + "/api/add": Page.add, + "/api/open": Page.open, + "/api/remove": Page.remove, + "/api/form": Page.form, + "/api/approve": Page.approve, + "/api/connect": Page.connect, + "/api/refresh": Page.refresh, + "/api/policy": Page.policy, + "/api/preview": Page.preview, + "/api/name": Page.name, + "/api/again": Page.again, + "/api/detail": Page.detail, +} + + +class Handler(BaseHTTPRequestHandler): + """One request: checked, then a fixed file, the state or an answer""" + + server: Page + timeout = TIMEOUT + server_version = "odmdm-connector" + + def version_string(self) -> str: + """The Server header: the name alone, without Python's version""" + return self.server_version + + def log_message(self, format: str, *args: Any) -> None: + """No request log: the first request's address holds the key""" + + def _answer(self, status: int, body: bytes, kind: str) -> None: + self.send_response(status) + headers = {**HEADERS, "Content-Type": kind, "Content-Length": str(len(body))} + for header, value in headers.items(): + self.send_header(header, value) + self.end_headers() + self.wfile.write(body) + + def _plain(self, status: int, sentence: str) -> None: + self._answer(status, sentence.encode(), "text/plain; charset=utf-8") + + def _json(self, status: int, data: Body) -> None: + self._answer(status, json.dumps(data).encode(), "application/json") + + def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None: + """http.server's own refusals, such as a malformed request, in the same plain form""" + self.close_connection = True + self._plain(code, message or HTTPStatus(code).phrase) + + def _refuse(self) -> None: + self._plain(HTTPStatus.FORBIDDEN, FORBIDDEN) + + def _here(self) -> bool: + """Whether the request came to this computer's address, in its one Host header; refused if not""" + hosts = self.headers.get_all("Host") or [] + if len(hosts) == 1 and hosts[0] in self.server.hosts: + return True + self._refuse() + return False + + def _admitted(self) -> bool: + """Whether the request came to this computer's address with the key in its one key header; refused if not""" + if not self._here(): + return False + given = self.headers.get_all(KEY) or [] + if len(given) == 1 and secrets.compare_digest(given[0].encode(), self.server.key.encode()): + return True + self._refuse() + return False + + def do_GET(self) -> None: + if not self._here(): + return + url = urlsplit(self.path) + if url.path in STATIC: + name, kind = STATIC[url.path] + self._answer(HTTPStatus.OK, resources.files(__package__).joinpath("static", name).read_bytes(), kind) + elif self._admitted(): + if url.path == "/api/state": + self._call(lambda: self.server.state()) + else: + self._plain(HTTPStatus.NOT_FOUND, "Not found.") + + def do_POST(self) -> None: + if not self._admitted(): + return + if self.headers.get("Origin") not in self.server.origins: + self._refuse() + return + action = ACTIONS.get(self.path) + if action is None: + self._plain(HTTPStatus.NOT_FOUND, "Not found.") + return + length = self.headers.get("Content-Length", "") + if not length.isdigit() or int(length) > LIMIT: + self._plain(HTTPStatus.BAD_REQUEST, "The request has no length or is too large.") + return + try: + body = json.loads(self.rfile.read(int(length)) or b"{}") + except (ValueError, RecursionError): + body = None + if not isinstance(body, dict): + self._plain(HTTPStatus.BAD_REQUEST, "The request is not a JSON object.") + return + self._call(lambda: action(self.server, body)) + + def _call(self, answer: Callable[[], Body]) -> None: + """The answer as JSON, made under the lock; an AppError is its sentence, anything else points at the log""" + try: + with self.server.lock: + data = answer() + except AppError as exc: + self._json(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) + except Exception: # A bug reaches the operator as a sentence, and the page goes on + LOGGER.exception("The page's request %s failed", urlsplit(self.path).path) + self._json( + HTTPStatus.INTERNAL_SERVER_ERROR, + {"error": f"The connector failed; the log says more: {self.server.app.log_path}"}, + ) + else: + self._json(HTTPStatus.OK, data) diff --git a/src/odmdm_fleet/__init__.py b/src/odmdm_fleet/__init__.py deleted file mode 100644 index 5ea4aca..0000000 --- a/src/odmdm_fleet/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Connects FleetDM to an OpenDefence deployment's SCEP enrolment""" - -__version__ = "0.1.0+261031" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/data/settings-line-v1.txt b/tests/data/settings-line-v1.txt new file mode 100644 index 0000000..88a888d --- /dev/null +++ b/tests/data/settings-line-v1.txt @@ -0,0 +1 @@ +ODMDM1 https://unit.example.fi/scep 0123456789abcdef0123456789abcdef 2026-11-21T14:00:00Z diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..b433301 --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,1509 @@ +"""The page's core without a page: the FakeMdm, a temporary settings directory and the time given""" + +import datetime +import io +import logging +import sys +import threading +import time +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import replace +from importlib.metadata import EntryPoint +from pathlib import Path +from typing import ClassVar + +import pytest + +from odmdm_connector import app, plugins, store +from odmdm_connector.fleet_plugin import FleetPlugin +from odmdm_connector.mdm import ASK_AGAIN, SEND_POLICY, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, Phone, State, Step +from odmdm_connector.settings import Settings +from odmdm_connector.testing import FakeMdm +from odmdm_connector.testing.fake import PHONES + +from .test_store import MemoryBackend + +CHALLENGE = "0123456789abcdef0123456789abcdef" # pragma: allowlist secret +LINE = f"ODMDM1 https://unit.example.fi/scep {CHALLENGE} 2026-11-21T14:00:00Z" +OTHER = LINE.replace("unit.example.fi", "other.example.fi").replace("14:00:00Z", "15:30:00Z") +NOW = datetime.datetime(2026, 11, 21, 12, 0, tzinfo=datetime.UTC) +VALUES = {"group": "Deploy App", "password": "pa55word"} # pragma: allowlist secret +LACKING = FakeMdm.lacking(SETUP, SET_CHALLENGE, ASK_AGAIN) + + +class Rig: + """An App and everything handed to it""" + + def __init__(self, directory: Path, backend: MemoryBackend | None = None) -> None: + self.directory = directory + #: The keychain, kept across starts; none by default, as in the one-file build + self.backend = backend + self.loaded: list[str] = [] + self.classes: dict[str, type[Mdm]] = {"fake": FakeMdm, "demo": LACKING} + self.versions = {"demo": "1.0.0"} + #: What listing the plugins raises, if anything + self.unlisted: plugins.PluginError | None = None + #: What plugins.load says when it cannot load the plugin + self.refused = "" + self.app = self.start() + + def installed(self) -> list[plugins.Plugin]: + if self.unlisted: + raise self.unlisted + return [ + plugins.Plugin("fake", "odmdm-connector", "1.2.0", EntryPoint("fake", "odmdm_connector.testing:Fake", "g")), + plugins.Plugin("demo", "odmdm-connector-demo", self.versions["demo"], EntryPoint("demo", "demo:Demo", "g")), + ] + + def load(self, name: str) -> type[Mdm]: + self.loaded.append(name) + if self.refused: + raise plugins.PluginError(self.refused) + return self.classes[name] + + def start(self) -> app.App: + """The app as started afresh on the same computer""" + return app.App( + store.Store(self.directory), + installed=self.installed, + load=self.load, + log_path=self.directory / "the.log", + keychain=store.Keychain(self.backend), + ) + + def settle(self) -> list[app.Result]: + self.app.worker.wait() + return self.app.drain() + + def connected(self, name: str = "fake", values: Mapping[str, str] = VALUES, remember: bool = True) -> FakeMdm: + """Pasted, connected and the phones read""" + self.app.paste_settings(LINE, NOW) + if self.app.approval(name): + self.app.approve(name) + self.app.connect(name, values, remember) + self.app.refresh() + self.settle() + assert isinstance(self.app.mdm, FakeMdm) + return self.app.mdm + + +@pytest.fixture +def rig(tmp_path: Path) -> Iterator[Rig]: + made = Rig(tmp_path / "config") + yield made + made.app.close() + + +@pytest.fixture +def keyed(tmp_path: Path) -> Iterator[Rig]: + """A rig whose computer has a keychain""" + made = Rig(tmp_path / "config", MemoryBackend()) + yield made + made.app.close() + + +#: Where the fake MDM's password for unit.example.fi is kept +KEPT = ("odmdm-connector", "unit.example.fi:fake:password") + + +def test_first_setup_holds_the_secret_in_memory_and_the_rest_in_the_file(rig: Rig) -> None: + with pytest.raises( + app.AppError, match="^Add the Deploy App first: on its MDM page, press Open in the MDM connector.$" + ): + rig.app.connect("fake", VALUES) + + pasted = rig.app.paste_settings(f" {LINE}\n", NOW) + form = rig.app.form("fake") + said = rig.app.connect("fake", VALUES) + [result] = rig.settle() + + assert pasted == "Deploy App unit.example.fi accepts phones until 14:00." + assert (form.title, [(value.field.key, value.value) for value in form.fields]) == ( + "Fake MDM", + [("group", "Deploy App"), ("password", "")], + ) + assert said == "Setting Fake MDM up for Deploy App unit.example.fi." + assert (result.job, result.error) == (app.Job.SETUP, "") + assert [step.label for step in result.steps] == [ + "Group Deploy App enrols at https://unit.example.fi/scep", + "Certificate template stated", + ] + assert rig.app.status == "Fake MDM is set up for Deploy App unit.example.fi." + assert rig.app.form("fake").fields[1].value == "pa55word" + text = (rig.directory / "settings.json").read_text(encoding="utf-8") + assert CHALLENGE not in text and "pa55word" not in text + assert rig.app.saved == store.Saved( + connections={ + "unit.example.fi": store.Connection( + mdm="fake", values={"group": "Deploy App"}, closes="2026-11-21T14:00:00+00:00" + ) + }, + active="unit.example.fi", + ) + + +@pytest.mark.parametrize( + ("values", "says"), + [ + ({"mdm_url": "", "token": "t0ken"}, "Fill in Fleet address."), # pragma: allowlist secret + ({"mdm_url": "https://mdm.example.fi", "token": " "}, "Fill in API token."), + ], +) +def test_a_required_field_left_empty_is_said_and_nothing_kept(rig: Rig, values: dict[str, str], says: str) -> None: + rig.classes["fake"] = FleetPlugin + rig.app.paste_settings(LINE, NOW) + before = rig.app.saved + + with pytest.raises(app.AppError, match=f"^{says}$"): + rig.app.connect("fake", values) + + assert rig.app.form("fake").fields[1].value == "" + assert rig.app.saved == before + assert store.Store(rig.directory).load() == before + assert rig.app.mdm is None + + +class Addressed(FakeMdm): + """An MDM with an address, which records every one made, as each would send its token there""" + + fields: ClassVar[tuple[Field, ...]] = ( + Field("mdm_url", "Address", required=True), + Field("token", "Token", secret=True, required=True), + Field("team", "Team", default="Deploy App"), + ) + made: ClassVar[list[dict[str, str]]] = [] + + def __init__(self, values: Mapping[str, str]) -> None: + super().__init__(values) + Addressed.made.append(dict(values)) + + +TOKEN_VALUES = {"mdm_url": "https://mdm.example.fi", "token": "t0ken", "team": "Deploy App"} # pragma: allowlist secret + + +@pytest.mark.parametrize( + "changed", + [ + {"mdm_url": "https://attacker.example.fi"}, + {"team": "Other"}, + {"mdm_url": "https://mdm.example.fi", "team": ""}, + ], +) +def test_a_kept_secret_goes_only_with_the_settings_it_was_kept_for(keyed: Rig, changed: dict[str, str]) -> None: + keyed.classes["fake"] = Addressed + keyed.app.paste_settings(LINE, NOW) + keyed.app.connect("fake", TOKEN_VALUES) + keyed.settle() + Addressed.made.clear() + before, backend = keyed.app.saved, keyed.backend + assert backend is not None + kept = dict(backend.items) + + with pytest.raises(app.AppError, match="^Type the Token again: the settings changed.$"): + keyed.app.connect("fake", {**TOKEN_VALUES, "token": "", **changed}) + + assert Addressed.made == [], "no MDM made, so nothing sent" + assert (keyed.app.saved, store.Store(keyed.directory).load(), backend.items) == (before, before, kept) + assert not keyed.app.busy() + assert keyed.app.connect("fake", {**TOKEN_VALUES, "token": ""}) == ( + "Setting Fake MDM up for Deploy App unit.example.fi." + ) + assert Addressed.made == [TOKEN_VALUES], "the same settings take the kept token" + keyed.settle() + + +def test_a_secret_is_held_only_once_its_settings_are_written(rig: Rig) -> None: + """Held before, a new token would stay under the old saved address and go there on the next connect""" + rig.classes["fake"] = Addressed + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", TOKEN_VALUES) + rig.settle() + Addressed.made.clear() + rig.app.store = store.Store(rig.directory / "settings.json" / "not-a-directory") + + with pytest.raises(app.AppError, match="cannot be written"): + rig.app.connect("fake", {**TOKEN_VALUES, "mdm_url": "https://new.example.fi", "token": "NEWTOKEN"}) + rig.app.store = store.Store(rig.directory) + rig.app.connect("fake", {**TOKEN_VALUES, "token": ""}) + + assert Addressed.made == [TOKEN_VALUES], "the old address gets only the token typed for it" + rig.settle() + + +def test_a_kept_secret_does_not_go_to_another_mdm(rig: Rig) -> None: + rig.connected() + rig.app.approve("demo") + + rig.app.connect("demo", {"group": "Deploy App", "password": ""}) + + assert isinstance(rig.app.mdm, FakeMdm) + assert rig.app.mdm.values == {"group": "Deploy App", "password": ""} + rig.settle() + + +@pytest.mark.parametrize("token", ["TOPSECRETA\nTOPSECRETB", "TOPSECRET\r", "TOP\x00SECRET", "TOP\x7fSECRET"]) +def test_a_secret_with_a_control_character_is_refused_before_it_is_held( + rig: Rig, caplog: pytest.LogCaptureFixture, token: str +) -> None: + caplog.set_level(logging.DEBUG) + rig.classes["fake"] = Addressed + rig.app.paste_settings(LINE, NOW) + before = rig.app.saved + + with pytest.raises(app.AppError) as raised: + rig.app.connect("fake", {**TOKEN_VALUES, "token": token}) + + assert str(raised.value) == ( + "The Token holds a line break or another character that cannot be part of it: copy it again." + ) + assert (rig.app.saved, rig.app.mdm, rig.app.form("fake").fields[1].value) == (before, None, "") + assert "TOPSECRET" not in caplog.text + + +def test_a_restart_holds_no_secret_and_connects_without_a_window(rig: Rig) -> None: + """The token is typed again on another day, and the MDM already set up is only connected""" + rig.connected() + + again = rig.start() + held = again.form("fake").fields[1].value + said = again.connect("fake", VALUES) + + assert (held, again.window) == ("", None) + assert said == "Connected to Fake MDM for Deploy App unit.example.fi." + assert isinstance(again.mdm, FakeMdm) + assert (again.mdm.values, again.mdm.calls, again.busy()) == (VALUES, [], False) + assert again.banner(NOW).text == "Deploy App unit.example.fi accepts phones until 14:00" + again.approve("demo") + with pytest.raises( + app.AppError, + match="^To set Fake MDM up, open enrolment on the MDM page of Deploy App unit.example.fi, " + "then press Open in the MDM connector there.$", + ): + again.connect("demo", VALUES) + again.close() + + +def test_a_damaged_settings_file_is_said_and_the_app_starts_without_it(rig: Rig) -> None: + rig.directory.mkdir() + (rig.directory / "settings.json").write_text("{", encoding="utf-8") + + started = rig.start() + + assert started.saved == store.Saved() + assert started.status.endswith("is damaged, so the app starts without it.") + started.close() + + +@pytest.mark.parametrize( + ("line", "says"), + [ + ("0123", "This is not a settings line: it has four parts and starts with ODMDM1."), + (LINE.replace("https", "http"), "The SCEP URL in the settings line must be https:///"), + (LINE.replace("14:00:00Z", "11:00:00Z"), "The enrolment window closed at 11:00"), + ], +) +def test_a_line_that_is_not_one_is_refused_in_a_sentence(rig: Rig, line: str, says: str) -> None: + with pytest.raises(app.AppError) as raised: + rig.app.paste_settings(line, NOW) + + assert str(raised.value).startswith(says) + assert (rig.app.window, rig.app.saved) == (None, store.Saved()) + + +def test_a_line_for_another_deploy_app_adds_it_and_works_with_it(rig: Rig) -> None: + rig.connected() + rig.app.preview(["a1"], ["BEAR1"], NOW) + + said = rig.app.paste_settings(OTHER, NOW) + + assert said == "Deploy App other.example.fi accepts phones until 15:30." + assert rig.app.saved.active == "other.example.fi" + assert list(rig.app.saved.connections) == ["unit.example.fi", "other.example.fi"] + assert rig.app.saved.connections["unit.example.fi"].values == {"group": "Deploy App"} + assert (rig.app.conn, rig.app.mdm, rig.app.phones) == ( + store.Connection(closes="2026-11-21T15:30:00+00:00"), + None, + [], + ) + assert rig.app.window is not None and rig.app.window.scep_url == "https://other.example.fi/scep" + with pytest.raises(app.AppError, match="Connect to the MDM first."): + rig.app.name({"a1": "BEAR1"}) + + +def test_two_deploy_apps_side_by_side_each_with_its_own_mdm_and_token(rig: Rig) -> None: + unit = rig.connected() + rig.app.paste_settings(OTHER, NOW) + rig.app.connect("fake", {"group": "Other unit", "password": "0ther"}) # pragma: allowlist secret + rig.settle() + + back = rig.app.open("unit.example.fi", NOW) + unit_again = rig.app.mdm + other = rig.app.open("other.example.fi", NOW) + + assert back == "Deploy App unit.example.fi accepts phones until 14:00." + assert isinstance(unit_again, FakeMdm) and unit_again is not unit + assert unit_again.values == VALUES + assert other == "Deploy App other.example.fi accepts phones until 15:30." + assert isinstance(rig.app.mdm, FakeMdm) + assert rig.app.mdm.values == {"group": "Other unit", "password": "0ther"} # pragma: allowlist secret + assert rig.app.form("fake").fields[0].value == "Other unit" + + +def test_the_deploy_apps_as_listed(rig: Rig) -> None: + rig.connected() + rig.app.paste_settings(OTHER, NOW) + + listed = rig.app.connections(NOW.replace(hour=13, minute=55)) + + assert listed == [ + app.DeployApp( + "unit.example.fi", + app.Banner( + app.Level.CLOSING, + "Deploy App unit.example.fi accepts phones until 14:00, 5 minutes from now", + "enrolment open until 14:00, 5 minutes left", + ), + False, + ), + app.DeployApp( + "other.example.fi", + app.Banner( + app.Level.OPEN, "Deploy App other.example.fi accepts phones until 15:30", "enrolment open until 15:30" + ), + True, + ), + ] + + +def test_reading_a_line_takes_nothing_from_it(rig: Rig) -> None: + rig.connected() + before = (rig.app.saved, rig.app.window, rig.app.status) + + known = rig.app.read_settings(LINE, NOW) + new = rig.app.read_settings(OTHER, NOW) + + assert known == app.Reading("unit.example.fi", "Deploy App unit.example.fi accepts phones until 14:00.", True) + assert new == app.Reading("other.example.fi", "Deploy App other.example.fi accepts phones until 15:30.", False) + assert (rig.app.saved, rig.app.window, rig.app.status) == before + with pytest.raises(app.AppError, match="This is not a settings line"): + rig.app.read_settings("ODMDM1", NOW) + + +def test_opening_a_deploy_app_without_its_token_says_so(rig: Rig) -> None: + rig.connected() + rig.app.paste_settings(OTHER, NOW) + rig.app.close() + rig.app = rig.start() + + said = rig.app.open("unit.example.fi", NOW) + + assert said == ( + "Deploy App unit.example.fi accepts phones until 14:00. " + "Type the Password again to connect: it is kept only while the connector runs." + ) + assert rig.app.mdm is None + assert rig.app.open("unit.example.fi", NOW) == said, "said again while it is not connected" + with pytest.raises(app.AppError, match="^There is no Deploy App nope.example.fi in this app.$"): + rig.app.open("nope.example.fi", NOW) + + +def test_removing_a_deploy_app_lets_go_of_its_token(rig: Rig) -> None: + rig.connected() + rig.app.paste_settings(OTHER, NOW) + rig.app.connect("fake", VALUES) + rig.settle() + + other = rig.app.remove("unit.example.fi") + kept = (rig.app.saved.active, rig.app.connected) + active = rig.app.remove("other.example.fi") + + assert other == "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + assert kept == ("other.example.fi", True) + assert active == "Deploy App other.example.fi is removed from this app, and its MDM token from this computer." + assert (rig.app.saved, rig.app.mdm, rig.app.window) == (store.Saved(), None, None) + assert rig.app.banner(NOW).level is app.Level.NONE + with pytest.raises(app.AppError, match="^There is no Deploy App unit.example.fi in this app.$"): + rig.app.remove("unit.example.fi") + rig.app.paste_settings(LINE, NOW) + assert rig.app.form("fake").fields[1].value == "", "added again, its token is typed again" + + +def test_a_deploy_app_whose_plugin_is_gone_is_removed(rig: Rig) -> None: + rig.app.paste_settings(LINE, NOW) + rig.app.approve("demo") + rig.app.connect("demo", VALUES) + rig.settle() + rig.app.paste_settings(OTHER, NOW) + rig.refused = "The MDM demo cannot be loaded" + + said = rig.app.remove("unit.example.fi") + + assert said == "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + assert list(rig.app.saved.connections) == ["other.example.fi"] + assert rig.app.remove("other.example.fi") == "Deploy App other.example.fi is removed from this app.", ( + "no MDM, no token" + ) + + +def test_a_result_for_a_deploy_app_no_longer_active_changes_nothing(rig: Rig) -> None: + rig.app.paste_settings(LINE, NOW) + rig.app.keep_callsigns("", ["BEAR1"]) + rig.connected() + rig.app.name(rig.app.preview(["a1"], ["BEAR1"], NOW).names) + rig.app.refresh() + rig.app.paste_settings(OTHER, NOW) + + rig.settle() + + assert (rig.app.phones, rig.app.status) == ([], "1 phone named.") + assert rig.app.saved.connections["unit.example.fi"].callsigns == ["BEAR1"] + + +def test_callsigns_are_kept_only_for_a_deploy_app(rig: Rig) -> None: + with pytest.raises( + app.AppError, match="^Add the Deploy App first: on its MDM page, press Open in the MDM connector.$" + ): + rig.app.keep_callsigns("BEAR", ["BEAR1"]) + + +def test_a_new_window_gives_the_mdm_its_challenge(rig: Rig) -> None: + fake = rig.connected() + + said = rig.app.paste_settings(LINE, NOW + datetime.timedelta(minutes=55)) + [result] = rig.settle() + + assert said == "Deploy App unit.example.fi accepts phones until 14:00. Giving the MDM the new challenge." + assert (result.job, fake.challenge, rig.app.status) == ( + app.Job.CHALLENGE, + CHALLENGE, + "Fake MDM has the new challenge.", + ) + assert (rig.app.challenge_note(), rig.app.challenge()) == ("", "") + + +def test_a_plugin_is_approved_before_it_is_imported(rig: Rig) -> None: + """Asked again when its package's version changes; only the chosen one is ever imported""" + asked = rig.app.approval("demo") + with pytest.raises(app.AppError, match="The MDM demo is a plugin that has not been approved in this app."): + rig.app.form("demo") + rig.app.approve("demo") + rig.app.form("demo") + rig.versions["demo"] = "1.0.1" + + assert asked == ( + "The MDM demo comes from the package odmdm-connector-demo 1.0.0, not with this app. " + "A plugin is code that sees the MDM token: use it only if you trust where it comes from." + ) + assert rig.app.approval("fake") == "" + assert rig.app.approval("demo").startswith("The MDM demo comes from the package odmdm-connector-demo 1.0.1") + assert rig.loaded == ["demo"] + assert rig.start().saved.approved == ["demo odmdm-connector-demo 1.0.0"] + rig.app.approve("demo") + assert rig.app.saved.approved == ["demo odmdm-connector-demo 1.0.1"] + with pytest.raises(app.AppError, match="No MDM named nope is installed."): + rig.app.approval("nope") + + +def test_an_mdm_set_up_but_given_the_challenge_by_hand_says_so(rig: Rig) -> None: + rig.classes["demo"] = FakeMdm.lacking(SET_CHALLENGE) + rig.app.paste_settings(LINE, NOW) + rig.app.approve("demo") + rig.app.connect("demo", VALUES) + rig.settle() + + assert rig.app.status == "Do the steps by hand to finish setting Fake MDM up for Deploy App unit.example.fi." + + +def test_an_mdm_lacking_everything_says_so_and_shows_the_challenge_only_to_be_copied(rig: Rig) -> None: + rig.app.paste_settings(LINE, NOW) + rig.app.approve("demo") + rig.app.connect("demo", VALUES) + [result] = rig.settle() + status = rig.app.status + said = rig.app.paste_settings(LINE, NOW) + + assert result.steps == (Step("The fake MDM cannot setup", False),) + assert status == "Do the steps by hand to finish setting Fake MDM up for Deploy App unit.example.fi." + assert said == "Deploy App unit.example.fi accepts phones until 14:00." + assert rig.app.challenge_note() == "The fake MDM cannot set_challenge" + assert rig.app.challenge() == CHALLENGE + assert not rig.app.busy() + with pytest.raises(app.AppError, match="The fake MDM cannot ask_again"): + rig.app.ask_again([]) + + +@pytest.mark.parametrize( + ("now", "level", "text", "short"), + [ + (NOW, app.Level.OPEN, "Deploy App unit.example.fi accepts phones until 14:00", "enrolment open until 14:00"), + ( + NOW.astimezone(datetime.timezone(datetime.timedelta(hours=2))), + app.Level.OPEN, + "Deploy App unit.example.fi accepts phones until 16:00", + "enrolment open until 16:00", + ), + ( + NOW.replace(hour=13, minute=50), + app.Level.CLOSING, + "Deploy App unit.example.fi accepts phones until 14:00, 10 minutes from now", + "enrolment open until 14:00, 10 minutes left", + ), + ( + NOW.replace(hour=13, minute=59, second=30), + app.Level.CLOSING, + "Deploy App unit.example.fi accepts phones until 14:00, 1 minute from now", + "enrolment open until 14:00, 1 minute left", + ), + ( + NOW.replace(hour=14), + app.Level.CLOSED, + ( + "Enrolment closed at 14:00. Open enrolment again on the MDM page of Deploy App, " + "then press Open in the MDM connector there." + ), + "enrolment closed at 14:00", + ), + ], +) +def test_the_banner_follows_the_window( + rig: Rig, now: datetime.datetime, level: app.Level, text: str, short: str +) -> None: + before = rig.app.banner(NOW) + rig.app.paste_settings(LINE, NOW) + + assert before == app.Banner( + app.Level.NONE, + "On the MDM page of Deploy App, press Open in the MDM connector to let phones enrol.", + "no enrolment window known", + ) + assert rig.app.banner(now) == app.Banner(level, text, short) + + +def test_the_phones_are_counted_by_where_they_are(rig: Rig) -> None: + assert rig.app.summary() == "" + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + rig.app.refresh() + assert rig.app.summary() == "", "nothing is said of the phones before they are listed" + rig.settle() + fake = rig.app.mdm + assert isinstance(fake, FakeMdm) + assert rig.app.summary() == "3 phones: 1 ready, 2 without a name" + + fake.group = [ + *PHONES, + replace(PHONES[2], id="a4", state=State.REFUSED), + replace(PHONES[2], id="a5", state=State.WAITING), + replace(PHONES[0], id="a6", state=State.REFUSED), + ] + rig.app.refresh() + rig.settle() + assert rig.app.summary() == "6 phones: 1 ready, 1 waiting for the phone, 1 failed, 3 without a name" + + fake.group = [PHONES[0]] + rig.app.refresh() + rig.settle() + assert rig.app.summary() == "1 phone: 1 without a name" + + fake.group = [] + rig.app.refresh() + rig.settle() + assert rig.app.summary() == "No phones yet." + + +def test_a_listing_that_failed_is_not_no_phones(rig: Rig) -> None: + rig.classes["fake"] = Broken + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + rig.app.refresh() + rig.settle() + + assert rig.app.summary() == "", "the MDM never listed its phones, so none is not said" + + +def test_after_a_restart_the_app_says_why_the_token_is_asked_for(rig: Rig) -> None: + rig.connected() + rig.app.close() + rig.app = rig.start() + typed = "Type the Password again to connect: it is kept only while the connector runs." + + first = rig.app.status + pasted = rig.app.paste_settings(LINE, NOW) + + assert (first, rig.app.mdm) == (typed, None) + assert pasted == f"Deploy App unit.example.fi accepts phones until 14:00. {typed}" + + +def test_after_a_restart_an_mdm_without_a_secret_is_connected_at_once(rig: Rig) -> None: + class NoSecret(FakeMdm): + fields: ClassVar = FakeMdm.fields[:1] + + rig.classes["fake"] = NoSecret + rig.connected() + rig.app.close() + rig.app = rig.start() + + assert (rig.app.status, rig.app.connected) == ("", True) + + +def test_several_secrets_not_at_hand_are_all_named(rig: Rig) -> None: + class TwoSecrets(FakeMdm): + fields: ClassVar = (*FakeMdm.fields, Field("pin", "PIN", secret=True)) + + rig.classes["fake"] = TwoSecrets + rig.connected(values={**VALUES, "pin": "1234"}) + rig.app.paste_settings(OTHER, NOW) + rig.app.close() + rig.app = rig.start() + + rig.app.open("unit.example.fi", NOW) + + assert rig.app.status.endswith( + "Type the Password and PIN again to connect: they are kept only while the connector runs." + ) + + +def test_the_table(rig: Rig) -> None: + fake = rig.connected() + fake.group = [*PHONES[:2], replace(PHONES[2], state=State.REFUSED, detail="name taken")] + rig.app.refresh() + rig.settle() + + rows = rig.app.rows(NOW.astimezone(datetime.timezone(datetime.timedelta(hours=2)))) + + assert rows == [ + app.Row("a1", "", "Pretend Phone 7", "2026-11-01 11:00", "waiting for a name", True, False, False, False), + app.Row("a2", "", "Pretend Phone 7", "2026-11-01 11:05", "waiting for a name", True, False, False, False), + app.Row( + "a3", + "OTTER1", + "Pretend Tablet 2", + "2026-11-01 11:10", + "refused by Deploy App: name taken", + False, + True, + False, + True, + ), + ] + + +def test_a_batch_numbered_on_from_the_callsigns_in_use(rig: Rig) -> None: + fake = rig.connected() + ids = rig.app.targets([]) + callsigns = rig.app.numbered("OTTER", rig.app.first_number("otter"), len(ids)) + + preview = rig.app.preview(ids, callsigns, NOW) + said = rig.app.name(preview.names) + results = rig.settle() + + assert (ids, callsigns) == (["a1", "a2"], ["OTTER2", "OTTER3"]) + assert (preview.ok, preview.button, preview.warning) == (True, "Name 2 phones", "") + assert [(row.phone, row.joined, row.callsign, row.refusal) for row in preview.rows] == [ + ("Pretend Phone 7", "2026-11-01 09:00", "OTTER2", ""), + ("Pretend Phone 7", "2026-11-01 09:05", "OTTER3", ""), + ] + assert said == "Naming 2 phones." + assert [result.job for result in results] == [app.Job.NAME] + assert (rig.app.status, rig.app.lines) == ("2 phones named.", ("Phone a1 is OTTER2", "Phone a2 is OTTER3")) + rig.settle() + assert rig.app.lines, "the lines stay while the phones are listed again" + assert [row.callsign for row in rig.app.rows(NOW)] == ["OTTER2", "OTTER3", "OTTER1"] + assert fake.calls[-3:] == ["phones", "name", "phones"] + + +def test_the_list_is_kept_and_used_up(rig: Rig) -> None: + """Typed and saved before any phone joined; what was given is gone from it next time""" + rig.app.paste_settings(LINE, NOW) + rig.app.keep_callsigns("BEAR", rig.app.listed("BEAR7\n\n BEAR9 \nBEAR11\n")) + rig.connected() + + preview = rig.app.preview(["a2"], rig.app.conn.callsigns, NOW) + rig.app.name(preview.names) + rig.settle() + + assert rig.start().conn.callsigns == ["BEAR9", "BEAR11"] + assert rig.app.conn.prefix == "BEAR" + + +@pytest.mark.parametrize( + ("ids", "callsigns", "refusals", "batch"), + [ + (["a1", "a2"], ["BEAR1"], ["", "no callsign left in the list"], "2 phones to name, but only 1 callsign."), + (["a1", "a2"], ["BEAR1", "bear1"], ["", "bear1 is given twice"], ""), + (["a1", "a1"], ["BEAR1", "BEAR2"], ["", "phone a1 is named twice"], ""), + (["a1"], ["otter1"], ["otter1 already belongs to phone a3"], ""), + (["a1", "zz"], ["-BEAR", "BEAR2"], ["-BEAR: a callsign is 3-32", "phone zz is not in the group"], ""), + ([], ["BEAR1"], [], "No phone is waiting for a name. To give a phone another callsign, select it first."), + ], +) +def test_every_refusal_is_said_and_stops_the_naming( + rig: Rig, ids: list[str], callsigns: list[str], refusals: list[str], batch: str +) -> None: + rig.connected() + + preview = rig.app.preview(ids, callsigns, NOW) + + assert [row.refusal[: len(said)] for row, said in zip(preview.rows, refusals, strict=True)] == refusals + assert (preview.refusal, preview.ok) == (batch, False) + with pytest.raises( + app.AppError, match="Preview the callsigns first: nothing is named without a preview that passed." + ): + rig.app.name(dict(zip(ids, callsigns, strict=False))) + + +def test_only_the_names_previewed_are_given(rig: Rig) -> None: + rig.connected() + rig.app.preview(["a1"], ["BEAR1"], NOW) + + with pytest.raises(app.AppError, match="Preview the callsigns first"): + rig.app.name({"a1": "BEAR2"}) + rig.app.name({"a1": "BEAR1"}) + with pytest.raises(app.AppError, match="Preview the callsigns first"): + rig.app.name({"a1": "BEAR1"}) + + +def test_a_phone_that_just_joined_is_warned_of(rig: Rig) -> None: + fake = rig.connected() + just = (NOW - datetime.timedelta(minutes=4)).isoformat() + fake.group = [replace(phone, joined=just) for phone in PHONES] + rig.app.refresh() + rig.settle() + + one = rig.app.preview(["a1"], ["BEAR1"], NOW) + fake.group = [*PHONES[:2], replace(PHONES[2], joined=just)] + rig.app.refresh() + rig.settle() + single = rig.app.preview(["a1"], ["BEAR1"], NOW) + + assert one.warning == ( + "3 phones joined less than 10 minutes ago and may still be installing their apps. Naming now sends the " + "policy to every phone again, which stops apps that are still installing: wait until they have their apps." + ) + assert single.warning == ( + "A phone joined less than 10 minutes ago and may still be installing its apps. Naming now sends the " + "policy to every phone again, which stops apps that are still installing: wait until it has its apps." + ) + assert single.ok + + +def test_phones_changed_since_the_preview_name_nothing(rig: Rig) -> None: + fake = rig.connected() + preview = rig.app.preview(["a1"], ["BEAR1"], NOW) + fake.group = [replace(PHONES[1], callsign="BEAR1"), *PHONES[::2]] + + rig.app.name(preview.names) + [result] = rig.settle() + + assert result.error == "Nothing named: BEAR1 already belongs to phone a2. Refresh and give callsigns again." + assert "name" not in fake.calls + + +class Refusing(FakeMdm): + """Refuses after the first phone, as an MDM failing half-way does""" + + def __init__(self, values: Mapping[str, str]) -> None: + super().__init__(values, refuse_after=1) + + +def test_a_batch_stopped_half_way_says_what_it_named(rig: Rig) -> None: + rig.classes["fake"] = Refusing + rig.app.paste_settings(LINE, NOW) + rig.app.keep_callsigns("", ["BEAR1", "BEAR2", "BEAR3"]) + rig.connected() + + rig.app.name(rig.app.preview(["a1", "a2"], ["BEAR1", "BEAR2"], NOW).names) + [result] = rig.settle() + + assert result.named == {"a1": "BEAR1"} + assert rig.app.status == "The fake MDM refused phone a2 Named before it stopped: a1 as BEAR1." + assert rig.app.lines == ("Phone a1 is BEAR1",) + assert rig.app.conn.callsigns == ["BEAR2", "BEAR3"] + + +def test_the_lines_go_once_anything_else_is_said(rig: Rig) -> None: + rig.connected() + rig.app.name(rig.app.preview(["a1"], ["BEAR1"], NOW).names) + rig.settle() + assert rig.app.lines == ("Phone a1 is BEAR1",) + + rig.app.paste_settings(LINE, NOW) + + assert not rig.app.lines + + +def test_asking_again(rig: Rig) -> None: + fake = rig.connected() + fake.group[2] = replace(fake.group[2], state=State.REFUSED) + rig.app.refresh() + rig.settle() + + rig.app.ask_again(["a3"]) + rig.settle() + first = (rig.app.status, rig.app.lines) + said = rig.app.ask_again([]) + rig.settle() + + assert first == ("Asked again.", ("Phone a3: certificate asked for again",)) + assert said == "Asking every named phone whose certificate failed again." + assert (rig.app.status, rig.app.lines) == ("No phone needed asking again.", ()) + assert "ask_again" in fake.calls + + +def test_a_phone_with_its_certificate_is_not_asked_again(rig: Rig) -> None: + fake = rig.connected() + calls = len(fake.calls) + + with pytest.raises( + app.AppError, + match="Nothing to ask again: the selected phones have their certificates, or have no callsign yet.", + ): + rig.app.ask_again(["a3"]) + + assert len(fake.calls) == calls + assert not rig.app.detail("a3", NOW).can_ask_again + + +def test_a_phone_without_a_callsign_is_not_asked_again(rig: Rig) -> None: + fake = rig.connected() + fake.group[0] = replace(fake.group[0], state=State.FAILED) + rig.app.refresh() + rig.settle() + + with pytest.raises(app.AppError, match="Nothing to ask again"): + rig.app.ask_again(["a1"]) + + assert not rig.app.detail("a1", NOW).can_ask_again + + +def test_a_mixed_selection_asks_only_the_failed_again(rig: Rig) -> None: + fake = rig.connected() + fake.group[2] = replace(fake.group[2], state=State.WAITING) + rig.app.refresh() + rig.settle() + + said = rig.app.ask_again(["a1", "a2", "a3"]) + rig.settle() + + assert said == "Asking 1 phone again; 2 phones left alone." + assert rig.app.detail("a3", NOW).can_ask_again + assert (rig.app.status, rig.app.lines) == ("Asked again.", ("Phone a3: certificate asked for again",)) + + +class Broken(FakeMdm): + """Fails the way no MDM is meant to""" + + failure: ClassVar[type[Exception]] = RuntimeError + + def phones(self) -> list[Phone]: + raise self.failure("the token is pa55word") + + def ask_again(self, ids: Sequence[str]) -> list[str]: + return ["Asked"] + + +class Unreachable(Broken): + failure = ConnectionRefusedError + + +@pytest.mark.parametrize( + ("broken", "says"), + [(Unreachable, "Cannot reach the MDM."), (Broken, "The MDM plugin failed; the log says more: ")], +) +def test_any_failure_is_one_sentence_and_the_worker_goes_on(rig: Rig, broken: type[FakeMdm], says: str) -> None: + rig.classes["fake"] = broken + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + rig.settle() + + rig.app.refresh() + [result] = rig.settle() + rig.app.ask_again([]) + rig.settle() + + assert result.error.startswith(says) + assert "Traceback" not in result.error + assert (rig.app.status, rig.app.lines) == ("Asked again.", ("Asked",)) + + +def test_a_settings_file_that_cannot_be_written_is_said(rig: Rig) -> None: + rig.app.store = store.Store(rig.directory / "settings.json" / "not-a-directory") + rig.directory.mkdir() + (rig.directory / "settings.json").write_text("{}", encoding="utf-8") + + with pytest.raises(app.AppError, match="cannot be written"): + rig.app.paste_settings(LINE, NOW) + assert rig.app.window is None + + +def test_a_listing_of_the_plugins_that_failed_is_said(rig: Rig) -> None: + rig.unlisted = plugins.PluginError("Two packages declare the MDM demo") + with pytest.raises(app.AppError, match="Two packages declare the MDM demo"): + rig.app.mdms() + + +def test_a_phones_detail(rig: Rig) -> None: + fake = rig.connected() + fake.group = [replace(PHONES[0], callsign="OTTER2", state=State.FAILED, detail="Fleet's own words")] + rig.app.refresh() + rig.settle() + + detail = rig.app.detail("a1", NOW) + + assert detail == app.Detail( + "a1", + "OTTER2", + "Pretend Phone 7", + "2026-11-01 09:00", + "failed", + "Fleet's own words", + "Deploy App unit.example.fi accepts phones until 14:00", + True, + ) + with pytest.raises(app.AppError, match="Phone zz is no longer in the MDM's list: refresh."): + rig.app.detail("zz", NOW) + + +def test_the_log_holds_no_secret(tmp_path: Path) -> None: + redact = app.Redact() + path = app.open_log(tmp_path / "logs", redact) + redact.add(CHALLENGE) + redact.add("") + try: + logging.getLogger("odmdm_connector.test").info("pasted %s", CHALLENGE) + try: + raise RuntimeError(f"challenge {CHALLENGE}") + except RuntimeError: + logging.getLogger("odmdm_connector.test").exception("failed") + finally: + handlers = [ + handler for handler in logging.getLogger().handlers if getattr(handler, "formatter", None) is redact + ] + for handler in handlers: + logging.getLogger().removeHandler(handler) + handler.close() + + text = path.read_text(encoding="utf-8") + assert CHALLENGE not in text + assert text.count("[secret]") == 2 + + +class Echoing(FakeMdm): + """An MDM whose answers repeat the secrets it was given""" + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step(f"Signed in with {self.values['password']}", True, f"challenge {window.challenge}") + raise MdmError(f"Refused {window.challenge} for {self.values['password']}") + + def set_challenge(self, window: Settings) -> None: + raise MdmError(f"Bad challenge {window.challenge}", lines=[f"password {self.values['password']}"]) + + def ask_again(self, ids: Sequence[str]) -> list[str]: + return [f"Asked with {self.values['password']}"] + + +def test_no_secret_reaches_the_operator_or_the_log(rig: Rig, tmp_path: Path) -> None: + rig.classes["fake"] = Echoing + terminal = io.StringIO() + stderr = logging.StreamHandler(terminal) + logging.getLogger().addHandler(stderr) + redact = app.Redact() + path = app.open_log(tmp_path / "logs", redact) + rig.app.redact = redact + try: + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + results = rig.settle() + statuses = [rig.app.status] + rig.app.paste_settings(LINE, NOW) + results += rig.settle() + statuses.append(rig.app.status) + rig.app.ask_again([]) + rig.settle() + finally: + for handler in [stderr, *(each for each in logging.getLogger().handlers if each.formatter is redact)]: + logging.getLogger().removeHandler(handler) + handler.close() + + shown = [ + *statuses, + *(result.error for result in results), + *(line for result in results for line in result.lines), + *(part for result in results for step in result.steps for part in (step.label, step.message)), + ] + assert statuses == ["Refused [secret] for [secret]", "Bad challenge [secret]"] + assert [step.label for result in results for step in result.steps] == ["Signed in with [secret]"] + for text in [*shown, path.read_text(encoding="utf-8"), terminal.getvalue()]: + assert CHALLENGE not in text + assert VALUES["password"] not in text + assert "[secret]" in terminal.getvalue() + assert rig.app.lines == ("Asked with [secret]",) + + +def test_the_app_on_this_computer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Its settings file and log in one directory, here a temporary one, and the system's keychain""" + backend = MemoryBackend() + monkeypatch.setattr(store, "directory", lambda: tmp_path) + monkeypatch.setattr(store, "platform_backend", lambda: backend) + before = list(logging.getLogger().handlers) + + started = app.App.default() + try: + assert started.log_path == tmp_path / "odmdm-connector.log" + assert started.store.path == tmp_path / "settings.json" + assert (started.keychain.backend, started.keeps) == (backend, True) + finally: + started.close() + for handler in set(logging.getLogger().handlers) - set(before): + logging.getLogger().removeHandler(handler) + handler.close() + + +class HalfSetUp(FakeMdm): + """Stops its setup after the first step""" + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step("Group found", True) + raise MdmError("The fake MDM refused the template") + + +def test_a_setup_that_stops_shows_the_steps_done(rig: Rig) -> None: + rig.classes["fake"] = HalfSetUp + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + + [result] = rig.settle() + + assert (result.steps, result.error) == ((Step("Group found", True),), "The fake MDM refused the template") + assert rig.app.status == "The fake MDM refused the template" + + +class Unconfigurable(FakeMdm): + def __init__(self, values: Mapping[str, str]) -> None: + raise MdmError("The fake MDM needs a group") + + +def test_a_plugin_that_cannot_be_used_is_said(rig: Rig) -> None: + rig.connected() + rig.classes["fake"] = Unconfigurable + + with pytest.raises(app.AppError, match="The fake MDM needs a group"): + rig.app.connect("fake", VALUES) + later = rig.start() + with pytest.raises(app.AppError, match="The fake MDM needs a group"): + later.connect("fake", VALUES) + rig.refused = "The MDM fake cannot be loaded" + + assert later.mdm is None + with pytest.raises(app.AppError, match="The MDM fake cannot be loaded"): + rig.start().form("fake") + later.close() + + +def test_nothing_reaches_the_mdm_before_it_is_connected(rig: Rig) -> None: + rig.app.refresh() + + with pytest.raises(app.AppError, match="Connect to the MDM first."): + rig.app.name({}) + with pytest.raises(app.AppError, match="Connect to the MDM first."): + rig.app.ask_again([]) + assert not rig.app.busy() + + +def test_one_listing_at_a_time(rig: Rig) -> None: + """A refresh asked while one is under way is not queued behind it""" + fake = rig.connected() + fake.calls.clear() + + rig.app.refresh() + rig.app.refresh() + rig.settle() + + assert fake.calls == ["phones"] + + +def test_a_time_that_is_not_one_is_shown_as_it_is(rig: Rig) -> None: + fake = rig.connected() + fake.group = [replace(PHONES[0], joined="yesterday"), replace(PHONES[1], joined="2026-11-01T09:05:00")] + rig.app.refresh() + rig.settle() + + assert [row.joined for row in rig.app.rows(NOW)] == ["yesterday", "2026-11-01 09:05"] + assert not rig.app.preview(["a1"], ["BEAR1"], NOW).warning + + +class Expired(FakeMdm): + """Does not accept its password, as an MDM does once a token has ended""" + + def phones(self) -> list[Phone]: + raise MdmError("The fake MDM does not accept the password", unauthorized=True) + + +def test_a_secret_the_mdm_does_not_accept_is_typed_again(rig: Rig) -> None: + rig.connected() + rig.classes["fake"] = Expired + rig.app.connect("fake", VALUES) + rig.settle() + + rig.app.refresh() + [result] = rig.settle() + + assert result.unauthorized + assert (rig.app.connected, rig.app.phones, rig.app.summary()) == (False, [], "") + assert rig.app.status == "The fake MDM does not accept the password" + assert rig.app.form("fake").fields[1].value == "" + assert rig.app.connect("fake", VALUES) == "Setting Fake MDM up for Deploy App unit.example.fi." + + +def test_a_refusal_of_an_mdm_no_longer_held_lets_go_of_nothing(rig: Rig) -> None: + """The token was typed again while a listing with the old one was under way""" + rig.connected() + rig.classes["fake"] = Expired + rig.app.connect("fake", VALUES) + rig.settle() + rig.app.refresh() + rig.classes["fake"] = FakeMdm + rig.app.connect("fake", VALUES) + + rig.settle() + + assert rig.app.connected + assert rig.app.form("fake").fields[1].value == "pa55word" + + +@pytest.mark.parametrize("sender", ["", "https://unit.example.fi", "https://mtls.unit.example.fi"]) +def test_a_line_is_taken_from_its_own_deploy_app(rig: Rig, sender: str) -> None: + """Or typed by hand, which names no sender""" + assert rig.app.read_settings(LINE, NOW, sender).host == "unit.example.fi" + assert rig.app.paste_settings(LINE, NOW, sender) == "Deploy App unit.example.fi accepts phones until 14:00." + + +@pytest.mark.parametrize( + "sender", + [ + "https://other.example.fi", + "http://mtls.unit.example.fi", + "https://mtls.unit.example.fi:8443", + "https://evil.example.fi.unit.example.fi", + "https://unit.example.fi.evil.example", + "null", + ], +) +def test_a_line_sent_by_another_page_is_refused(rig: Rig, sender: str) -> None: + says = ( + f"These settings are for Deploy App unit.example.fi, but the page that sent them is {sender}: " + "use the button on that Deploy App's own MDM page." + ) + + for take in (rig.app.read_settings, rig.app.paste_settings): + with pytest.raises(app.AppError) as raised: + take(LINE, NOW, sender) + assert str(raised.value) == says + assert (rig.app.window, rig.app.saved) == (None, store.Saved()) + + +def test_a_remembered_token_connects_at_the_next_start(keyed: Rig) -> None: + assert keyed.app.keeps + keyed.connected() + keyed.app.paste_settings(OTHER, NOW) + keyed.app.connect("fake", {"group": "Other unit", "password": "0ther"}) # pragma: allowlist secret + keyed.settle() + assert keyed.backend is not None and keyed.backend.items[KEPT] == VALUES["password"] + keyed.app.close() + + keyed.app = keyed.start() + at_start = (keyed.app.status, keyed.app.connected) + opened = keyed.app.open("unit.example.fi", NOW) + + assert at_start == ("", True) + assert opened == "Deploy App unit.example.fi accepts phones until 14:00." + assert isinstance(keyed.app.mdm, FakeMdm) and keyed.app.mdm.values == VALUES + assert keyed.app.form("fake").fields[1].value == VALUES["password"] + keyed.app.close() + keyed.app = keyed.start() + assert keyed.app.paste_settings(LINE, NOW).endswith("Giving the MDM the new challenge."), "connected, no typing" + + +def test_the_keychain_is_read_once_until_the_token_changes(keyed: Rig, monkeypatch: pytest.MonkeyPatch) -> None: + """A keychain may ask the operator before it answers, and every request would wait for that""" + keyed.connected() + keyed.app.close() + backend = keyed.backend + assert backend is not None + reads: list[str] = [] + read = backend.get_password + + def counted(service: str, account: str) -> str | None: + reads.append(account) + return read(service, account) + + monkeypatch.setattr(backend, "get_password", counted) + keyed.app = keyed.start() + for _ in range(3): + assert [each.remembered for each in keyed.app.form("fake").fields] == [False, True] + keyed.app.banner(NOW) + assert reads == ["unit.example.fi:fake:password"] + + keyed.app.connect("fake", VALUES, remember=False) + keyed.settle() + reads.clear() + assert [[each.remembered for each in keyed.app.form("fake").fields] for _ in range(2)] == [[False, False]] * 2 + assert reads == ["unit.example.fi:fake:password"], "read once more after connecting" + + +def test_a_token_not_remembered_is_removed_from_the_keychain(keyed: Rig) -> None: + keyed.connected() + + said = keyed.app.connect("fake", VALUES, remember=False) + + assert keyed.backend is not None and keyed.backend.items == {} + assert said == "Setting Fake MDM up for Deploy App unit.example.fi." + assert keyed.app.connected, "held until the connector stops" + keyed.app.close() + keyed.app = keyed.start() + assert (keyed.app.status, keyed.app.connected) == ( + "Type the Password again to connect: it is not kept on this computer.", + False, + ) + + +def test_a_keychain_that_does_not_take_the_token_is_said(keyed: Rig) -> None: + assert keyed.backend is not None + keyed.backend.broken = True + keyed.app.paste_settings(LINE, NOW) + + said = keyed.app.connect("fake", VALUES) + + assert said == ( + "This computer's keychain cannot be used, so the Password is kept only until the connector stops. " + "Setting Fake MDM up for Deploy App unit.example.fi." + ) + # The page shows the line while the setup runs, beside a heading that already says what the sentence does + assert (keyed.app.status, keyed.app.lines) == ( + "Setting Fake MDM up for Deploy App unit.example.fi.", + ("This computer's keychain cannot be used, so the Password is kept only until the connector stops.",), + ) + assert keyed.app.connected + assert VALUES["password"] not in (keyed.directory / "settings.json").read_text(encoding="utf-8") + + +def test_a_token_the_mdm_does_not_accept_leaves_the_keychain(keyed: Rig) -> None: + keyed.connected() + keyed.classes["fake"] = Expired + keyed.app.connect("fake", VALUES) + keyed.settle() + + keyed.app.refresh() + keyed.settle() + + assert keyed.backend is not None and keyed.backend.items == {} + assert not keyed.app.connected + keyed.app.close() + keyed.app = keyed.start() + assert keyed.app.status == "Type the Password again to connect: it is not kept on this computer." + + +def test_removing_a_deploy_app_removes_its_kept_token(keyed: Rig) -> None: + keyed.connected() + + said = keyed.app.remove("unit.example.fi") + + assert said == "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + assert keyed.backend is not None and keyed.backend.items == {} + + +@pytest.mark.parametrize("why", ["undeletable", "plugin gone"]) +def test_a_kept_token_that_cannot_be_removed_is_said(keyed: Rig, why: str) -> None: + keyed.connected() + assert keyed.backend is not None + if why == "undeletable": + keyed.backend.undeletable = True + else: + keyed.refused = "The MDM fake cannot be loaded" + + said = keyed.app.remove("unit.example.fi") + + assert said == ( + "Deploy App unit.example.fi is removed from this app, but its MDM token may still be in this computer's " + "keychain: delete the odmdm-connector item of unit.example.fi there by hand." + ) + assert keyed.app.saved == store.Saved() + + +def test_without_keyring_the_app_holds_the_token_for_the_session(rig: Rig, monkeypatch: pytest.MonkeyPatch) -> None: + """As in the one-file build, which leaves keyring out""" + monkeypatch.setitem(sys.modules, "keyring", None) + + def start() -> app.App: + keychain = store.Keychain(store.platform_backend()) + return app.App(store.Store(rig.directory), installed=rig.installed, load=rig.load, keychain=keychain) + + rig.app.close() + rig.app = start() + assert not rig.app.keeps + assert rig.connected().values == VALUES + rig.app.close() + rig.app = start() + assert (rig.app.status, rig.app.connected) == ( + "Type the Password again to connect: it is kept only while the connector runs.", + False, + ) + + +def test_a_setup_shows_its_steps_as_they_are_done(rig: Rig) -> None: + """A setup can take minutes, so each step is there to tick as soon as it is done, secrets blanked out""" + go = threading.Event() + + class Slow(FakeMdm): + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step("Group found", True, f"with {self.values['password']}") + go.wait(5) + yield Step("Certificate template stated", True) + + rig.classes["fake"] = Slow + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + for _ in range(500): + if rig.app.progress: + break + time.sleep(0.01) + + assert rig.app.progress == (Step("Group found", True, "with [secret]"),) + go.set() + (result,) = rig.settle() + assert [step.label for step in result.steps] == ["Group found", "Certificate template stated"] + + go.clear() + rig.app.connect("fake", VALUES) + assert rig.app.progress in ((), (Step("Group found", True, "with [secret]"),)), "the last setup's steps are gone" + go.set() + rig.settle() + + +class Forced(FakeMdm): + """Records the window and force of every setup""" + + setups: ClassVar[list[tuple[Settings, bool]]] = [] + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + Forced.setups.append((window, force)) + return super().setup(window, force, dry_run) + + +def test_the_policy_is_sent_again_as_apply_force_policy_with_its_steps(keyed: Rig) -> None: + """A setup with force and no challenge, so a window pasted earlier never replaces a newer one""" + keyed.classes["fake"] = Forced + keyed.connected() + Forced.setups.clear() + + note = keyed.app.policy_note() + said = keyed.app.send_policy() + [result] = keyed.settle() + + assert note == ( + "For a phone whose browser refuses its certificate: the MDM sends the policy to every phone again. " + "Phones keep their certificates. Not while phones are still installing apps: it stops their installs." + ) + assert said == "Sending the policy again for Deploy App unit.example.fi." + assert Forced.setups == [(Settings("https://unit.example.fi/scep", ""), True)] + assert (result.job, result.error) == (app.Job.POLICY, "") + assert result.steps[-1] == Step("Certificate template stated", True, "forced") + assert keyed.app.status == "Fake MDM has sent the policy again to the phones of Deploy App unit.example.fi." + + # After a restart, with enrolment closed and no window pasted: the command line needs none either + keyed.app.close() + keyed.app = keyed.start() + keyed.app.send_policy() + keyed.settle() + assert Forced.setups[-1] == (Settings("https://unit.example.fi/scep", ""), True) + + +def test_the_policy_is_sent_again_one_job_at_a_time(keyed: Rig) -> None: + """Every send rewrites the policy: asked again while one waits or runs, or a setup does, nothing more is sent""" + keyed.classes["fake"] = Forced + keyed.connected() + Forced.setups.clear() + + first = keyed.app.send_policy() + second = keyed.app.send_policy() + keyed.settle() + + assert first == second == "Sending the policy again for Deploy App unit.example.fi." + assert Forced.setups == [(Settings("https://unit.example.fi/scep", ""), True)] + + keyed.app.paste_settings(LINE, NOW) + keyed.app.connect("fake", VALUES) + during_setup = keyed.app.send_policy() + keyed.settle() + + assert during_setup == "Sending the policy again for Deploy App unit.example.fi." + assert [force for _, force in Forced.setups] == [True, False], "the setup only, nothing forced beside it" + + +class PolicyRefused(FakeMdm): + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step("Group found", True) + if force: + raise MdmError("Fleet refused: the policy cannot be uploaded") + + +def test_a_policy_the_mdm_refuses_is_its_reason(rig: Rig) -> None: + rig.classes["fake"] = PolicyRefused + rig.connected() + + rig.app.send_policy() + [result] = rig.settle() + + assert (result.job, result.steps) == (app.Job.POLICY, (Step("Group found", True),)) + assert result.error == rig.app.status == "Fleet refused: the policy cannot be uploaded" + + +@pytest.mark.parametrize( + ("lacking", "says"), [(SEND_POLICY, "The fake MDM cannot send_policy"), (SETUP, "The fake MDM cannot setup")] +) +def test_the_policy_is_not_offered_by_an_mdm_that_cannot_send_it(rig: Rig, lacking: str, says: str) -> None: + with pytest.raises(app.AppError, match="^Connect to the MDM first.$"): + rig.app.send_policy() + assert rig.app.policy_note() == "" + rig.classes["fake"] = FakeMdm.lacking(lacking) + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + rig.settle() + + assert rig.app.policy_note() == "" + with pytest.raises(app.AppError, match=f"^{says}$"): + rig.app.send_policy() + assert not rig.app.busy() + + +#: The Fleet plugin's fields on the fake MDM: whatever reads them gets the team's default +FleetFields = type("FleetFields", (FakeMdm,), {"fields": FleetPlugin.fields}) +GOLDEN = LINE.replace("unit.example.fi", "golden-monkey.example.fi") + + +def test_the_team_suggested_is_named_after_the_deployment(rig: Rig) -> None: + rig.classes["fake"] = FleetFields + rig.app.paste_settings(GOLDEN, NOW) + + form = {each.field.key: each for each in rig.app.form("fake").fields} + rig.app.connect("fake", {"mdm_url": "https://mdm.example.fi", "token": "t0ken"}) # pragma: allowlist secret + rig.settle() + + assert (form["team"].value, form["team"].field.default) == ("golden-monkey DeployApp", "golden-monkey DeployApp") + assert form["key_alias"].value == "rmscep" + assert rig.app.saved.connections["golden-monkey.example.fi"].values["team"] == "golden-monkey DeployApp" + assert isinstance(rig.app.mdm, FakeMdm) and rig.app.mdm.values["team"] == "golden-monkey DeployApp" + + +def test_a_team_saved_or_typed_stays_as_it_is(rig: Rig) -> None: + rig.classes["fake"] = FleetFields + rig.app.paste_settings(GOLDEN, NOW) + rig.app.connect("fake", {"mdm_url": "https://mdm.example.fi", "token": "t0ken", "team": "Deploy App"}) + rig.settle() + + [team] = [each for each in rig.app.form("fake").fields if each.field.key == "team"] + + assert team.value == "Deploy App" + assert rig.app.saved.connections["golden-monkey.example.fi"].values["team"] == "Deploy App" + with pytest.raises(app.AppError, match="^Fill in Team.$"): + rig.app.connect("fake", {"mdm_url": "https://mdm.example.fi", "token": "t0ken", "team": " "}) diff --git a/tests/test_browser.py b/tests/test_browser.py new file mode 100644 index 0000000..daf8569 --- /dev/null +++ b/tests/test_browser.py @@ -0,0 +1,168 @@ +"""Opening the page in the default browser, with the opener replaced so that no test starts anything""" + +import html +import os +import stat +import sys +from pathlib import Path +from urllib.parse import urlparse +from urllib.request import url2pathname + +import pytest + +from odmdm_connector import browser + +KEY = "k3y-of_the.page" +ADDRESS = f"http://127.0.0.1:8737/#key={KEY}&x=<\"'>" + + +class Opener: + """The opener: what it was handed, and its answer or what it raises""" + + def __init__(self, answer: bool = True, raises: Exception | None = None) -> None: + self.answer, self.raises = answer, raises + self.handed: list[str] = [] + + def __call__(self, url: str, new: int = 0, autoraise: bool = True) -> bool: + self.handed.append(url) + if self.raises is not None: + raise self.raises + return self.answer + + +@pytest.fixture +def desktop(monkeypatch: pytest.MonkeyPatch) -> None: + """A Linux computer with a desktop""" + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setenv("DISPLAY", ":0") + monkeypatch.delenv("WAYLAND_DISPLAY", raising=False) + + +def _opener(monkeypatch: pytest.MonkeyPatch) -> Opener: + made = Opener() + monkeypatch.setattr("webbrowser.open", made) + return made + + +def test_the_opener_gets_a_file_that_leads_on_to_the_address( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None +) -> None: + opener = _opener(monkeypatch) + + assert browser.open_page(ADDRESS, tmp_path / "config") + + [handed] = opener.handed + assert KEY not in handed, "only the file's path reaches another program's arguments" + assert urlparse(handed).scheme == "file" + path = Path(url2pathname(urlparse(handed).path)) + assert path == tmp_path / "config" / browser.NAME + text = path.read_text(encoding="utf-8") + assert html.escape(ADDRESS, quote=True) in text + assert ADDRESS not in text, "escaped for HTML" + assert 'http-equiv="refresh"' in text + assert " None: + _opener(monkeypatch) + + browser.open_page(ADDRESS, tmp_path) + + assert stat.S_IMODE((tmp_path / browser.NAME).stat().st_mode) == 0o600 + + +def test_a_file_left_from_an_earlier_start_is_replaced( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None +) -> None: + left = tmp_path / browser.NAME + left.write_text("the earlier key", encoding="utf-8") + if os.name == "posix": + left.chmod(0o644) + _opener(monkeypatch) + + assert browser.open_page(ADDRESS, tmp_path) + + assert "the earlier key" not in left.read_text(encoding="utf-8") + if os.name == "posix": + assert stat.S_IMODE(left.stat().st_mode) == 0o600 + + +@pytest.mark.parametrize("display", ["DISPLAY", "WAYLAND_DISPLAY"]) +def test_either_display_is_a_desktop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None, display: str +) -> None: + monkeypatch.delenv("DISPLAY") + monkeypatch.setenv(display, "wayland-0") + opener = _opener(monkeypatch) + + assert browser.open_page(ADDRESS, tmp_path) + assert len(opener.handed) == 1 + + +def test_without_a_desktop_nothing_is_written_or_opened( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None +) -> None: + monkeypatch.delenv("DISPLAY") + opener = _opener(monkeypatch) + + assert not browser.open_page(ADDRESS, tmp_path) + assert opener.handed == [] + assert list(tmp_path.iterdir()) == [] + + +@pytest.mark.parametrize("platform", ["win32", "darwin"]) +def test_windows_and_macos_always_have_a_desktop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, platform: str +) -> None: + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.delenv("DISPLAY", raising=False) + monkeypatch.delenv("WAYLAND_DISPLAY", raising=False) + opener = _opener(monkeypatch) + + assert browser.open_page(ADDRESS, tmp_path) + assert len(opener.handed) == 1 + + +@pytest.mark.parametrize( + "opener", + [Opener(answer=False), Opener(raises=OSError(2, "No such file")), Opener(raises=ValueError("embedded null byte"))], + ids=["says no", "cannot start", "refuses the path"], +) +def test_when_no_browser_is_asked_the_file_is_gone_and_the_answer_is_no( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None, opener: Opener +) -> None: + monkeypatch.setattr("webbrowser.open", opener) + + assert not browser.open_page(ADDRESS, tmp_path) + assert len(opener.handed) == 1 + assert not (tmp_path / browser.NAME).exists() + + +def test_a_file_that_cannot_be_written_is_no(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None) -> None: + blocked = tmp_path / "a file, not a directory" + blocked.write_text("", encoding="utf-8") + opener = _opener(monkeypatch) + + assert not browser.open_page(ADDRESS, blocked) + assert opener.handed == [] + + +def test_remove_takes_the_file_away_and_is_quiet_when_it_is_not_there( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None +) -> None: + _opener(monkeypatch) + browser.open_page(ADDRESS, tmp_path) + + browser.remove(tmp_path) + browser.remove(tmp_path) + + assert not (tmp_path / browser.NAME).exists() + + +def test_remove_says_in_the_log_when_it_cannot(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + (tmp_path / browser.NAME).mkdir() + + browser.remove(tmp_path) + + assert f"The file {tmp_path / browser.NAME} could not be removed" in caplog.text diff --git a/tests/test_console.py b/tests/test_console.py new file mode 100644 index 0000000..f0322d2 --- /dev/null +++ b/tests/test_console.py @@ -0,0 +1,1185 @@ +"""The CLI + +An operator runs these by hand, so a missing setting has to say what is missing and a refusal has +to say why, rather than end in a traceback. +""" + +import argparse +import codecs +import datetime +import getpass +import json +import logging +import runpy +import sys +from dataclasses import dataclass +from importlib.metadata import EntryPoint +from pathlib import Path + +import pytest + +from odmdm_connector import __version__, console, plugins, web +from odmdm_connector import fleet as fleet_module +from odmdm_connector.fleet_plugin import FleetPlugin + +from .test_fleet import Request, Response, _Fleet, _host, _mdm + + +@dataclass +class Ran: + """What a run of the command line ended with and printed""" + + exit_code: int + stdout: str + stderr: str + + @property + def output(self) -> str: + return self.stdout + self.stderr + + +class Run: + """console.main on a list of arguments, what is typed at its prompt and extra environment""" + + def __init__(self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> None: + self.capsys = capsys + self.monkeypatch = monkeypatch + + def __call__(self, arguments: list[str], typed: str | None = None, env: dict[str, str] | None = None) -> Ran: + for key, value in (env or {}).items(): + self.monkeypatch.setenv(key, value) + if typed is not None: + self.monkeypatch.setattr(getpass, "getpass", lambda prompt: typed) + self.capsys.readouterr() + try: + code = console.main(arguments) + except SystemExit as exc: + code = int(exc.code or 0) + out, err = self.capsys.readouterr() + return Ran(code, out, err) + + +@pytest.fixture +def run(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> Run: + return Run(capsys, monkeypatch) + + +#: The certificate subject the template loader accepts: the callsign the operator gave the phone +NAMED = "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" + + +@pytest.fixture +def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: + """A configured connector talking to a stubbed Fleet whose team "rmscep" has its certificate template + + And its policy, last sent after the time _host gives a phone by default. + """ + token = tmp_path / "token" + token.write_text("token\n", encoding="utf-8") + monkeypatch.setenv("ODMDM_MDM_URL", "https://mdm.test") + monkeypatch.setenv("ODMDM_TOKEN_FILE", str(token)) + monkeypatch.setenv("ODMDM_TEAM", "rmscep") + stub = _Fleet() + stub.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep"}] + stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": NAMED, "certificate_authority_id": 3}] + stub.profiles = [ + { + "name": "rmscep-policy", + "profile_uuid": "g4bb", + "created_at": "2026-11-20T21:02:44.458685Z", + "updated_at": "2026-11-20T21:02:44Z", + "raw": {"defaultPermissionPolicy": "GRANT"}, + } + ] + _mdm(stub, monkeypatch) + return stub + + +@pytest.mark.parametrize("command", [["apply"], ["challenge"]]) +def test_a_domain_is_required(command: list[str], monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """Without it there is nothing to state to Fleet; the template defaults to the one shipped""" + monkeypatch.delenv("ODMDM_DOMAIN", raising=False) + + result = run(command, env={"ODMDM_CHALLENGE": "new-window"}) + + assert result.exit_code == 1 + assert "ODMDM_DOMAIN" in result.stderr + + +def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + path = tmp_path / "template.json" + path.write_text( + json.dumps( + { + "apps": [{"package": "com.example.one"}], + "policy": {"defaultPermissionPolicy": "GRANT"}, + "certificate": {"name": "{key_alias}", "subject": NAMED, "authority": "RMSCEP"}, + } + ), + encoding="utf-8", + ) + monkeypatch.setenv("ODMDM_TEMPLATE", str(path)) + monkeypatch.setenv("ODMDM_DOMAIN", "example.fi") + + +def test_apply_states_the_template(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """One team: phones enrol into the team that has the certificate template""" + _template(tmp_path, monkeypatch) + monkeypatch.setenv("ODMDM_CHALLENGE", "new-window") + + result = run(["apply"]) + + assert result.exit_code == 0, result.output + assert "Applied to team rmscep (7): 1 apps assigned" in result.output + assert fleet.authorities[0]["challenge"] == "new-window" + assert fleet.authorities[0]["url"] == "https://example.fi/scep" + + +def test_a_dry_run_never_reaches_fleet( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """Checking an edited template must not change the estate""" + _template(tmp_path, monkeypatch) + + result = run(["apply", "--dry-run"]) + + assert result.exit_code == 0, result.output + assert not fleet.calls + + +def test_a_new_window_touches_only_the_authority( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """A rewritten policy stops apps installing on phones enrolling right now""" + _template(tmp_path, monkeypatch) + + result = run(["challenge"], typed="new-window") + + assert result.exit_code == 0, result.output + assert "new-window" not in result.output, "asked for without echoing it" + assert fleet.authorities[0]["challenge"] == "new-window" + changed = {path for method, path in fleet.calls if method != "GET"} + assert changed == {"/api/latest/fleet/certificate_authorities/3"} + + +def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """No Fleet configured is a sentence, not a traceback""" + monkeypatch.delenv("ODMDM_MDM_URL", raising=False) + + result = run(["phones"]) + + assert result.exit_code == 1 + assert "Fleet address is missing: give --set mdm_url=... or set ODMDM_MDM_URL" in result.stderr + + +NO_NAME = ( + "Could not replace certificate variables: host 6f1c0e52-9a6b-4b8e-8f43-2d0c5f6a1b7e does not have an IDP user " + "for variable FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" +) +REFUSED = "SCEP enrollment failed: Enrollment failed with SCEP failInfo: badMessageCheck" +UNREACHED = "Network error during SCEP enrollment: Failed to communicate with SCEP server" + + +@pytest.mark.parametrize( + ("status", "detail", "says"), + [ + ("", "", "no certificate requested"), + ("failed", NO_NAME, "named, but its certificate was not asked for again: ask again"), + ("pending", "", "requested, waiting for the phone"), + ("delivering", "", "requested, waiting for the phone"), + ("delivered", "", "requested, waiting for the phone"), + ("pending", REFUSED, "requested, waiting for the phone"), + ("delivered", UNREACHED, "requested, waiting for the phone"), + ("verified", "", "has its certificate"), + ( + "failed", + REFUSED, + "refused by Deploy App: name taken or not allowed, enrolment closed, or Fleet has an old challenge", + ), + ("failed", UNREACHED, "could not reach Deploy App"), + ("failed", "", "failed"), + ( + "failed", + "Something Fleet says that nobody has seen yet", + "failed: Something Fleet says that nobody has seen yet", + ), + ], +) +def test_phones_says_where_each_certificate_is(fleet: _Fleet, status: str, detail: str, says: str, run: Run) -> None: + """In words an operator can act on, rather than Fleet's status and detail""" + fleet.hosts = [_host(31, status, "OTTER4", detail)] + + result = run(["phones"]) + + assert result.exit_code == 0, result.output + assert result.output.split()[:4] == ["31", "OTTER4", "Google", "sdk_gphone64_arm64"] + assert result.output.rstrip("\n").split("2026-11-01 ", 1)[1] == says + + +def test_a_phone_fresh_from_enrolment_waits_for_a_name(fleet: _Fleet, run: Run) -> None: + """Its first request fails for want of one""" + fleet.hosts = [_host(31, "failed", detail=NO_NAME)] + + result = run(["phones"]) + + assert result.exit_code == 0, result.output + assert result.output.split()[:2] == ["31", "-"] + assert result.output.rstrip().endswith("waiting for a name") + + +def test_phones_lists_in_enrolment_order_with_the_callsign_fleet_issues(fleet: _Fleet, run: Run) -> None: + """The certificate carries the name up to its "@"; an old remove row is history, not state""" + fleet.hosts = [ + _host(32, "verified", "OTTER1@CODE", enrolled="2026-11-02T08:00:00Z"), + _host(33, enrolled="2026-11-01T08:00:00Z"), + ] + fleet.hosts[0]["mdm"]["profiles"].insert( + 0, {"name": "rmscep", "status": "failed", "operation_type": "remove", "detail": REFUSED} + ) + + result = run(["phones"]) + + assert result.exit_code == 0, result.output + lines = result.output.splitlines() + assert lines[0].split()[:2] == ["33", "-"] + assert lines[1].split()[:2] == ["32", "OTTER1"] + assert lines[1].endswith("has its certificate") + + +def test_an_empty_team_says_so(fleet: _Fleet, run: Run) -> None: + """Rather than printing nothing, which reads as a failure""" + result = run(["phones"]) + + assert result.exit_code == 0, result.output + assert "No phones in the team" in result.output + + +def _named(fleet: _Fleet) -> dict[int, str]: + return {h["id"]: h["end_users"][0]["idp_username"] if h["end_users"] else "" for h in fleet.hosts} + + +def _changes(fleet: _Fleet) -> list[tuple[str, str]]: + return [(method, path.removeprefix("/api/latest/fleet")) for method, path in fleet.calls if method != "GET"] + + +def test_name_gives_any_number_of_phones_their_callsigns(fleet: _Fleet, run: Run) -> None: + """In any order, each named and then asked for its certificate again under the name""" + fleet.hosts = [_host(host, "failed", detail=NO_NAME) for host in (31, 32, 33)] + + result = run(["name", "33=OTTER5", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Phone 33 is OTTER5", "Phone 31 is OTTER4"] + assert _named(fleet) == {31: "OTTER4", 32: "", 33: "OTTER5"} + assert _changes(fleet) == [ + ("PUT", "/hosts/33/device_mapping"), + ("POST", "/hosts/33/certificates/81/resend"), + ("PUT", "/hosts/31/device_mapping"), + ("POST", "/hosts/31/certificates/81/resend"), + ] + + +def test_a_request_still_pending_takes_the_name_without_a_resend(fleet: _Fleet, run: Run) -> None: + """Fleet refuses to resend it, and it needs none: it is filled in when it goes""" + fleet.hosts = [_host(31, "pending")] + + result = run(["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Phone 31 is OTTER4"] + assert _named(fleet) == {31: "OTTER4"} + + +def test_a_phone_with_its_certificate_under_the_name_is_left_alone(fleet: _Fleet, run: Run) -> None: + """Asked again under the name it holds, it is refused as taken and then reads as refused""" + fleet.hosts = [_host(31, "verified", "OTTER4@CODE"), _host(32, "failed", detail=NO_NAME)] + + result = run(["name", "31=otter4", "32=OTTER5"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Phone 31 is already OTTER4", "Phone 32 is OTTER5"] + assert _changes(fleet) == [("PUT", "/hosts/32/device_mapping"), ("POST", "/hosts/32/certificates/81/resend")] + assert _named(fleet)[31] == "OTTER4@CODE" + + +def test_a_phone_with_no_request_is_named_and_the_batch_goes_on(fleet: _Fleet, run: Run) -> None: + """Fleet has no request to send it again, and fills the name in when it makes one""" + fleet.hosts = [_host(31, "failed", detail=NO_NAME), _host(32), _host(33, "failed", detail=NO_NAME)] + + result = run(["name", "--all", "OTTER"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [ + "Phone 31 is OTTER1", + "Phone 32 is OTTER2. Fleet has no certificate request for it, so nothing was sent", + "Phone 33 is OTTER3", + ] + assert _named(fleet) == {31: "OTTER1", 32: "OTTER2", 33: "OTTER3"} + assert ("POST", "/hosts/32/certificates/81/resend") not in _changes(fleet) + + +@pytest.mark.parametrize( + ("first", "start", "expected"), + [ + ("KETTU1", [], {42: "OTTER1", 43: "OTTER2", 41: "OTTER3"}), + ("otter7", [], {42: "OTTER8", 43: "OTTER9", 41: "OTTER10"}), + ("OTTER7", ["--start", "20"], {42: "OTTER20", 43: "OTTER21", 41: "OTTER22"}), + ], +) +def test_name_all_numbers_the_phones_without_a_name( + fleet: _Fleet, first: str, start: list[str], expected: dict[int, str], run: Run +) -> None: + """In enrolment order, then host id, from one above the highest number in use unless told""" + fleet.hosts = [ + _host(40, "verified", first, enrolled="2026-11-01T08:00:00Z"), + _host(41, "failed", detail=NO_NAME, enrolled="2026-11-03T08:00:00Z"), + _host(43, "failed", detail=NO_NAME, enrolled="2026-11-02T08:00:00Z"), + _host(42, "failed", detail=NO_NAME, enrolled="2026-11-02T08:00:00Z"), + ] + + result = run(["name", "--all", "OTTER", *start]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [f"Phone {host} is {callsign}" for host, callsign in expected.items()] + assert _named(fleet) == {40: first, **expected} + + +def test_name_all_with_every_phone_named_names_nothing(fleet: _Fleet, run: Run) -> None: + """A second run finds nobody waiting, and changes nothing""" + fleet.hosts = [_host(31, "verified", "OTTER1")] + + result = run(["name", "--all", "OTTER"]) + + assert result.exit_code == 0, result.output + assert "Nothing to name" in result.output + assert not _changes(fleet) + + +@pytest.mark.parametrize( + ("arguments", "says"), + [ + (["31=OT"], "OT: a callsign is 3-32 letters"), + (["31=OTTER-"], "OTTER-: a callsign is 3-32 letters"), + (["--all", "O"], "O1: a callsign is 3-32 letters"), + (["31=OTTER4", "32=otter4"], "otter4 is given twice"), + (["31=OTTER4", "31=OTTER5"], "phone 31 is named twice"), + (["31=otter9"], "otter9 already belongs to phone 33"), + (["--all", "OTTER", "--start", "9"], "OTTER9 already belongs to phone 33"), + (["31=OTTER4", "99=OTTER5"], "phone 99 is not in the group"), + ], +) +def test_name_changes_nothing_unless_every_name_can_be_given( + fleet: _Fleet, arguments: list[str], says: str, run: Run +) -> None: + """A typo refuses the whole command, rather than leaving half a batch named""" + fleet.hosts = [ + _host(31, "failed", detail=NO_NAME), + _host(32, "failed", detail=NO_NAME), + _host(33, "verified", "OTTER9@CODE"), + ] + + result = run(["name", *arguments]) + + assert result.exit_code == 1 + assert f"Nothing named: {says}" in result.stderr + assert not _changes(fleet) + + +@pytest.mark.parametrize("arguments", [[], ["31=OTTER4", "--all", "OTTER"], ["31=OTTER4", "--start", "3"], ["OTTER4"]]) +def test_name_says_how_it_is_used(fleet: _Fleet, arguments: list[str], run: Run) -> None: + """Before Fleet is asked anything""" + result = run(["name", *arguments]) + + assert result.exit_code == 2 + assert not fleet.calls + + +def test_renaming_a_phone_with_its_certificate_says_what_to_revoke(fleet: _Fleet, run: Run) -> None: + """The old callsign stays valid in Deploy App until an admin revokes it there""" + fleet.hosts = [_host(31, "verified", "OTTER3")] + + result = run(["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [ + "Phone 31 is OTTER4. It was OTTER3 and still has that certificate: revoke OTTER3 in Deploy App." + ] + + +def test_renaming_a_refused_phone_says_nothing_to_revoke(fleet: _Fleet, run: Run) -> None: + """A refused name was never issued to this phone, and may be another phone's""" + fleet.hosts = [_host(31, "failed", "OTTER3", REFUSED)] + + result = run(["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Phone 31 is OTTER4"] + + +def test_name_without_a_certificate_template_says_so(fleet: _Fleet, run: Run) -> None: + """Before a phone is named, so nothing is left half done""" + fleet.certificates = [] + fleet.hosts = [_host(31, "failed", detail=NO_NAME)] + + result = run(["name", "31=OTTER4"]) + + assert result.exit_code == 1 + assert "no certificate template named rmscep: set Fleet up first" in result.stderr + assert not _changes(fleet) + + +def test_resend_asks_again_for_every_named_phone_that_failed(fleet: _Fleet, run: Run) -> None: + """A phone named in Fleet by hand is one of them: naming alone does not send the request again""" + fleet.hosts = [ + _host(31, "failed", "OTTER4", REFUSED), + _host(32, "failed", detail=NO_NAME), + _host(33, "verified", "OTTER5"), + _host(34, "failed", "OTTER6", NO_NAME), + _host(35, "pending", "OTTER7"), + ] + + result = run(["resend"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [ + "Phone 31 (OTTER4): certificate asked for again", + "Phone 34 (OTTER6): certificate asked for again", + ] + assert _changes(fleet) == [ + ("POST", "/hosts/31/certificates/81/resend"), + ("POST", "/hosts/34/certificates/81/resend"), + ] + + +def test_resend_given_hosts_asks_for_those(fleet: _Fleet, run: Run) -> None: + """Whatever state they are in: the operator chose them""" + fleet.hosts = [_host(31, "failed", "OTTER4", REFUSED), _host(32, "failed", detail=NO_NAME)] + + result = run(["resend", "32"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Phone 32 (no name): certificate asked for again"] + assert _changes(fleet) == [("POST", "/hosts/32/certificates/81/resend")] + + +@pytest.mark.parametrize(("arguments", "says", "code"), [([], "Nothing to resend", 0), (["99"], "not in the team", 1)]) +def test_resend_says_when_it_sends_nothing(fleet: _Fleet, arguments: list[str], says: str, code: int, run: Run) -> None: + """Nobody failed, or a host that is not in the team: said, and nothing sent""" + fleet.hosts = [_host(31, "verified", "OTTER4")] + + result = run(["resend", *arguments]) + + assert result.exit_code == code, result.output + assert says in result.output + assert not _changes(fleet) + + +#: After the fixture's policy was last sent +LATER = "2026-11-20T21:10:02Z" + + +def _policy_changes(fleet: _Fleet) -> list[tuple[str, str]]: + return [change for change in _changes(fleet) if "/configuration_profiles" in change[1]] + + +def test_name_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Fleet, run: Run) -> None: + """Fleet can write a bare policy over a new phone's, and never sends ours again by itself + + Measured: the certificate installs, Chrome is not allowed to use it, and Deploy App says + "Certificate Authentication Failed". Fleet's own copy uploaded again reaches the phone. + """ + fleet.hosts = [ + _host(31, "failed", detail=NO_NAME, enrolled=LATER), + _host(32, "failed", detail=NO_NAME, enrolled=LATER), + _host(33, "verified", "OTTER1"), + ] + + result = run(["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines() == [ + "Phone 31 is OTTER4", + "Policy sent again: 2 phones enrolled after it was last sent", + ] + assert _policy_changes(fleet) == [("DELETE", "/configuration_profiles/g4bb"), ("POST", "/configuration_profiles")] + assert [profile["raw"] for profile in fleet.profiles] == [{"defaultPermissionPolicy": "GRANT"}] + + +def test_resend_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Fleet, run: Run) -> None: + """The phone asked again may be one whose policy Fleet overwrote""" + fleet.hosts = [_host(31, "failed", "OTTER4", REFUSED, enrolled=LATER), _host(32, "verified", "OTTER5")] + + result = run(["resend"]) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines() == [ + "Phone 31 (OTTER4): certificate asked for again", + "Policy sent again: 1 phone enrolled after it was last sent", + ] + assert _policy_changes(fleet) == [("DELETE", "/configuration_profiles/g4bb"), ("POST", "/configuration_profiles")] + + +def test_a_policy_sent_again_is_then_left_alone(fleet: _Fleet, run: Run) -> None: + """Fleet stamps an upload with its own clock, so the policy is newer than every phone already there + + Sent on every run, it would be rewritten under phones still installing their apps. + """ + fleet.now = "2026-11-20T21:30:00.123456Z" + fleet.hosts = [ + _host(31, "failed", detail=NO_NAME, enrolled=LATER), + _host(32, "failed", detail=NO_NAME, enrolled=LATER), + ] + + first = run(["name", "31=OTTER4"]) + fleet.calls.clear() + second = run(["name", "32=OTTER5"]) + + assert first.stdout.splitlines()[-1] == "Policy sent again: 2 phones enrolled after it was last sent" + assert second.exit_code == 0, second.output + assert second.stdout.splitlines() == ["Phone 32 is OTTER5"] + assert not _policy_changes(fleet) + + +@pytest.mark.parametrize(("policy", "enrolled"), [(True, "2026-11-01T19:38:12Z"), (False, LATER)]) +def test_the_policy_is_left_alone_unless_a_phone_enrolled_after_it( + fleet: _Fleet, policy: bool, enrolled: str, run: Run +) -> None: + """Every phone enrolled before it was last sent, or the team has no policy to send""" + if not policy: + fleet.profiles = [] + fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=enrolled)] + + result = run(["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Phone 31 is OTTER4"] + assert _changes(fleet) == [("PUT", "/hosts/31/device_mapping"), ("POST", "/hosts/31/certificates/81/resend")] + + +@pytest.mark.parametrize( + ("command", "said"), + [ + (["name", "31=OTTER4"], "Phone 31 is already OTTER4"), + (["name", "--all", "OTTER"], "Nothing to name"), + (["resend"], "Nothing to resend"), + ], +) +def test_the_policy_is_sent_again_only_after_a_phone_is_named_or_asked_again( + fleet: _Fleet, command: list[str], said: str, run: Run +) -> None: + """A run that changed nothing leaves the policy alone, as it would a phone still installing apps""" + fleet.hosts = [_host(31, "verified", "OTTER4", enrolled=LATER)] + + result = run(command) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [said] + assert not _changes(fleet) + + +def test_a_policy_fleet_refuses_is_said_after_the_names( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """The phones are named all the same, and the refusal is said as any other""" + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.url.params.get("alt") == "media": + return Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=LATER)] + + result = run(["name", "31=OTTER4"]) + + assert result.exit_code == 1 + assert result.output.splitlines()[0] == "Phone 31 is OTTER4" + assert "Fleet refused: GET /api/latest/fleet/configuration_profiles/g4bb?alt=media answered 500" in result.stderr + assert _named(fleet) == {31: "OTTER4"} + assert not _policy_changes(fleet) + + +def test_a_policy_lost_between_delete_and_upload_is_said( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """The team then has no policy, every phone in it loses the settings, and a later run sees nothing""" + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.method == "POST" and request.url.path.endswith("/configuration_profiles"): + return Response(502, text="Bad Gateway") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=LATER)] + + result = run(["name", "31=OTTER4"]) + + assert result.exit_code == 1 + assert result.output.splitlines()[0] == "Phone 31 is OTTER4" + assert "may now be missing" in result.stderr + assert "sending the policy again puts it back" in result.stderr + assert "apply" not in result.stderr, "Fleet's sentence names no command" + assert not fleet.profiles + + +def test_apply_force_policy_makes_no_team( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """Sending the policy again is a repair: a team Fleet lacks is refused before anything is changed""" + _template(tmp_path, monkeypatch) + monkeypatch.setenv("ODMDM_CHALLENGE", "new-window") + + result = run(["apply", "--force-policy", "--team", "Typo"]) + + assert result.exit_code == 1 + assert result.stderr == ( + "Fleet has no team named Typo, so nothing was changed: sending the policy again makes no team. " + "Check the team's name.\n" + ) + assert not _changes(fleet) + + +@pytest.mark.parametrize("command", [["phones"], ["name", "31=OTTER4"], ["resend"]]) +def test_an_unknown_team_is_named_not_created(fleet: _Fleet, command: list[str], run: Run) -> None: + """A typo must not leave an empty team behind for the next phone to enrol into""" + fleet.hosts = [_host(31, "failed", detail=NO_NAME)] + + result = run([*command, "--team", "Typo"]) + + assert result.exit_code == 1 + assert "no team named Typo" in result.stderr + assert not _changes(fleet) + + +def test_the_mdm_address_must_be_https(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """The token goes with every request, so it must not cross the network readable""" + monkeypatch.setenv("ODMDM_MDM_URL", "http://mdm.test") + + result = run(["phones"]) + + assert result.exit_code == 1 + assert "must start with https://" in result.stderr + assert not fleet.calls + + +@pytest.mark.parametrize("start", ["0", "-3"]) +def test_name_all_starts_from_one_or_more(fleet: _Fleet, start: str, run: Run) -> None: + """Callsigns are numbered from 1""" + result = run(["name", "--all", "OTTER", "--start", start]) + + assert result.exit_code == 2 + assert not fleet.calls + + +@pytest.mark.parametrize("count", [4, 5]) +def test_phones_reads_every_page_of_hosts(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, count: int, run: Run) -> None: + """A team bigger than one page is listed whole, also when the last page is full""" + monkeypatch.setattr(fleet_module, "HOSTS_PER_PAGE", 2) + fleet.hosts = [_host(31 + n, "verified", f"OTTER{n + 1}") for n in range(count)] + + result = run(["phones"]) + + assert result.exit_code == 0, result.output + assert [line.split()[0] for line in result.output.splitlines()] == [str(31 + n) for n in range(count)] + + +def test_a_batch_stopped_half_way_says_which_phones_are_named( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """So the operator names only the rest, rather than guessing""" + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.url.path.endswith("/hosts/32/certificates/81/resend"): + return Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(host, "failed", detail=NO_NAME) for host in (31, 32, 33)] + + result = run(["name", "--all", "OTTER"]) + + assert result.exit_code == 1 + assert result.stdout.splitlines() == ["Phone 31 is OTTER1"] + assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.stderr + assert "Already named before it stopped: 31=OTTER1 32=OTTER2. phones shows where each is" in result.stderr + assert _named(fleet) == {31: "OTTER1", 32: "OTTER2", 33: ""} + + +def test_a_rename_stopped_half_way_still_says_what_to_revoke( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """Nothing shows the old callsign afterwards, so its line must not be lost with the error""" + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.url.path.endswith("/hosts/32/certificates/81/resend"): + return Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "verified", "OTTER3"), _host(32, "failed", detail=NO_NAME)] + + result = run(["name", "31=OTTER4", "32=OTTER5"]) + + assert result.exit_code == 1 + assert result.stdout.splitlines() == [ + "Phone 31 is OTTER4. It was OTTER3 and still has that certificate: revoke OTTER3 in Deploy App." + ] + assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.stderr + + +def test_a_resend_stopped_half_way_says_what_was_asked( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """The phones asked before the error are said as on success""" + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.url.path.endswith("/hosts/34/certificates/81/resend"): + return Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "failed", "OTTER31", REFUSED), _host(34, "failed", "OTTER34", REFUSED)] + + result = run(["resend"]) + + assert result.exit_code == 1 + assert result.stdout.splitlines() == ["Phone 31 (OTTER31): certificate asked for again"] + assert "Fleet refused: POST /api/latest/fleet/hosts/34/certificates/81/resend answered 500" in result.stderr + + +LINE = (Path(__file__).parent / "data" / "settings-line-v1.txt").read_text(encoding="utf-8").strip() +SECRET = "0123456789abcdef0123456789abcdef" # pragma: allowlist secret + + +@pytest.fixture +def window(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: + """The stub Fleet, a template, the vector's domain, and a clock before its window closes""" + _template(tmp_path, monkeypatch) + monkeypatch.setenv("ODMDM_DOMAIN", "unit.example.fi") + monkeypatch.setattr(console, "_now", lambda: datetime.datetime(2026, 11, 21, 12, 0, tzinfo=datetime.UTC)) + fleet.authorities[0]["url"] = "https://unit.example.fi/scep" + return fleet + + +@pytest.mark.parametrize( + ("arguments", "typed", "env"), + [ + ([], LINE, {}), + ([], None, {"ODMDM_CHALLENGE": LINE}), + ], +) +def test_challenge_takes_the_settings_line( + window: _Fleet, + caplog: pytest.LogCaptureFixture, + arguments: list[str], + typed: str | None, + env: dict[str, str], + run: Run, +) -> None: + """Typed at the hidden prompt or from the environment""" + result = run(["-vv", "challenge", *arguments], typed=typed, env=env) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines()[-1] == ( + "Fleet has the new challenge. The enrolment window is open until 2026-11-21 14:00" + ) + assert window.authorities[0]["challenge"] == SECRET + assert window.authorities[0]["url"] == "https://unit.example.fi/scep" + assert SECRET not in result.output + assert SECRET not in caplog.text + + +def test_challenge_takes_the_team(window: _Fleet, run: Run) -> None: + """The team's certificate template says which authority gets the challenge, so the team is given as elsewhere""" + window.teams.append({"id": 8, "name": "North"}) + window.authorities.append({"id": 4, "name": "ODMDM_NORTH", "url": "https://north.example.fi/scep"}) + window.certificates = [ + {"id": 82, "name": "rmscep", "team_id": 8, "subject_name": NAMED, "certificate_authority_id": 4} + ] + + result = run(["challenge", "--team", "North"], env={"ODMDM_CHALLENGE": LINE}) + + assert result.exit_code == 1 + assert "the team takes its certificates from authority ODMDM_NORTH" in result.stderr + assert not _changes(window) + + +def test_challenge_is_never_an_argument(window: _Fleet, run: Run) -> None: + """An argument is in the process list and the shell history""" + result = run(["challenge", "--challenge", LINE]) + + assert result.exit_code == 2 + assert "unrecognized arguments: --challenge" in result.stderr + assert not window.calls + + +@pytest.mark.parametrize( + ("line", "says"), + [ + (LINE.replace("unit.example.fi", "other.example.fi"), "is for other.example.fi, not unit.example.fi"), + (LINE.replace("https://", "http://"), "must be https:///"), + (LINE.replace("2026-11-21T14", "2026-11-21T11"), "closed at 11:00"), + (LINE.replace("ODMDM1", "ODMDM2"), "not a settings line"), + (LINE.replace("ODMDM1", "odmdm1"), "not a settings line"), + (LINE.split(None, 1)[1], "not a settings line"), + ('"' + LINE + '"', "not a settings line"), + ], +) +def test_challenge_refuses_a_line_it_cannot_use(window: _Fleet, line: str, says: str, run: Run) -> None: + """Before Fleet is asked anything, and without the challenge in the message""" + result = run(["challenge"], typed=line) + + assert result.exit_code == 1 + assert says in result.stderr + assert SECRET not in result.output + assert not window.calls + + +def test_apply_takes_the_settings_line_from_the_environment( + window: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """ODMDM_CHALLENGE may hold the line; apply must not send the whole line as the challenge""" + monkeypatch.setenv("ODMDM_CHALLENGE", LINE) + + result = run(["apply"]) + + assert result.exit_code == 0, result.output + assert window.authorities[0]["challenge"] == SECRET + assert SECRET not in result.output + + +def test_apply_refuses_a_line_for_another_deployment(window: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + monkeypatch.setenv("ODMDM_CHALLENGE", LINE.replace("unit.example.fi", "other.example.fi")) + + result = run(["apply"]) + + assert result.exit_code == 1 + assert "is for other.example.fi" in result.stderr + assert not window.calls + + +@pytest.mark.parametrize( + ("options", "env", "says"), + [ + (["--mdm", "nope"], {}, "No MDM named nope is installed"), + ([], {"ODMDM_MDM": "nope"}, "No MDM named nope is installed"), + (["--set", "nope=1"], {}, "fleet has no setting nope; it has key_alias, mdm_url, team, template, token"), + (["--set", "team"], {}, "--set takes KEY=VALUE"), + (["--set", f"token={SECRET}"], {}, "token is a secret: put it in a file and set ODMDM_TOKEN_FILE"), + ], +) +def test_the_mdm_and_its_settings_are_checked_first( + fleet: _Fleet, options: list[str], env: dict[str, str], says: str, run: Run +) -> None: + """Before the MDM is asked anything, and without a value in the message""" + result = run([*options, "phones"], env=env) + + assert result.exit_code == 2 + assert says in result.stderr + assert SECRET not in result.output + assert not fleet.calls + + +def test_set_gives_an_mdm_setting(fleet: _Fleet, run: Run) -> None: + """The same as the command's own shorthand, here --team""" + result = run(["--set", "team=Typo", "phones"]) + + assert result.exit_code == 1 + assert "no team named Typo" in result.stderr + + +def test_a_secret_is_never_read_from_a_plain_variable(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """Only from the file its _FILE variable names""" + monkeypatch.delenv("ODMDM_TOKEN_FILE") + + result = run(["phones"], env={"ODMDM_TOKEN": "token"}) + + assert result.exit_code == 1 + assert "API token is missing: put it in a file and set ODMDM_TOKEN_FILE to that file" in result.stderr + assert not fleet.calls + + +def test_a_secret_with_a_line_break_is_refused_and_never_shown( + fleet: _Fleet, tmp_path: Path, run: Run, caplog: pytest.LogCaptureFixture +) -> None: + caplog.set_level(logging.DEBUG) + token = tmp_path / "broken.token" + token.write_text("TOPSECRETA\nTOPSECRETB\n", encoding="utf-8") + + result = run(["phones"], env={"ODMDM_TOKEN_FILE": str(token)}) + + assert result.exit_code == 1 + assert result.stderr == ( + "The API token holds a line break or another character that cannot be part of it: copy it again.\n" + ) + assert "TOPSECRET" not in result.output + caplog.text + assert not fleet.calls + + +@pytest.mark.parametrize( + "written", + [ + b"TOPSECRET\n", + codecs.BOM_UTF8 + b"TOPSECRET\r\n", + "TOPSECRET\r\n".encode("utf-16"), + codecs.BOM_UTF16_BE + "TOPSECRET".encode("utf-16-be"), + ], + ids=["utf-8", "utf-8 with its mark", "utf-16 as PowerShell 5.1 writes", "utf-16 big-endian"], +) +def test_a_token_file_is_read_in_the_encodings_editors_write( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, written: bytes +) -> None: + token = tmp_path / "token" + token.write_bytes(written) + monkeypatch.setenv("ODMDM_TOKEN_FILE", str(token)) + + assert console._values("fleet", FleetPlugin.fields, {}, "")["token"] == "TOPSECRET" + + +@pytest.mark.parametrize("unreadable", ["not text", "not readable"]) +def test_a_token_file_that_cannot_be_read_as_text_is_said_without_the_token( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run, unreadable: str +) -> None: + token = tmp_path / "broken.token" + token.write_bytes(b"TOPSECRET\xff\xfe") + if unreadable == "not readable": + token.write_text("TOPSECRET", encoding="utf-8") + + def refuse(self: Path) -> bytes: + raise PermissionError(13, "Permission denied", str(self)) + + monkeypatch.setattr(Path, "read_bytes", refuse) + + result = run(["phones"], env={"ODMDM_TOKEN_FILE": str(token)}) + + assert result.exit_code == 1 + assert result.stderr == f"The file {token} cannot be read as plain text: save the API token in it as plain text.\n" + assert "TOPSECRET" not in result.output + assert not fleet.calls + + +@pytest.mark.parametrize( + ("command", "capability"), + [ + (["challenge"], "set_challenge"), + (["apply"], "setup"), + (["resend"], "ask_again"), + (["apply", "--force-policy"], "send_policy"), + ], +) +def test_a_capability_the_mdm_lacks_is_its_sentence( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: list[str], capability: str, run: Run +) -> None: + """Said instead of calling the MDM, and before a challenge is asked for""" + _template(tmp_path, monkeypatch) + monkeypatch.setattr(FleetPlugin, "missing", {capability: "Paste the challenge in the MDM's console by hand"}) + + result = run(command) + + assert result.exit_code == 1 + assert result.stderr == "Paste the challenge in the MDM's console by hand\n" + assert not fleet.calls + + +def test_a_dry_run_needs_no_mdm(monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """The template shipped with the connector, checked with nothing configured but the domain""" + for setting in ("MDM_URL", "TOKEN_FILE", "TEMPLATE"): + monkeypatch.delenv(f"ODMDM_{setting}", raising=False) + monkeypatch.setenv("ODMDM_DOMAIN", "example.fi") + + result = run(["apply", "--dry-run"]) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines()[0] == "Template names 3 apps, 3 installed at enrolment" + assert result.stdout.splitlines()[-1] == " launcher link 'Deploy App' -> https://mtls.example.fi/" + + +def _declare(monkeypatch: pytest.MonkeyPatch, *found: tuple[str, str, str]) -> None: + """These MDMs installed and no other, each as name, package and module:class""" + declared = [ + plugins.Plugin(name, package, "0.1.0", EntryPoint(name, value, plugins.GROUP)) for name, package, value in found + ] + monkeypatch.setattr(plugins, "_declared", lambda: declared) + + +FAKE = ("fake", "odmdm-connector-fake", "odmdm_connector.testing.fake:FakeMdm") + + +def test_mdms_lists_what_is_installed_without_loading_it(monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + _declare( + monkeypatch, + ("zeta", "odmdm-connector-zeta", "never_imported:Mdm"), + ("fleet", "odmdm-connector", "odmdm_connector.never_imported:Mdm"), + ) + + result = run(["mdms"]) + + assert result.exit_code == 0, result.output + assert [line.split() for line in result.stdout.splitlines()] == [ + ["fleet", "odmdm-connector", "0.1.0", "built", "in"], + ["zeta", "odmdm-connector-zeta", "0.1.0", "plugin"], + ] + + +def test_a_plugin_says_whose_code_it_is_before_it_runs(monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """On stderr, so what the command prints stays the same""" + _declare(monkeypatch, FAKE) + + result = run(["--mdm", "fake", "phones"]) + + assert result.exit_code == 0, result.output + assert result.stderr == "The MDM fake is a plugin from odmdm-connector-fake 0.1.0: code that sees the MDM token\n" + assert [line.split()[:2] for line in result.stdout.splitlines()] == [["a1", "-"], ["a2", "-"], ["a3", "OTTER1"]] + + +def test_the_built_in_mdm_says_nothing_of_itself(fleet: _Fleet, run: Run) -> None: + fleet.hosts = [_host(31)] + + result = run(["phones"]) + + assert result.exit_code == 0, result.output + assert not result.stderr + + +@pytest.mark.parametrize( + ("found", "command", "says"), + [ + ([FAKE, ("fake", "odmdm-connector-other", "never_imported:Mdm")], ["mdms"], "odmdm-connector-fake 0.1.0 and"), + ([FAKE, ("fake", "odmdm-connector-other", "never_imported:Mdm")], ["--mdm", "fake", "phones"], "Uninstall one"), + ( + [("old", "odmdm-connector-old", "tests.test_plugins:Old")], + ["--mdm", "old", "phones"], + "speaks MDM API version 2", + ), + ], +) +def test_a_plugin_the_connector_cannot_use_is_said( + monkeypatch: pytest.MonkeyPatch, found: list[tuple[str, str, str]], command: list[str], says: str, run: Run +) -> None: + _declare(monkeypatch, *found) + + result = run(command) + + assert result.exit_code == 1 + assert says in result.stderr + + +def test_python_m_runs_the_command_line(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + """The way to run it from a zip application or a checkout, without the installed script""" + monkeypatch.setattr(sys, "argv", ["odmdm-connector", "--version"]) + + with pytest.raises(SystemExit) as ended: + runpy.run_module("odmdm_connector", run_name="__main__") + + assert ended.value.code == 0 + assert capsys.readouterr().out == f"odmdm-connector, version {__version__}\n" + + +def test_ctrl_c_at_the_prompt_says_it_stopped(window: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """A sentence rather than a traceback, and the MDM is not asked""" + + def interrupted(prompt: str) -> str: + raise KeyboardInterrupt + + monkeypatch.setattr(getpass, "getpass", interrupted) + + result = run(["challenge"]) + + assert result.exit_code == 1 + assert result.stderr == "Stopped before the command finished.\n" + assert not window.calls + + +@pytest.mark.parametrize("level", ["debug", "", "1.5"]) +def test_a_log_level_that_is_not_a_number_is_said(run: Run, level: str) -> None: + result = run(["mdms"], env={"ODMDM_LOG_LEVEL": level}) + + assert (result.exit_code, result.stdout, result.stderr) == (1, "", f"{console.LOG_LEVEL}\n") + + +def _pages(monkeypatch: pytest.MonkeyPatch) -> list[argparse.Namespace]: + """What the web command was started with, each time, in place of serving the page""" + started: list[argparse.Namespace] = [] + + def page(args: argparse.Namespace) -> int: + """Serve the page""" + started.append(args) + return 0 + + monkeypatch.setattr(console, "page", page) + return started + + +@pytest.mark.parametrize( + ("arguments", "verbose"), + [([], 0), (["-v"], 1), (["--mdm", "fleet", "--set", "team=Deploy App"], 0)], +) +def test_without_a_command_the_page_starts_with_web_s_defaults( + arguments: list[str], verbose: int, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """A downloaded file is started by a double-click, with no arguments""" + started = _pages(monkeypatch) + + result = run(arguments) + + assert result.exit_code == 0 + assert [(args.port, args.browser, args.verbose) for args in started] == [(web.PORT, True, verbose)] + + +@pytest.mark.parametrize("arguments", [["--help"], ["--version"], ["nope"], ["-v", "nope"]]) +def test_help_version_and_a_wrong_command_start_no_page( + arguments: list[str], monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + started = _pages(monkeypatch) + + result = run(arguments) + + assert not started + assert result.exit_code == (2 if "nope" in arguments else 0) + if "nope" in arguments: + assert "invalid choice: 'nope'" in result.stderr + + +def test_the_team_is_named_after_the_deployment_unless_given(monkeypatch: pytest.MonkeyPatch) -> None: + """From --domain, else ODMDM_DOMAIN; a team given with --team, --set or ODMDM_TEAM wins""" + monkeypatch.delenv("ODMDM_TEAM", raising=False) + host = "golden-monkey.example.fi" + + assert console._values("fleet", FleetPlugin.fields, {}, host)["team"] == "golden-monkey DeployApp" + assert console._values("fleet", FleetPlugin.fields, {"team": "Deploy App"}, host)["team"] == "Deploy App" + monkeypatch.setenv("ODMDM_TEAM", "rmscep") + assert console._values("fleet", FleetPlugin.fields, {}, host)["team"] == "rmscep" + + +def test_the_team_default_is_the_pages_for_any_spelling_of_the_domain(monkeypatch: pytest.MonkeyPatch) -> None: + """A domain in mixed case gives the page's lower-case team, and an address with its scheme gives none""" + monkeypatch.delenv("ODMDM_TEAM", raising=False) + + assert ( + console._values("fleet", FleetPlugin.fields, {}, "Golden-Monkey.Example.fi")["team"] + == "golden-monkey DeployApp" + ) + assert console._values("fleet", FleetPlugin.fields, {}, "https://golden-monkey.example.fi")["team"] == "" + + +def test_the_default_team_reaches_fleet(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + monkeypatch.delenv("ODMDM_TEAM") + fleet.hosts = [_host(31)] + + named = run(["phones"], env={"ODMDM_DOMAIN": "golden-monkey.example.fi"}) + monkeypatch.delenv("ODMDM_DOMAIN") + unnamed = run(["phones"]) + + assert ("teams" in str(fleet.calls), named.exit_code) == (True, 1) + assert "golden-monkey DeployApp" in named.stderr, "the team asked for, which the stub does not hold" + assert (unnamed.exit_code, unnamed.stderr) == (1, "Team is missing: give --set team=... or set ODMDM_TEAM\n") diff --git a/tests/test_core.py b/tests/test_core.py new file mode 100644 index 0000000..d7147a2 --- /dev/null +++ b/tests/test_core.py @@ -0,0 +1,74 @@ +"""The naming rules, without an MDM""" + +from dataclasses import replace + +import pytest + +from odmdm_connector import core +from odmdm_connector.mdm import Phone, State + + +def _phone(phone: str, callsign: str = "") -> Phone: + return Phone(phone, callsign, "a phone", "2026-11-01T08:00:00Z", State.READY if callsign else State.NEEDS_NAME) + + +def test_ids_are_whatever_the_mdm_calls_its_phones() -> None: + """Opaque strings, split at the first =""" + assert core.pairs(["31=OTTER4", "a-b=OTTER5"]) == [("31", "OTTER4"), ("a-b", "OTTER5")] + + +@pytest.mark.parametrize("value", ["OTTER4", "=OTTER4", "31="]) +def test_a_pair_without_both_halves_is_refused(value: str) -> None: + with pytest.raises(ValueError, match="is not ID=CALLSIGN"): + core.pairs([value]) + + +def test_numbering_goes_on_from_the_highest_in_use() -> None: + """In the order the phones are given, skipping the named ones""" + phones = [_phone("a", "otter7"), _phone("b"), _phone("c", "KETTU9"), _phone("d")] + + assert core.numbered(phones, "OTTER", None) == [("b", "OTTER8"), ("d", "OTTER9")] + assert core.numbered(phones, "OTTER", 20) == [("b", "OTTER20"), ("d", "OTTER21")] + assert (core.next_number(phones, "otter"), core.next_number(phones, "BEAR")) == (8, 1) + + +@pytest.mark.parametrize( + ("wanted", "says"), + [ + ([("a", "OTTER4")], ""), + ([("x", "OTTER4")], "phone x is not in the group"), + ([("a", "OTTER4"), ("a", "OTTER5")], "phone a is named twice"), + ([("a", "-OTTER")], "-OTTER: a callsign is 3-32 letters"), + ([("a", "OTTER4"), ("b", "otter4")], "otter4 is given twice"), + ([("a", "otter9")], "otter9 already belongs to phone c"), + ([("c", "otter9")], ""), + ], +) +def test_a_batch_is_refused_whole(wanted: list[tuple[str, str]], says: str) -> None: + """Callsigns compared without case; a phone may keep its own""" + phones = [_phone("a"), _phone("b"), _phone("c", "OTTER9")] + + refused = core.refusal(phones, wanted) + + assert refused.startswith(says) if says else not refused + + +@pytest.mark.parametrize( + ("state", "says"), + [ + (State.NO_REQUEST, "no certificate requested: the words"), + (State.NEEDS_NAME, "waiting for a name"), + (State.NOT_ASKED, "named, but its certificate was not asked for again: the words"), + (State.WAITING, "requested, waiting for the phone"), + (State.READY, "has its certificate"), + (State.REFUSED, "refused by Deploy App: the words"), + (State.UNREACHABLE, "could not reach Deploy App: the words"), + (State.FAILED, "failed: the words"), + ], +) +def test_the_plugins_words_explain_only_a_certificate_not_under_way(state: State, says: str) -> None: + """After asking again, an old refusal does not sit beside a request that is waiting""" + phone = Phone("a1", "OTTER1", "a phone", "2026-11-01T08:00:00Z", state, "the words") + + assert core.said(phone) == says + assert core.said(replace(phone, detail="")) == state.value diff --git a/tests/test_fleet.py b/tests/test_fleet.py new file mode 100644 index 0000000..fbf6555 --- /dev/null +++ b/tests/test_fleet.py @@ -0,0 +1,1064 @@ +"""The MDM dialect, against a stubbed transport + +What matters here is the ORDER and the restraint: the policy has to be in force before anything +installs, and an unchanged policy must not be re-uploaded, because a policy rewritten on every +pass never settles long enough for the device to finish installing anything. +""" + +import dataclasses +import http.client +import json +import logging +import re +import ssl +import urllib.error +import urllib.request +from typing import Any, Self +from urllib.parse import parse_qsl, urlsplit + +import pytest + +from odmdm_connector import __version__ +from odmdm_connector import fleet as fleet_module +from odmdm_connector.fleet import FleetError, FleetMdm, authority_name +from odmdm_connector.icon import launcher_icon +from odmdm_connector.template import App, Certificate, LinkApp, MdmTemplate + +TEMPLATE = MdmTemplate( + apps=( + App(package="com.example.one", preinstall=True, config={"k": "v"}), + App(package="com.example.two", preinstall=False), + ), + policy={"defaultPermissionPolicy": "GRANT"}, +) + + +@dataclasses.dataclass(frozen=True) +class Url: + path: str + params: dict[str, str] + + +@dataclasses.dataclass(frozen=True) +class Request: + """What the fake Fleet reads of a request""" + + method: str + url: Url + headers: dict[str, str] + content: bytes + + +_dumps = json.dumps + + +class Response: + """An answer of the fake Fleet, read as the real opener's answer is""" + + def __init__(self, status: int, json: Any = None, text: str = "") -> None: + self.status = status + self.content = _dumps(json).encode() if json is not None else text.encode() + + def read(self) -> bytes: + return self.content + + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc: object) -> None: + return None + + +class _Fleet: + """A Fleet that records what it was told, in order""" + + def __init__(self) -> None: + self.calls: list[tuple[str, str]] = [] + self.titles: list[dict[str, Any]] = [] + self.profiles: list[dict[str, Any]] = [] + #: When an upload lands. Fleet lists a profile's created_at to the microsecond and its + #: updated_at to the second (a live Fleet 4.90.1). + self.now = "2026-11-20T21:02:44.458685Z" + self.certificates: list[dict[str, Any]] = [] + self.hosts: list[dict[str, Any]] = [] + self.web_apps: list[dict[str, Any]] = [] + self.authorities: list[dict[str, Any]] = [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] + self.teams: list[dict[str, Any]] = [{"id": 7, "name": "rmscep"}] + self._next_id = 100 + + def handler(self, request: Request) -> Response: + path = request.url.path + self.calls.append((request.method, path)) + if path.endswith("/hosts") and request.method == "GET": + # Fleet answers one page at a time, the first being page 0 + per_page = int(request.url.params.get("per_page", "100")) + first = int(request.url.params.get("page", "0")) * per_page + return Response(200, json={"hosts": [{"id": h["id"]} for h in self.hosts[first : first + per_page]]}) + if path.endswith("/device_mapping") and request.method == "PUT": + # The name shows in the host detail as its IdP user, which is what the certificate reads + found = next(h for h in self.hosts if h["id"] == int(path.split("/")[-2])) + found["end_users"] = [{"idp_username": json.loads(request.content)["email"], "idp_info_updated_at": None}] + return Response(200, json={}) + if path.endswith("/resend") and request.method == "POST": + # Fleet finds the template through the host's own row, so a host without one is not + # found (read in Fleet 4.90.1's source). A row still pending is refused, and any other + # starts over as pending; the answer has no body (both seen on a live Fleet 4.90.1). + found = next(h for h in self.hosts if h["id"] == int(path.split("/")[-4])) + template = int(path.split("/")[-2]) + rows = [ + r + for r in found["mdm"]["profiles"] + if r.get("certificate_template_id") == template and r["operation_type"] == "install" + ] + if not rows: + return Response(404, json={"message": "Resource Not Found"}) + if rows[0]["status"] == "pending": + return Response( + 400, + json={ + "message": "Bad request", + "errors": [{"name": "base", "reason": "Couldn't resend pending certificate template."}], + }, + ) + rows[0].update(status="pending", detail="") + return Response(200) + if "/hosts/" in path and request.method == "GET": + which = int(path.rsplit("/", 1)[-1]) + return Response(200, json={"host": next(h for h in self.hosts if h["id"] == which)}) + if path.endswith("/certificate_authorities") and request.method == "GET": + # Fleet's listing omits the url; only the detail carries it. Mirrored so a check + # that reads the url off the listing fails here too. + return Response( + 200, + json={ + "certificate_authorities": [{k: v for k, v in a.items() if k != "url"} for a in self.authorities] + }, + ) + if "/certificate_authorities/" in path and request.method == "GET": + which = int(path.rsplit("/", 1)[-1]) + matching = [a for a in self.authorities if a["id"] == which] + return Response(200, json=matching[0] if matching else {}) + if path.endswith("/certificate_authorities") and request.method == "POST": + body = json.loads(request.content)["custom_scep_proxy"] + self._next_id += 1 + made = {"id": self._next_id, "name": body["name"], "url": body["url"], "challenge": body["challenge"]} + self.authorities.append(made) + return Response(200, json={"certificate_authority": made}) + if "/certificate_authorities/" in path and request.method == "PATCH": + which = int(path.rsplit("/", 1)[-1]) + body = json.loads(request.content)["custom_scep_proxy"] + if "name" in body: + # Fleet reads a name on a PATCH as a rename and refuses it as a conflict with + # the authority's own name. Measured against a live Fleet 4.90.1. + return Response(409, json={"message": "Conflict"}) + for authority in self.authorities: + if authority["id"] == which: + authority.update(body) + return Response(200, json={}) + if path.endswith("/certificates") and request.method == "GET": + # A team's own templates; one a test put there without a team is every team's + team = int(request.url.params.get("team_id", "0")) + return Response( + 200, json={"certificates": [c for c in self.certificates if c.get("team_id", team) == team]} + ) + if path.endswith("/certificates") and request.method == "POST": + body = json.loads(request.content) + self._next_id += 1 + made = { + "id": self._next_id, + "name": body["name"], + "team_id": body["team_id"], + "subject_name": body["subject_name"], + "certificate_authority_id": body["certificate_authority_id"], + } + self.certificates.append(made) + return Response(200, json=made) + if "/certificates/" in path and request.method == "DELETE": + gone = int(path.rsplit("/", 1)[-1]) + self.certificates = [c for c in self.certificates if c["id"] != gone] + return Response(200, json={}) + if path == "/api/latest/fleet/teams" and request.method == "GET": + return Response(200, json={"teams": self.teams}) + if path == "/api/latest/fleet/teams" and request.method == "POST": + self._next_id += 1 + made = {"id": self._next_id, "name": json.loads(request.content)["name"]} + self.teams.append(made) + return Response(200, json={"team": made}) + if path.endswith("/software/titles"): + # Fleet scopes the listing to one team. A stub that ignored team_id would let a + # lookup find another team's app and call that a pass. + wanted_team = request.url.params.get("team_id") + listed = [t for t in self.titles if wanted_team is None or str(t.get("team_id")) == str(wanted_team)] + return Response(200, json={"software_titles": listed}) + if path.endswith("/software/web_apps"): + # Publishing the SAME url twice yields TWO package names: observed against the real + # Fleet, where one url gave x023e... and then xb017.... Google does not dedupe by + # url, which is what makes every re-run leave a permanent orphan behind. + body = request.content.decode("utf-8", "replace") + url_match = re.search(r'name="url"\r?\n\r?\n([^\r\n]+)', body) + title_match = re.search(r'name="title"\r?\n\r?\n([^\r\n]+)', body) + wanted = url_match.group(1) if url_match else "" + asked = title_match.group(1) if title_match else "" + if len(asked) >= 30: + # Google refuses a web app title of 30 characters or more, as a bare 400. + return Response(400, json={"message": "Couldn't create. Please check the provided data"}) + if any(a["title"] == asked for a in self.web_apps): + # Fleet refuses a name already published to the enterprise, whatever team it is + # in and even if its team is gone. Publishing cannot be undone. + return Response(409, json={"message": "Web app with this name already exists in this fleet"}) + self._next_id += 1 + pkg = f"com.google.enterprise.webapp.x{self._next_id:08x}" + self.web_apps.append( + {"app_store_id": pkg, "url": wanted, "title": title_match.group(1) if title_match else ""} + ) + return Response(200, json={"app_store_id": pkg}) + if path.endswith("/app_store_app") and request.method == "PATCH": + body = json.loads(request.content) + title_id = int(path.split("/")[-2]) + for title in self.titles: + if title["id"] == title_id and "display_name" in body: + title["display_name"] = body["display_name"] + return Response(200, json={"app_store_app": {}}) + if path.endswith("/software/app_store_apps"): + # This is what puts an app in a team. A new web app is listed under its package name, + # not its title, until a device reports it: seen on the real Fleet. + body = json.loads(request.content) + self._next_id += 1 + self.titles.append( + { + "id": self._next_id, + "name": body["app_store_id"], + "display_name": "", + "team_id": body.get("team_id"), + "app_store_app": {"app_store_id": body["app_store_id"]}, + } + ) + return Response(200, json={"software_title_id": self._next_id}) + if path.endswith("/configuration_profiles"): + if request.method == "GET": + return Response( + 200, json={"profiles": [{k: v for k, v in p.items() if k != "raw"} for p in self.profiles]} + ) + # An upload the MDM keeps, so a second pass can see it is already there. Without + # this the adapter is right to upload again: a profile that has gone missing must + # be restored whatever we remember pushing. + raw = re.search(rb"application/json\r\n\r\n(.*)\r\n--", request.content, re.DOTALL) + assert raw, "the policy must be uploaded as JSON" + self.profiles.append( + { + "name": "rmscep-policy", + "profile_uuid": f"uuid-{len(self.profiles)}", + "created_at": self.now, + "updated_at": self.now.split(".")[0] + "Z", + "raw": json.loads(raw.group(1)), + } + ) + return Response(200, json={}) + if "/configuration_profiles/" in path and request.method == "GET": + # Only alt=media answers with the policy; without it Fleet sends metadata. + found = next(p for p in self.profiles if p["profile_uuid"] == path.rsplit("/", 1)[-1]) + media = request.url.params.get("alt") == "media" + return Response(200, json=found["raw"] if media else {"name": found["name"]}) + if "/configuration_profiles/" in path and request.method == "DELETE": + self.profiles.clear() + return Response(200, json={}) + if "/app_store_app" in path or path.endswith("/setup_experience/software"): + return Response(200, json={}) + return Response(200, json={}) + + +class _Opener: + """The opener, answering with a handler instead of the network""" + + def __init__(self, handler: Any) -> None: + self.handler = handler + self.sent: list[urllib.request.Request] = [] + + def open(self, request: urllib.request.Request, timeout: float) -> Any: + self.sent.append(request) + parts = urlsplit(request.full_url) + return self.handler( + Request( + request.get_method(), + Url(parts.path, dict(parse_qsl(parts.query))), + {name.lower(): value for name, value in request.header_items()}, + request.data if isinstance(request.data, bytes) else b"", + ) + ) + + +def _answering(handler: Any, monkeypatch: pytest.MonkeyPatch) -> _Opener: + opener = _Opener(handler) + monkeypatch.setattr(fleet_module, "_OPENER", opener) + return opener + + +def _mdm(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> FleetMdm: + # Looked up on every request, so a test can swap the handler after this + _answering(lambda request: fleet.handler(request), monkeypatch) + return FleetMdm("https://mdm.test", "token") + + +def test_the_policy_lands_before_anything_installs(monkeypatch: pytest.MonkeyPatch) -> None: + """A permission grant only applies to an app that installs while it is already in force + + Land it late and the device comes up facing a permission wizard, with a certificate no app + is allowed to see. + """ + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + + paths = [p for _, p in fleet.calls] + profile = next(i for i, p in enumerate(paths) if p.endswith("/configuration_profiles")) + install = next(i for i, p in enumerate(paths) if p.endswith("/software/app_store_apps")) + assert profile < install, f"policy must precede installs, got {paths}" + + +def test_only_the_chosen_apps_install_at_enrolment(monkeypatch: pytest.MonkeyPatch) -> None: + """The rest stay available on demand rather than lengthening the enrolment burst""" + fleet = _Fleet() + result = _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + assert result["preinstall"] == ["com.example.one"] + assert len(result["assigned"]) == 2 + + +def _policy_uploads(fleet: _Fleet) -> int: + return len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) + + +def test_an_unchanged_policy_is_not_rewritten(monkeypatch: pytest.MonkeyPatch) -> None: + """Measured: a policy rewritten every pass never settles and nothing ever installs + + Each run of the command is a new process, so nothing from the last run can be remembered. + """ + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + uploads_after_first = _policy_uploads(fleet) + _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + assert _policy_uploads(fleet) == uploads_after_first, "the same policy must not be uploaded twice" + + +def test_a_changed_policy_replaces_the_old_one(monkeypatch: pytest.MonkeyPatch) -> None: + """Otherwise an edited template would look applied and change nothing on a phone""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + changed = MdmTemplate(apps=TEMPLATE.apps, policy={"defaultPermissionPolicy": "PROMPT"}) + _mdm(fleet, monkeypatch).apply("rmscep", changed) + assert [p["raw"] for p in fleet.profiles] == [changed.policy] + + +def test_force_reaches_a_host_that_just_joined(monkeypatch: pytest.MonkeyPatch) -> None: + """Fleet can overwrite a new host's policy with a bare one, and never sends ours again by itself""" + fleet = _Fleet() + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", TEMPLATE) + before = _policy_uploads(fleet) + mdm.apply("rmscep", TEMPLATE, force_policy=True) + assert _policy_uploads(fleet) == before + 1 + + +def test_a_refusal_is_reported_not_swallowed(monkeypatch: pytest.MonkeyPatch) -> None: + """Applying half a template is worse than applying none""" + _answering(lambda request: Response(403, text="nope"), monkeypatch) + with pytest.raises(FleetError): + FleetMdm("https://mdm.test", "token").apply("rmscep", TEMPLATE) + + +@pytest.mark.parametrize("upload", [False, True]) +def test_a_token_fleet_does_not_accept_is_said_in_plain_words(monkeypatch: pytest.MonkeyPatch, upload: bool) -> None: + """A token from a signed-in account ends with that sign-in, days later: the operator must be told what to do""" + _answering(lambda request: Response(401, json={"message": "Authentication required"}), monkeypatch) + mdm = FleetMdm("https://mdm.test", "token") + + with pytest.raises(FleetError, match="the API token is not accepted.*give a new one") as raised: + if upload: + mdm._upload("/api/latest/fleet/configuration_profiles", {}, "policy.json", b"{}", "profile") + else: + mdm.team_id("Deploy App") + + assert "Authentication required" not in str(raised.value) + + +def test_the_launcher_icon_is_a_valid_png() -> None: + """Without one the web app is accepted and then never published, and every install says NOT_FOUND""" + png = launcher_icon() + assert png[:8] == b"\x89PNG\r\n\x1a\n" + width = int.from_bytes(png[16:20], "big") + height = int.from_bytes(png[20:24], "big") + assert width == height == 512, "square and at least 512x512 is enforced" + + +def test_the_link_app_is_offered_alongside_the_others(monkeypatch: pytest.MonkeyPatch) -> None: + """It is a browser shortcut, so it only works if the browser is installed too""" + fleet = _Fleet() + monkeypatch.setattr(FleetMdm, "ensure_link_app", lambda self, team, title, url: "com.google.enterprise.webapp.test") + with_link = MdmTemplate(apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp("Deploy App", "https://x/")) + result = _mdm(fleet, monkeypatch).apply("rmscep", with_link) + assert "com.google.enterprise.webapp.test" in result["preinstall"] + + +def test_the_certificate_template_is_stated_before_anything_else(monkeypatch: pytest.MonkeyPatch) -> None: + """Its subject names the device, which becomes its callsign + + So it is configuration that gets reviewed and deployed, not something typed into a console. + """ + fleet = _Fleet() + with_cert = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR,OU=$OTHER", authority="RMSCEP"), + ) + _mdm(fleet, monkeypatch).apply("rmscep", with_cert) + paths = [p for _, p in fleet.calls] + assert any(p.endswith("/certificates") for p in paths), "the template must be stated" + cert = next(i for i, p in enumerate(paths) if p.endswith("/certificates")) + install = next(i for i, p in enumerate(paths) if p.endswith("/software/app_store_apps")) + assert cert < install + + +def test_an_unknown_authority_is_named_rather_than_guessed(monkeypatch: pytest.MonkeyPatch) -> None: + """A template pointing at an authority that is not there would issue nothing, silently""" + fleet = _Fleet() + with_cert = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR", authority="NOT-THERE"), + ) + with pytest.raises(FleetError, match="NOT-THERE"): + _mdm(fleet, monkeypatch).apply("rmscep", with_cert) + + +def test_an_unchanged_certificate_template_is_left_alone(monkeypatch: pytest.MonkeyPatch) -> None: + """Recreating it re-asks every device in the team, so it is not done for nothing""" + fleet = _Fleet() + with_cert = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR,OU=$OTHER", authority="RMSCEP"), + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", with_cert) + before = len([1 for method, path in fleet.calls if path.endswith("/certificates") and method == "POST"]) + mdm.apply("rmscep", with_cert) + after = len([1 for method, path in fleet.calls if path.endswith("/certificates") and method == "POST"]) + assert after == before, "an unchanged template must not be recreated" + + +def test_a_changed_template_on_a_team_without_devices_is_replaced(monkeypatch: pytest.MonkeyPatch) -> None: + """There is no update in place, and the name has to survive as the keystore alias""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) + changed = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$OTHER", authority="RMSCEP"), + ) + _mdm(fleet, monkeypatch).apply("rmscep", changed) + + assert [(c["name"], c["subject_name"]) for c in fleet.certificates] == [("rmscep", "CN=$OTHER")] + + +def test_a_changed_template_on_a_team_with_devices_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: + """Measured: every device deletes its certificate, asks again, and is refused its own name""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) + fleet.hosts = [_host(1, "verified", "OTTER1")] + fleet.calls.clear() + changed = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$OTHER", authority="RMSCEP"), + ) + + with pytest.raises(FleetError, match="1 devices in team 7"): + _mdm(fleet, monkeypatch).apply("rmscep", changed) + + assert not [call for call in fleet.calls if call[0] == "DELETE"] + assert fleet.certificates[0]["subject_name"] == "CN=$VAR,OU=$OTHER" + + +def _host( + host_id: int, status: str = "", name: str = "", detail: str = "", enrolled: str = "2026-11-01T19:38:12Z" +) -> dict[str, Any]: + """A phone as Fleet's host detail shows it, its certificate row left out when there is no status + + The policy's row is there too, so that only the certificate's row is read as the certificate. + """ + rows: list[dict[str, Any]] = [ + {"profile_uuid": "g4bb", "name": "rmscep-policy", "status": "verified", "operation_type": "install"} + ] + if status: + rows.append( + { + "profile_uuid": "fleet-host-certificate-template", + "name": "rmscep", + "status": status, + "operation_type": "install", + "detail": detail, + "certificate_template_id": 81, + } + ) + return { + "id": host_id, + "hardware_model": "Google sdk_gphone64_arm64", + "last_enrolled_at": enrolled, + "end_users": [{"idp_username": name, "idp_info_updated_at": None}] if name else [], + "mdm": {"profiles": rows}, + } + + +def test_a_resend_refused_for_another_reason_is_reported(monkeypatch: pytest.MonkeyPatch) -> None: + """Only a request still pending needs nothing; a host with no request at all is not found""" + fleet = _Fleet() + fleet.hosts = [_host(31)] + + with pytest.raises(FleetError, match="answered 404"): + _mdm(fleet, monkeypatch).resend(31, 81) + + +def _with_cert(authority: str = "RMSCEP") -> MdmTemplate: + """A template that asks for a certificate, which is what drags the authority in""" + return MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR,OU=$OTHER", authority=authority), + ) + + +def test_a_fresh_mdm_gets_the_authority_created(monkeypatch: pytest.MonkeyPatch) -> None: + """Pointing the MDM at us is configuration, and Fleet lets us do it, so nobody should type it + + Without this a deployment is not set up by running one command: it is one command plus a + console, and the console step is the one people get wrong. + """ + fleet = _Fleet() + fleet.authorities = [] + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://new.test/scep", challenge="not-a-secret") + created = [c for c in fleet.calls if c == ("POST", "/api/latest/fleet/certificate_authorities")] + assert created, "the authority should have been created" + assert fleet.authorities[0]["url"] == "https://new.test/scep" + + +def test_an_authority_already_pointing_at_us_is_left_alone(monkeypatch: pytest.MonkeyPatch) -> None: + """Without a challenge to hand over, rewriting it is churn on something every device depends on""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://deployment.test/scep") + touched = [c for c in fleet.calls if c[0] in ("POST", "PATCH") and "certificate_authorities" in c[1]] + assert not touched, "an authority already pointing at us must not be rewritten" + + +def test_a_new_windows_challenge_reaches_an_authority_already_pointing_at_us( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Every enrolment window has a new challenge, and Fleet never shows the old one to compare""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply( + "rmscep", _with_cert(), scep_url="https://deployment.test/scep", challenge="new-window" + ) + assert len(fleet.authorities) == 1 + assert fleet.authorities[0]["challenge"] == "new-window" + assert fleet.authorities[0]["url"] == "https://deployment.test/scep" + + +def test_an_authority_is_named_after_its_deploy_app() -> None: + """Fleet takes letters, digits and underscores only""" + assert authority_name("https://golden-monkey.example.fi/scep") == "ODMDM_GOLDEN_MONKEY" + assert authority_name("https://North.example.fi/scep") == "ODMDM_NORTH" + + +def test_a_second_deploy_app_gets_an_authority_and_a_team_of_its_own(monkeypatch: pytest.MonkeyPatch) -> None: + """One Fleet serves several Deploy Apps, and the first one's authority, team and template stay as they are""" + fleet = _Fleet() + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="first") + first = [dict(c) for c in fleet.certificates] + + mdm.apply("second DeployApp", _with_cert(""), scep_url="https://second.test/scep", challenge="second") + + assert [(a["name"], a["url"], a["challenge"]) for a in fleet.authorities] == [ + ("RMSCEP", "https://deployment.test/scep", "first"), + ("ODMDM_SECOND", "https://second.test/scep", "second"), + ] + assert [team["name"] for team in fleet.teams] == ["rmscep", "second DeployApp"] + assert fleet.certificates[: len(first)] == first + [made] = fleet.certificates[len(first) :] + assert (made["team_id"], made["certificate_authority_id"]) == (fleet.teams[1]["id"], fleet.authorities[1]["id"]) + + +def test_an_authority_under_the_old_shared_name_is_found_by_its_address(monkeypatch: pytest.MonkeyPatch) -> None: + """Every Deploy App's authority was once RMSCEP: a template that names none must not make a second one + + A second one would get the team's template replaced, and every phone asked again under a taken name. + """ + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c9") + + assert [(a["id"], a["name"], a["challenge"]) for a in fleet.authorities] == [(3, "RMSCEP", "c9")] + assert [c["certificate_authority_id"] for c in fleet.certificates] == [3] + + +def test_an_authority_made_by_hand_is_found_by_its_address(monkeypatch: pytest.MonkeyPatch) -> None: + """Whatever it was called in Fleet's console; another Deploy App's is asked and left alone""" + fleet = _Fleet() + fleet.authorities = [ + {"id": 4, "name": "OTHER_UNIT", "url": "https://other.test/scep"}, + {"id": 9, "name": "Typed_by_hand", "url": "https://deployment.test/scep"}, + ] + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c9") + + assert [a.get("challenge") for a in fleet.authorities] == [None, "c9"] + assert [c["certificate_authority_id"] for c in fleet.certificates] == [9] + + +def test_the_likely_names_are_asked_for_their_address_first(monkeypatch: pytest.MonkeyPatch) -> None: + """The listing has no address, so each one costs a request: another Deploy App's is not asked""" + fleet = _Fleet() + fleet.authorities.insert(0, {"id": 4, "name": "OTHER_UNIT", "url": "https://other.test/scep"}) + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep") + + assert ("GET", "/api/latest/fleet/certificate_authorities/3") in fleet.calls + assert ("GET", "/api/latest/fleet/certificate_authorities/4") not in fleet.calls + + +def test_an_authority_of_another_kind_has_no_address_to_ask_for(monkeypatch: pytest.MonkeyPatch) -> None: + fleet = _Fleet() + fleet.authorities = [{"id": 2, "name": "DIGI", "type": "digicert"}] + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c") + + assert ("GET", "/api/latest/fleet/certificate_authorities/2") not in fleet.calls + assert [a["name"] for a in fleet.authorities] == ["DIGI", "ODMDM_DEPLOYMENT"] + + +def test_a_template_may_name_a_new_authority(monkeypatch: pytest.MonkeyPatch) -> None: + """For two Deploy Apps whose hosts begin alike""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("north", _with_cert("NORTH_2"), scep_url="https://north.other.test/scep") + + assert [(a["name"], a["url"]) for a in fleet.authorities[1:]] == [("NORTH_2", "https://north.other.test/scep")] + + +def test_a_name_that_serves_another_address_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: + """Two Deploy Apps whose hosts begin alike would share a name, and it is never repointed""" + fleet = _Fleet() + fleet.authorities = [{"id": 4, "name": "ODMDM_NORTH", "url": "https://north.example.fi/scep"}] + with pytest.raises(FleetError) as raised: + _mdm(fleet, monkeypatch).apply("north", _with_cert(""), scep_url="https://north.other.test/scep", challenge="c") + + assert str(raised.value) == ( + "certificate authority ODMDM_NORTH already serves https://north.example.fi/scep: give this Deploy App a " + "template that names another authority, or delete that authority in Fleet if the Deploy App moved" + ) + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" + + +def test_a_team_of_another_deploy_app_is_refused_even_when_empty(monkeypatch: pytest.MonkeyPatch) -> None: + """Replacing its template would enrol that Deploy App's phones into this one""" + fleet = _Fleet() + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep") + before = [dict(c) for c in fleet.certificates] + fleet.calls.clear() + + with pytest.raises(FleetError) as raised: + mdm.apply("rmscep", _with_cert(""), scep_url="https://second.test/scep", challenge="c2") + + assert str(raised.value) == ( + "the team takes its certificates from authority RMSCEP, which serves https://deployment.test/scep, not " + "https://second.test/scep, so nothing was changed. If that authority is this Deploy App's, correct its " + "address in Fleet; if not, choose another team." + ) + assert fleet.certificates == before + assert fleet.authorities == [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet, no authority made beside it" + + +@pytest.mark.parametrize( + "held", ["https://deployment.test/scep/", "https://deployment.test:443/scep", "https://deployment.test/SCEP"] +) +def test_an_address_that_differs_by_little_is_refused_aloud(monkeypatch: pytest.MonkeyPatch, held: str) -> None: + """An authority typed by hand with a slash too many is not this address + + Making a new one beside it would give that one the challenge, and the team's phones, which ask + the one their template is bound to, would be refused with nothing to show why. + """ + fleet = _Fleet() + fleet.authorities = [{"id": 3, "name": "Typed_by_hand", "url": held}] + fleet.certificates = [ + {"id": 81, "name": "rmscep", "subject_name": "CN=$VAR,OU=$OTHER", "certificate_authority_id": 3} + ] + + with pytest.raises(FleetError, match="which serves " + re.escape(held) + ", not https://deployment.test/scep"): + _mdm(fleet, monkeypatch).apply( + "rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c2" + ) + + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" + + +def test_the_challenge_goes_to_the_authority_the_team_is_bound_to(monkeypatch: pytest.MonkeyPatch) -> None: + """Two authorities typed for one address: the team's phones ask only the one its template names""" + fleet = _Fleet() + fleet.authorities = [ + {"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}, + {"id": 9, "name": "Second_of_the_same", "url": "https://deployment.test/scep"}, + ] + fleet.certificates = [ + {"id": 81, "name": "rmscep", "subject_name": "CN=$VAR,OU=$OTHER", "certificate_authority_id": 9} + ] + + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c2") + + assert [a.get("challenge") for a in fleet.authorities] == [None, "c2"] + assert [c["certificate_authority_id"] for c in fleet.certificates] == [9], "the template was left as it is" + + +def test_an_authority_that_serves_another_deploy_app_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: + """A template that names an authority gets that one or none + + Repointing it would send the phones of the Deploy App it serves to the one connected now. + """ + fleet = _Fleet() + with pytest.raises(FleetError) as raised: + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://moved.test/scep", challenge="rotated") + + assert str(raised.value) == ( + "certificate authority RMSCEP already serves https://deployment.test/scep: give this Deploy App a " + "template that names another authority, or delete that authority in Fleet if the Deploy App moved" + ) + assert fleet.authorities == [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" + + +def test_an_authority_kept_with_an_upper_case_host_is_still_ours(monkeypatch: pytest.MonkeyPatch) -> None: + """An earlier version kept the host as the line had it, and a host compares without case""" + fleet = _Fleet() + fleet.authorities[0]["url"] = "HTTPS://Deployment.TEST/scep" + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://deployment.test/scep", challenge="c3") + + assert fleet.authorities[0]["challenge"] == "c3" + + +def test_a_refused_authority_makes_no_team(monkeypatch: pytest.MonkeyPatch) -> None: + """A second Deploy App naturally gets a team of its own, and a refusal must not leave it behind empty""" + fleet = _Fleet() + with pytest.raises(FleetError, match="already serves https://deployment.test/scep"): + _mdm(fleet, monkeypatch).apply("Second unit", _with_cert(), scep_url="https://second.test/scep", challenge="c2") + + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" + + +def test_without_a_scep_url_the_authority_must_already_exist(monkeypatch: pytest.MonkeyPatch) -> None: + """The path for an MDM we cannot create one in: state what is there, or say what is missing""" + fleet = _Fleet() + fleet.authorities = [] + with pytest.raises(FleetError, match="RMSCEP"): + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) + assert not [c for c in fleet.calls if c[0] != "GET"], "no team was made for it" + + +def test_without_a_scep_url_a_template_must_name_its_authority(monkeypatch: pytest.MonkeyPatch) -> None: + fleet = _Fleet() + with pytest.raises(FleetError, match="names no certificate authority"): + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert("")) + assert not fleet.calls + + +def test_applying_twice_publishes_one_web_app(monkeypatch: pytest.MonkeyPatch) -> None: + """A re-run reuses the launcher instead of leaving another permanent one behind + + Google does not dedupe by url: the same url published twice came back as two package names, + so every mdm-apply added another launcher to the team. Fleet cannot delete a web app, so each + one is permanent, and the third publish of a name is refused outright. + """ + fleet = _Fleet() + template = MdmTemplate( + apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp(title="Deploy App", url="https://same.test/") + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", template) + mdm.apply("rmscep", template) + + assert len(fleet.web_apps) == 1, f"the re-run must not publish again, got {[a['title'] for a in fleet.web_apps]}" + launchers = [t for t in fleet.titles if t["display_name"].startswith("Deploy App")] + assert len(launchers) == 1, "the team must end up with one launcher, not one per run" + + +def test_a_wiped_team_says_what_is_wrong_instead_of_just_409(monkeypatch: pytest.MonkeyPatch) -> None: + """A name published to a team that no longer exists must fail legibly + + A full fresh run deletes the team and makes it again. The web app outlives it, because Fleet + cannot delete one, so publishing the same name answers 409. Whether Fleet still lists an app + whose team is gone is not something this stub can decide, so the contract tested here is the + one that holds either way: when it cannot be found, the operator is told the name is taken + and what to do about it, rather than being handed a bare conflict. + """ + fleet = _Fleet() + template = MdmTemplate( + apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp(title="Deploy App", url="https://same.test/") + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", template) + published = fleet.web_apps[-1]["app_store_id"] + + # The team is deleted and recreated: its software titles go with it, the web app does not. + fleet.titles = [t for t in fleet.titles if (t.get("app_store_app") or {}).get("app_store_id") != published] + + with pytest.raises(FleetError) as caught: + mdm.apply("rmscep", template) + said = str(caught.value) + assert "Deploy App (same)" in said, f"it must name the title that is taken, said: {said}" + assert "deleted" in said.lower() or "cannot be deleted" in said.lower(), f"it must say why: {said}" + assert "display name" in said.lower(), f"it must offer the recoverable case before giving up: {said}" + assert len(fleet.web_apps) == 1, "it must not have published a second app before failing" + + +def test_the_launcher_points_at_this_deployment_not_the_last_one(monkeypatch: pytest.MonkeyPatch) -> None: + """The web app is identified by the host it serves, never by a bare title + + Fleet cannot read, change or delete a web app's url, so reusing one because the title matched + kept a decommissioned deployment's link and handed every device an icon that opened a host + which no longer existed. Everything else about the apply was correct, which is what made it + so quiet. The deployment that replaced it reused the team name too, so the team is no help: + the host in the title is what tells the two apart. + """ + fleet = _Fleet() + template = MdmTemplate( + apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp(title="Deploy App", url="https://old.test/") + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", template) + first = fleet.web_apps[-1]["app_store_id"] + + moved = MdmTemplate( + apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp(title="Deploy App", url="https://new.test/") + ) + mdm.apply("rmscep", moved) + second = fleet.web_apps[-1]["app_store_id"] + + assert fleet.web_apps[-1]["url"] == "https://new.test/", "the moved deployment must publish its own url" + assert second != first, "same title, different url: it must not reuse the old app" + + +def test_the_launcher_title_names_the_deployment_and_fits() -> None: + """Google refuses a web app title of 30 characters or more, and a full host rarely fits""" + title = FleetMdm._published_title("Deploy App", "https://mtls.quiet-otter.example.fi/") + assert title == "Deploy App (quiet-otter)" + long_name = FleetMdm._published_title("Deploy App", "https://mtls.thoughtful-hippopotamus.example.org/") + assert len(long_name) < 30 + assert long_name.startswith("Deploy App (thoughtful") + + +@pytest.mark.parametrize( + ("created", "updated", "enrolled", "later"), + [ + ("2026-11-20T21:02:44.458685Z", "2026-11-20T21:02:44Z", "2026-11-20T21:02:44Z", 0), + ("2026-11-20T21:02:44.458685Z", "2026-11-20T21:02:44Z", "2026-11-20T21:10:02Z", 1), + ("2026-11-20T21:02:44.458685Z", None, "2026-11-20T21:02:44Z", 0), + ("2026-11-20T21:02:44.458685Z", None, "2026-11-20T21:02:45Z", 1), + ("2026-11-20T21:02:44.458685Z", "2026-11-20T21:20:00Z", "2026-11-20T21:10:02Z", 0), + ], +) +def test_enrolment_and_upload_are_compared_as_times( + monkeypatch: pytest.MonkeyPatch, created: str, updated: str | None, enrolled: str, later: int +) -> None: + """Fleet writes created_at to the microsecond, updated_at and last_enrolled_at to the second + + As strings, "...44Z" sorts after "...44.458685Z", so a phone that enrolled before the upload + would read as later. updated_at is the last upload when Fleet gives it. + """ + fleet = _Fleet() + profile = {"name": "rmscep-policy", "profile_uuid": "g4bb", "created_at": created, "raw": TEMPLATE.policy} + fleet.profiles = [profile | ({"updated_at": updated} if updated else {})] + fleet.hosts = [_host(31, enrolled=enrolled), _host(32, enrolled="")] + mdm = _mdm(fleet, monkeypatch) + + assert mdm.resend_policy(7, mdm.phones(7, "rmscep")) == later + assert _policy_uploads(fleet) == later + assert [p["raw"] for p in fleet.profiles] == [TEMPLATE.policy] + + +def test_a_policy_without_a_time_is_reported(monkeypatch: pytest.MonkeyPatch) -> None: + """Rather than ending a command that has already named phones in a traceback""" + fleet = _Fleet() + fleet.profiles = [{"name": "rmscep-policy", "profile_uuid": "g4bb", "raw": TEMPLATE.policy}] + fleet.hosts = [_host(31)] + mdm = _mdm(fleet, monkeypatch) + + with pytest.raises(FleetError, match="the time '' could not be read"): + mdm.resend_policy(7, mdm.phones(7, "rmscep")) + assert not _policy_uploads(fleet) + + +# --- the transport -------------------------------------------------------------- + +TOKEN = "secret-token-4f2a" + + +@pytest.mark.parametrize("url", ["http://mdm.example.fi", "file:///etc", "ftp://192.0.2.10"]) +def test_only_https_is_sent(monkeypatch: pytest.MonkeyPatch, url: str) -> None: + """The token goes with every request, so it must not cross the network readable""" + opener = _answering(lambda request: Response(200, json={}), monkeypatch) + + with pytest.raises(FleetError, match="must start with https://"): + FleetMdm(url, TOKEN).team_id("rmscep") + + assert not opener.sent + + +def test_the_opener_only_proxies_and_speaks_https() -> None: + """No redirect is followed, no other scheme is spoken, no status is turned into an exception + + The proxy handler is there only while the environment names a proxy: without one it has nothing to open. + """ + handlers: list[object] = vars(fleet_module._OPENER)["handlers"] + + assert {type(handler) for handler in handlers} <= {urllib.request.ProxyHandler, urllib.request.HTTPSHandler} + https = next(handler for handler in handlers if isinstance(handler, urllib.request.HTTPSHandler)) + context: ssl.SSLContext = vars(https)["_context"] + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.check_hostname + + +def test_a_request_says_who_asks_and_what_it_sends(monkeypatch: pytest.MonkeyPatch) -> None: + seen: list[Request] = [] + + def answer(request: Request) -> Response: + seen.append(request) + return Response(200, json={"team": {"id": 9}}) + + _answering(answer, monkeypatch) + + assert FleetMdm("https://mdm.example.fi/", TOKEN).team_id("Ålands", create=True) == 9 + + created = seen[-1] + assert (created.method, created.url.path) == ("POST", "/api/latest/fleet/teams") + assert created.headers["authorization"] == f"Bearer {TOKEN}" + assert created.headers["user-agent"] == f"odmdm-connector/{__version__}" + assert created.headers["content-type"] == "application/json" + assert json.loads(created.content) == {"name": "Ålands"} + + +def test_an_empty_answer_is_an_empty_object(monkeypatch: pytest.MonkeyPatch) -> None: + _answering(lambda request: Response(204), monkeypatch) + assert FleetMdm("https://mdm.example.fi", TOKEN)._call("DELETE", "/api/latest/fleet/teams/9") == {} + + +@pytest.mark.parametrize("status", [301, 302, 307, 404, 500]) +def test_an_answer_outside_2xx_is_a_refusal(monkeypatch: pytest.MonkeyPatch, status: int) -> None: + """A redirect is not followed either: it would carry the token on to wherever it points""" + opener = _answering(lambda request: Response(status, text="x" * 1000), monkeypatch) + + with pytest.raises(FleetError) as raised: + FleetMdm("https://mdm.example.fi", TOKEN)._call("GET", "/api/latest/fleet/teams") + + assert str(raised.value) == f"GET /api/latest/fleet/teams answered {status}: {'x' * 800}" + assert len(opener.sent) == 1 + + +def test_an_upload_refused_says_so(monkeypatch: pytest.MonkeyPatch) -> None: + _answering(lambda request: Response(302, text="y" * 300), monkeypatch) + + with pytest.raises(FleetError) as raised: + FleetMdm("https://mdm.example.fi", TOKEN)._upload("/api/x", {}, "p.json", b"{}", "profile") + + assert str(raised.value) == f"upload to /api/x answered 302: {'y' * 200}" + + +@pytest.mark.parametrize( + "failure", + [ + urllib.error.URLError(ConnectionRefusedError(61, "Connection refused")), + urllib.error.URLError(ssl.SSLCertVerificationError("certificate verify failed")), + TimeoutError("timed out"), + ssl.SSLError("record layer failure"), + http.client.RemoteDisconnected("Remote end closed connection without response"), + ], +) +def test_an_mdm_out_of_reach_is_said_without_the_token( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, failure: Exception +) -> None: + def failing(request: Request) -> Response: + raise failure + + _answering(failing, monkeypatch) + caplog.set_level(logging.DEBUG) + + with pytest.raises(FleetError, match="^could not reach the MDM: ") as raised: + FleetMdm("https://mdm.example.fi", TOKEN).team_id("rmscep") + + assert TOKEN not in str(raised.value) + assert TOKEN not in caplog.text + + +def test_a_request_that_cannot_be_carried_is_said_without_the_token( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """http.client refuses a header with a line break in a ValueError whose text quotes it, token and all""" + + def refusing(request: Request) -> Response: + raise ValueError(f"Invalid header value {request.headers['authorization'].encode()!r}") + + _answering(refusing, monkeypatch) + caplog.set_level(logging.DEBUG) + + with pytest.raises(FleetError) as raised: + FleetMdm("https://mdm.example.fi", TOKEN).team_id("rmscep") + + assert str(raised.value) == "the MDM address or the token holds a character a request cannot carry" + assert raised.value.__cause__ is None and raised.value.__suppress_context__ + assert TOKEN not in caplog.text + + +def test_the_upload_is_a_form_with_the_file_last(monkeypatch: pytest.MonkeyPatch) -> None: + seen: list[Request] = [] + + def answer(request: Request) -> Response: + seen.append(request) + return Response(200, json={"ok": True}) + + _answering(answer, monkeypatch) + + result = FleetMdm("https://mdm.example.fi", TOKEN)._upload( + "/api/x", + {"title": "Deploy App", "url": "https://deploy.example.fi"}, + "icon.png", + b"\x89PNG", + "icon", + "image/png", + ) + + assert result == {"ok": True} + kind, _, boundary = seen[0].headers["content-type"].partition("; boundary=") + assert kind == "multipart/form-data" + assert ( + seen[0].content + == ( + f'--{boundary}\r\nContent-Disposition: form-data; name="title"\r\n\r\nDeploy App\r\n' + f'--{boundary}\r\nContent-Disposition: form-data; name="url"\r\n\r\nhttps://deploy.example.fi\r\n' + f'--{boundary}\r\nContent-Disposition: form-data; name="icon"; filename="icon.png"\r\n' + f"Content-Type: image/png\r\n\r\n" + ).encode() + + b"\x89PNG\r\n" + + f"--{boundary}--\r\n".encode() + ) + + +@pytest.mark.parametrize( + "fields, filename, content_type", + [ + ({'ti"tle': "x"}, "p.json", "application/json"), + ({"title\r\n": "x"}, "p.json", "application/json"), + ({}, 'p".json', "application/json"), + ({}, "p\n.json", "application/json"), + ({}, "p.json", "application/json\r\nX-Evil: 1"), + ], +) +def test_a_name_that_would_break_the_form_is_refused( + monkeypatch: pytest.MonkeyPatch, fields: dict[str, str], filename: str, content_type: str +) -> None: + opener = _answering(lambda request: Response(200), monkeypatch) + + with pytest.raises(ValueError, match="cannot go in a multipart header"): + FleetMdm("https://mdm.example.fi", TOKEN)._upload("/api/x", fields, filename, b"{}", "profile", content_type) + + assert not opener.sent diff --git a/tests/test_fleet_plugin.py b/tests/test_fleet_plugin.py new file mode 100644 index 0000000..b90f174 --- /dev/null +++ b/tests/test_fleet_plugin.py @@ -0,0 +1,276 @@ +"""Fleet behind the MDM contract, against the stubbed Fleet""" + +import datetime + +import pytest + +from odmdm_connector.fleet_plugin import FleetPlugin +from odmdm_connector.mdm import Mdm, MdmError, State +from odmdm_connector.settings import Settings + +from .test_fleet import Request, Response, _Fleet, _host, _mdm, _policy_uploads + +NO_NAME = "Could not replace certificate variables: host 6f1c does not have an IDP user for variable FLEET_VAR_X" +REFUSED = "SCEP enrollment failed: Enrollment failed with SCEP failInfo: badMessageCheck" +UNREACHED = "Network error during SCEP enrollment: Failed to communicate with SCEP server" +WINDOW = Settings("https://example.fi/scep", "new-window", datetime.datetime(2026, 11, 21, 14, tzinfo=datetime.UTC)) + + +@pytest.fixture +def fleet(monkeypatch: pytest.MonkeyPatch) -> _Fleet: + """A stubbed Fleet whose team has its certificate template""" + stub = _Fleet() + stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": "CN=$X", "certificate_authority_id": 3}] + _mdm(stub, monkeypatch) + return stub + + +def _plugin(**values: str) -> Mdm: + return FleetPlugin({"mdm_url": "https://mdm.test", "token": "token", "team": "rmscep", **values}) + + +@pytest.mark.parametrize( + ("status", "callsign", "detail", "state", "words"), + [ + ("", "", "", State.NO_REQUEST, ""), + ("verified", "OTTER4", "", State.READY, ""), + ("failed", "", NO_NAME, State.NEEDS_NAME, ""), + ("failed", "OTTER4", NO_NAME, State.NOT_ASKED, "ask again"), + ("failed", "OTTER4", REFUSED, State.REFUSED, "name taken or not allowed"), + ("failed", "OTTER4", UNREACHED, State.UNREACHABLE, ""), + ("failed", "OTTER4", "Something new", State.FAILED, "Something new"), + ("pending", "OTTER4", "", State.WAITING, "up to 15 minutes"), + ("delivered", "OTTER4", UNREACHED, State.WAITING, "up to 15 minutes; last time: could not reach Deploy App"), + ], +) +def test_fleets_status_and_detail_become_a_state( + fleet: _Fleet, status: str, callsign: str, detail: str, state: State, words: str +) -> None: + """Fleet's words are kept beside the state as its detail""" + fleet.hosts = [_host(31, status, callsign, detail)] + + [phone] = _plugin().phones() + + assert (phone.id, phone.callsign, phone.joined) == ("31", callsign, "2026-11-01T19:38:12Z") + assert phone.state is state + assert phone.detail.startswith(words) if words else not phone.detail + + +def _listings(fleet: _Fleet) -> int: + return len([path for _, path in fleet.calls if path.endswith("/hosts")]) + + +def test_name_answers_its_lines_and_reads_the_phones_once(fleet: _Fleet) -> None: + """Read once, and the phones checked are the ones named""" + fleet.hosts = [_host(31, "failed", detail=NO_NAME), _host(32)] + + lines = _plugin().name({"32": "OTTER5", "31": "OTTER4"}) + + assert lines == [ + "Phone 32 is OTTER5. Fleet has no certificate request for it, so nothing was sent", + "Phone 31 is OTTER4", + ] + assert _listings(fleet) == 1 + + +def test_phones_are_read_afresh_on_every_call(fleet: _Fleet) -> None: + """A refresh never shows what an earlier one read""" + fleet.hosts = [_host(31)] + plugin = _plugin() + + first = plugin.phones() + fleet.hosts.append(_host(32)) + second = plugin.phones() + + assert ([p.id for p in first], [p.id for p in second]) == (["31"], ["31", "32"]) + assert _listings(fleet) == 2 + + +@pytest.mark.parametrize("call", ["name", "ask_again"]) +def test_an_id_not_in_the_team_changes_nothing(fleet: _Fleet, call: str) -> None: + fleet.hosts = [_host(31, "failed", detail=NO_NAME)] + plugin = _plugin() + + with pytest.raises(MdmError, match="host 99 is not in the team"): + plugin.name({"99": "OTTER4"}) if call == "name" else plugin.ask_again(["99"]) + + assert not [method for method, _ in fleet.calls if method != "GET"] + + +def test_a_batch_stopped_half_way_names_the_phones_named(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.url.path.endswith("/hosts/32/certificates/81/resend"): + return Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(host, "failed", detail=NO_NAME) for host in (31, 32, 33)] + + with pytest.raises(MdmError, match="Fleet refused: POST .*/hosts/32/.* answered 500") as raised: + _plugin().name({"31": "OTTER1", "32": "OTTER2", "33": "OTTER3"}) + + assert raised.value.named == {"31": "OTTER1", "32": "OTTER2"} + assert not raised.value.unauthorized + + +def test_a_token_fleet_does_not_accept_is_marked(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """So the connector lets go of it and asks for it again""" + monkeypatch.setattr(fleet, "handler", lambda request: Response(401, json={"message": "Authentication required"})) + _mdm(fleet, monkeypatch) + + with pytest.raises(MdmError, match="Fleet refused: the API token is not accepted") as raised: + _plugin().phones() + + assert raised.value.unauthorized + + +def test_a_token_refused_while_the_policy_is_replaced_is_marked(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """The token ended between deleting the old policy and uploading the new one""" + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.method == "POST" and request.url.path.endswith("/configuration_profiles"): + return Response(401, json={"message": "Authentication required"}) + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled="2026-11-21T09:00:00Z")] + fleet.profiles = [ + {"name": "rmscep-policy", "profile_uuid": "g4bb", "created_at": "2026-11-20T21:02:44Z", "raw": {}} + ] + + with pytest.raises(MdmError, match="was being replaced in team 7 and may now be missing") as raised: + _plugin().name({"31": "OTTER1"}) + + assert raised.value.unauthorized + + +@pytest.mark.parametrize( + ("values", "says"), + [ + ({"mdm_url": ""}, "The Fleet address is missing"), + ({"mdm_url": "http://mdm.test"}, "must start with https://"), + ({"token": ""}, "The Fleet API token is missing"), + ({"team": ""}, "The Fleet team is missing"), + ], +) +def test_fleet_is_reached_only_when_configured(fleet: _Fleet, values: dict[str, str], says: str) -> None: + """Said when Fleet is first needed, so a dry run needs no token""" + plugin = _plugin(**values) + + [step] = plugin.setup(WINDOW, dry_run=True) + with pytest.raises(MdmError, match=says): + plugin.phones() + + assert step.label == "Template names 3 apps, 3 installed at enrolment" + assert "launcher link 'Deploy App' -> https://mtls.example.fi/" in step.message + assert not fleet.calls + + +def test_ask_again_without_ids_and_nobody_failed_answers_nothing(fleet: _Fleet) -> None: + fleet.hosts = [_host(31, "verified", "OTTER4")] + + assert _plugin().ask_again([]) == [] + assert not [method for method, _ in fleet.calls if method != "GET"] + + +def test_the_template_and_key_alias_are_advanced() -> None: + """Rarely changed, and the key alias never for a deployment: the window shows them only when asked""" + assert [item.key for item in FleetPlugin.fields if item.advanced] == ["template", "key_alias"] + + +def test_the_token_help_says_which_token_lasts() -> None: + """The token My account gives ends with that sign-in, as the refusal then says""" + [token] = [each for each in FleetPlugin.fields if each.key == "token"] + + assert token.help == ( + "A global admin's API token: in Fleet, My account, Get API token. That one ends with that sign-in, " + "after 5 days by default; an API-only user's does not." + ) + + +def test_the_team_is_named_after_the_deployment_by_default() -> None: + """golden-monkey.example.fi's team is golden-monkey DeployApp; it must be given, and the connector suggests it""" + [team] = [each for each in FleetPlugin.fields if each.key == "team"] + + assert team.required + assert team.default_for("golden-monkey.example.fi") == "golden-monkey DeployApp" + + +def test_a_new_window_reaches_only_this_deploy_apps_authority(fleet: _Fleet) -> None: + """On a Fleet that serves several Deploy Apps, each with a challenge of its own + + The names say nothing: the team's template is bound to authority 3, which serves this Deploy App. + """ + fleet.authorities = [ + {"id": 4, "name": "UNIT_B", "url": "https://north.example.fi/scep", "challenge": "norths"}, + {"id": 3, "name": "UNIT_A", "url": "https://example.fi/scep", "challenge": "old"}, + ] + + _plugin().set_challenge(WINDOW) + + assert [authority["challenge"] for authority in fleet.authorities] == ["norths", "new-window"] + assert [call for call in fleet.calls if call[0] != "GET"] == [ + ("PATCH", "/api/latest/fleet/certificate_authorities/3") + ] + + +def test_a_new_window_is_refused_when_the_team_asks_another_address(fleet: _Fleet) -> None: + """A Deploy App that moved, or the wrong team: said aloud, and the challenge goes nowhere""" + fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://old.example.fi/scep", "challenge": "old"}] + + with pytest.raises(MdmError) as raised: + _plugin().set_challenge(WINDOW) + + assert str(raised.value) == ( + "Fleet refused: the team takes its certificates from authority RMSCEP, which serves " + "https://old.example.fi/scep, not https://example.fi/scep, so nothing was changed. If that authority is this " + "Deploy App's, correct its address in Fleet; if not, choose another team." + ) + assert fleet.authorities == [{"id": 3, "name": "RMSCEP", "url": "https://old.example.fi/scep", "challenge": "old"}] + assert not [call for call in fleet.calls if call[0] != "GET"] + + +def test_a_new_window_before_the_team_is_made_finds_the_authority_by_its_address(fleet: _Fleet) -> None: + fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep", "challenge": "old"}] + + _plugin(team="golden-monkey DeployApp").set_challenge(WINDOW) + + assert fleet.authorities[0]["challenge"] == "new-window" + + +def test_sending_the_policy_again_makes_no_team(fleet: _Fleet) -> None: + """A repair creates nothing: a team Fleet lacks is refused before the authority or anything else is changed""" + fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep", "challenge": "old"}] + + with pytest.raises(MdmError) as raised: + list(_plugin(team="golden-monkey DeployApp").setup(WINDOW, force=True)) + + assert str(raised.value) == ( + "Fleet has no team named golden-monkey DeployApp, so nothing was changed: sending the policy again makes " + "no team. Check the team's name." + ) + assert not raised.value.unauthorized + assert not [call for call in fleet.calls if call[0] != "GET"] + assert fleet.authorities[0]["challenge"] == "old" + + +def test_setup_with_force_sends_the_unchanged_policy_again_and_no_challenge(fleet: _Fleet) -> None: + """apply --force-policy, and Send the policy again on the page: for a phone whose policy Fleet overwrote""" + fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep", "challenge": "old"}] + bare = Settings("https://example.fi/scep", "") + list(_plugin().setup(bare)) + before = _policy_uploads(fleet) + + list(_plugin().setup(bare)) + unforced = _policy_uploads(fleet) + steps = list(_plugin().setup(bare, force=True)) + + assert unforced == before, "unchanged, so not sent" + assert _policy_uploads(fleet) == before + 1 + assert steps[-1].label.startswith("Applied to team rmscep (7): ") + assert fleet.authorities[0]["challenge"] == "old" diff --git a/tests/test_manifest.py b/tests/test_manifest.py new file mode 100644 index 0000000..4b8cc9a --- /dev/null +++ b/tests/test_manifest.py @@ -0,0 +1,58 @@ +"""packaging/manifest.py: connector.json, the contract with Deploy App's MDM page""" + +import hashlib +import json +import re +from importlib.metadata import version +from pathlib import Path + +import manifest +import pytest + +RELEASE = version("odmdm-connector") + + +def test_the_manifest_names_the_mdms_built_in_and_each_file_in_a_fixed_order(tmp_path: Path) -> None: + for name in (f"odmdm-connector-{RELEASE}.pyz", f"odmdm-connector-{RELEASE}-windows-x64.exe"): + (tmp_path / name).write_bytes(name.encode()) + (tmp_path / manifest.NAME).write_text("the one written before", encoding="utf-8") + + assert manifest.main([str(tmp_path)]) == 0 + + written = json.loads((tmp_path / manifest.NAME).read_text(encoding="utf-8")) + assert written == { + "version": RELEASE, + "mdms": [{"name": "fleet", "title": "Fleet"}], + "files": [ + { + "os": system, + "arch": arch, + "file": name, + "size": len(name), + "sha256": hashlib.sha256(name.encode()).hexdigest(), + } + for system, arch, name in ( + ("windows", "x64", f"odmdm-connector-{RELEASE}-windows-x64.exe"), + ("any", "any", f"odmdm-connector-{RELEASE}.pyz"), + ) + ], + } + assert all(re.fullmatch(r"[A-Za-z0-9._+-]{1,120}", item["file"]) for item in written["files"]) + + +@pytest.mark.parametrize( + "name", ["odmdm-connector-0.0.1+1-windows-x64.exe", "odmdm-connector-macos-arm64.zip", "notes.txt", "a folder"] +) +def test_a_file_that_is_not_the_connector_s_is_named_never_skipped( + name: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + (tmp_path / f"odmdm-connector-{RELEASE}.pyz").write_bytes(b"pyz") + if name == "a folder": + (tmp_path / name).mkdir() + else: + (tmp_path / name).write_bytes(b"other") + + assert manifest.main([str(tmp_path)]) == 1 + + assert name in capsys.readouterr().err + assert not (tmp_path / manifest.NAME).exists() diff --git a/tests/test_mdm.py b/tests/test_mdm.py new file mode 100644 index 0000000..4b54ead --- /dev/null +++ b/tests/test_mdm.py @@ -0,0 +1,56 @@ +"""The MDM contract""" + +import pytest + +from odmdm_connector import mdm + + +def test_an_error_carries_the_phones_named_before_it() -> None: + """So the operator names only the rest""" + named = {"31": "OTTER1"} + + error = mdm.MdmError("stopped", named) + named["32"] = "OTTER2" + + assert str(error) == "stopped" + assert error.named == {"31": "OTTER1"} + assert not mdm.MdmError("stopped").named + + +def test_every_state_is_a_sentence_and_every_capability_is_named() -> None: + """The state's value is what the operator reads""" + assert all(state.value and state.value == state.value.strip() for state in mdm.State) + assert set(mdm.CAPABILITIES) == {"setup", "set_challenge", "ask_again", "send_policy"} + assert mdm.API_VERSION == 1 + + +def test_a_field_is_shown_unless_marked_advanced() -> None: + """The window hides a field marked advanced until asked; the command line takes it as any other""" + assert not mdm.Field("team", "Team").advanced + assert mdm.Field("key_alias", "Key alias", advanced=True).advanced + + +def test_a_default_may_name_the_deployment() -> None: + """The first label of the Deploy App's host; without a host such a default is none, and any other is itself""" + team = mdm.Field("team", "Team", default="{deployment} DeployApp") + + assert team.default_for("golden-monkey.example.fi") == "golden-monkey DeployApp" + assert team.default_for("") == "" + assert mdm.Field("key_alias", "Key alias", default="rmscep").default_for("") == "rmscep" + assert mdm.Field("plain", "Plain", default="{x} {deployment}").default_for("a.example.fi") == "{x} a" + + +@pytest.mark.parametrize( + ("host", "default"), + [ + ("Golden-Monkey.Example.fi", "golden-monkey DeployApp"), + (" golden-monkey.example.fi\n", "golden-monkey DeployApp"), + ("https://golden-monkey.example.fi", ""), + ("golden-monkey.example.fi/scep", ""), + ("golden monkey.example.fi", ""), + ("localhost", ""), + ], +) +def test_a_deployment_default_takes_only_a_plain_host_in_lower_case(host: str, default: str) -> None: + """The page and the command line give one team for one Deploy App; a host the settings would refuse gives none""" + assert mdm.Field("team", "Team", default="{deployment} DeployApp").default_for(host) == default diff --git a/tests/test_no_processes.py b/tests/test_no_processes.py new file mode 100644 index 0000000..1d715f2 --- /dev/null +++ b/tests/test_no_processes.py @@ -0,0 +1,115 @@ +"""The connector starts no process, and the test run makes sure of it""" + +import ast +import os +import subprocess +import webbrowser +from collections.abc import Callable +from pathlib import Path + +import pytest + + +@pytest.mark.parametrize( + "start", + [ + lambda: subprocess.run(["true"], check=False), + lambda: os.system("true"), + lambda: os.popen("true"), + lambda: webbrowser.open("https://example.fi"), + ], +) +def test_a_process_start_fails_the_test(start: Callable[[], object]) -> None: + with pytest.raises(RuntimeError, match="started a process"): + start() + + +#: browser.py: ruff's ban is off for the whole file, so this test holds the rule there +BROWSER = Path(__file__).parent.parent / "src" / "odmdm_connector" / "browser.py" +#: The modules browser.py may import, and the only things of webbrowser it may use +BROWSER_IMPORTS = frozenset({"html", "logging", "os", "sys", "webbrowser", "pathlib"}) +BROWSER_OPENS = frozenset({"open", "Error"}) + + +def _starts(name: str) -> bool: + """Whether os. starts a process""" + return name in {"system", "popen", "fork", "forkpty", "posix_spawn", "posix_spawnp", "startfile"} or ( + name.startswith(("exec", "spawn")) + ) + + +def _breaches(source: str) -> list[str]: + """What the source does beyond opening a browser, read without importing it""" + tree = ast.parse(source) + found: list[str] = [] + #: The names os and webbrowser are bound to, as imported + bound: dict[str, str] = {} + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + top = alias.name.split(".")[0] + if top not in BROWSER_IMPORTS: + found.append(f"import {alias.name}") + if alias.name in ("os", "webbrowser"): + bound[alias.asname or alias.name] = alias.name + elif isinstance(node, ast.ImportFrom): + module = "." * node.level + (node.module or "") + if module.split(".")[0] not in BROWSER_IMPORTS: + found.append(f"from {module} import") + for alias in node.names: + if (module == "os" and _starts(alias.name)) or ( + module == "webbrowser" and alias.name not in BROWSER_OPENS + ): + found.append(f"from {module} import {alias.name}") + elif isinstance(node, ast.Name) and node.id == "__import__": + found.append("__import__") + used = {id(node.value) for node in ast.walk(tree) if isinstance(node, ast.Attribute)} + for node in ast.walk(tree): + if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in bound: + module = bound[node.value.id] + if (module == "os" and _starts(node.attr)) or (module == "webbrowser" and node.attr not in BROWSER_OPENS): + found.append(f"{module}.{node.attr}") + elif isinstance(node, ast.Name) and node.id in bound and id(node) not in used: + # Handed on whole, as to getattr, the module could reach anything in it + found.append(f"{bound[node.id]} itself") + return found + + +def test_browser_py_only_opens_a_browser() -> None: + assert _breaches(BROWSER.read_text(encoding="utf-8")) == [] + + +@pytest.mark.parametrize( + "source", + [ + "import subprocess", + "import multiprocessing.pool", + "import pty", + "import importlib", + "from . import store", + "from .os import system", + "from asyncio import create_subprocess_exec", + "__import__('subprocess')", + "import os\nos.posix_spawn('x', [], {})", + "import os\nos.fork()", + "import os\nos.execv('x', [])", + "import os\nos.spawnlp(0, 'x')", + "import os as o\no.system('x')", + "import os\ngetattr(os, 'system')('x')", + "from os import popen", + "from os import execvp", + "import webbrowser\nwebbrowser.get('x')", + "import webbrowser\nwebbrowser.open_new_tab('x')", + "from webbrowser import BackgroundBrowser", + ], +) +def test_the_guard_on_browser_py_finds_a_process_start(source: str) -> None: + assert _breaches(source) + + +def test_the_guard_on_browser_py_lets_what_it_needs_through() -> None: + allowed = ( + "import html, logging, os, sys, webbrowser\nfrom pathlib import Path\n" + "os.open('x', os.O_WRONLY)\nos.environ.get('DISPLAY')\nwebbrowser.open('x')\nexcept_ = webbrowser.Error\n" + ) + assert _breaches(allowed) == [] diff --git a/tests/test_odmdm_fleet.py b/tests/test_odmdm_connector.py similarity index 55% rename from tests/test_odmdm_fleet.py rename to tests/test_odmdm_connector.py index 196f9d6..44443ce 100644 --- a/tests/test_odmdm_fleet.py +++ b/tests/test_odmdm_connector.py @@ -1,8 +1,8 @@ """Package level tests""" -from odmdm_fleet import __version__ +from odmdm_connector import __version__ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "0.1.0+261031" + assert __version__ == "1.5.0+261122" diff --git a/tests/test_plugins.py b/tests/test_plugins.py new file mode 100644 index 0000000..3cddb7b --- /dev/null +++ b/tests/test_plugins.py @@ -0,0 +1,106 @@ +"""Finding MDM plugins through their entry points""" + +from importlib.metadata import EntryPoint + +import pytest + +from odmdm_connector import plugins +from odmdm_connector.fleet_plugin import FleetPlugin + +#: A module that does not exist, so importing it fails the test that does +NEVER = "odmdm_connector_never_imported:Mdm" + + +class Old: + """A plugin written for another version of the contract""" + + API_VERSION = 2 + + +class Bare: + """A plugin that speaks the contract's version and declares nothing else""" + + API_VERSION = 1 + + +def _plugin(name: str, value: str, package: str = "odmdm-connector-demo", version: str = "1.0.0") -> plugins.Plugin: + return plugins.Plugin(name, package, version, EntryPoint(name, value, plugins.GROUP)) + + +@pytest.fixture +def declared(monkeypatch: pytest.MonkeyPatch) -> list[plugins.Plugin]: + """The entry points the plugins module sees, whatever is installed""" + found: list[plugins.Plugin] = [] + monkeypatch.setattr(plugins, "_declared", lambda: found) + return found + + +def test_fleet_is_registered_as_a_plugin_would_be() -> None: + """Through the package's own entry point, read from the installed metadata""" + fleet = plugins.find("fleet") + + assert (fleet.package, fleet.built_in) == ("odmdm-connector", True) + assert plugins.load("fleet") is FleetPlugin + + +def test_listing_imports_no_plugin(declared: list[plugins.Plugin]) -> None: + """Built-in first, then by name""" + declared += [ + _plugin("zeta", NEVER), + _plugin("demo", NEVER), + _plugin("fleet", "odmdm_connector.never_imported:Mdm", "odmdm_connector", "1.1.0"), + ] + + found = plugins.installed() + + assert [(p.name, p.built_in) for p in found] == [("fleet", True), ("demo", False), ("zeta", False)] + + +def test_loading_imports_only_the_one_chosen(declared: list[plugins.Plugin]) -> None: + declared += [_plugin("demo", NEVER), _plugin("fleet", "odmdm_connector.fleet_plugin:FleetPlugin")] + + assert plugins.load("fleet") is FleetPlugin + with pytest.raises(plugins.PluginError, match="The MDM demo from odmdm-connector-demo 1.0.0 cannot be loaded"): + plugins.load("demo") + + +def test_two_packages_claiming_one_name_are_both_named(declared: list[plugins.Plugin]) -> None: + declared += [_plugin("demo", NEVER), _plugin("demo", NEVER, "odmdm-connector-other", "2.0.0")] + + for call in (plugins.installed, lambda: plugins.load("demo")): + with pytest.raises(plugins.PluginError) as raised: + call() + assert "odmdm-connector-demo 1.0.0 and odmdm-connector-other 2.0.0" in str(raised.value) + + +def test_another_contract_version_is_refused(declared: list[plugins.Plugin]) -> None: + declared.append(_plugin("old", "tests.test_plugins:Old")) + + with pytest.raises( + plugins.PluginError, match="needs a connector that speaks MDM API version 2; this one speaks version 1" + ): + plugins.load("old") + + +def test_an_unknown_name_is_not_installed(declared: list[plugins.Plugin]) -> None: + with pytest.raises(plugins.NotInstalled, match="No MDM named nope is installed"): + plugins.load("nope") + + +def test_a_class_declaring_too_little_is_refused(declared: list[plugins.Plugin]) -> None: + """Said before anything reads its title, fields or missing""" + declared.append(_plugin("bare", "tests.test_plugins:Bare")) + + with pytest.raises(plugins.PluginError) as raised: + plugins.load("bare") + + assert str(raised.value) == ( + "The MDM bare from odmdm-connector-demo 1.0.0 does not declare title, fields, missing, so it cannot be used" + ) + + +def test_built_in_means_the_connectors_own_code_too() -> None: + """The connector's distribution name on an entry point outside its package is no proof""" + assert not _plugin("odd", NEVER, "odmdm-connector", "1.1.0").built_in + assert not _plugin("odd", "odmdm_connector_x.mdm:Mdm", "odmdm-connector", "1.1.0").built_in + assert _plugin("fleet", "odmdm_connector:Mdm", "odmdm-connector", "1.1.0").built_in diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 0000000..85c588b --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,137 @@ +"""The settings line Deploy App's MDM page copies, version 1 + +The same line for every MDM, so the vector in tests/data is shared with Deploy App. +""" + +import datetime +from pathlib import Path + +import pytest + +from odmdm_connector.settings import Settings, SettingsError, is_line, parse + +VECTOR = (Path(__file__).parent / "data" / "settings-line-v1.txt").read_text(encoding="utf-8") +CHALLENGE = "0123456789abcdef0123456789abcdef" # pragma: allowlist secret +BEFORE = datetime.datetime(2026, 11, 21, 12, 0, tzinfo=datetime.UTC) +CLOSES = datetime.datetime(2026, 11, 21, 14, 0, tzinfo=datetime.UTC) + + +def test_the_shared_vector() -> None: + assert VECTOR.split() == ["ODMDM1", "https://unit.example.fi/scep", CHALLENGE, "2026-11-21T14:00:00Z"] + assert parse(VECTOR, BEFORE) == Settings("https://unit.example.fi/scep", CHALLENGE, CLOSES) + + +@pytest.mark.parametrize("around", [" {} ", "\n{}\r\n", "\t{}\n\n"]) +def test_whitespace_and_line_breaks_around_it_are_ignored(around: str) -> None: + assert parse(around.format(VECTOR.strip()), BEFORE).challenge == CHALLENGE + + +def test_the_challenge_never_shows_in_its_repr() -> None: + assert CHALLENGE not in repr(parse(VECTOR, BEFORE)) + + +@pytest.mark.parametrize( + ("line", "says"), + [ + ("", "not a settings line"), + ("ODMDM2 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "not a settings line"), + ("odmdm1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "not a settings line"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE, "not a settings line"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z OTTER1", "not a settings line"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE.upper() + " 2026-11-21T14:00:00Z", "32 lowercase hex"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE[:-1] + " 2026-11-21T14:00:00Z", "32 lowercase hex"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE[:-1] + "g 2026-11-21T14:00:00Z", "32 lowercase hex"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00", "is not YYYY-MM-DDTHH:MM:SSZ"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21 14:00:00Z", "not a settings line"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-31T14:00:00Z", "is not YYYY-MM-DDTHH:MM:SSZ"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00+00:00", "is not YYYY-MM-DD"), + ], +) +def test_a_line_that_cannot_be_used_says_why(line: str, says: str) -> None: + with pytest.raises(SettingsError, match=says) as raised: + parse(line, BEFORE) + assert CHALLENGE[:-1] not in str(raised.value), "the challenge is never in a message" + + +@pytest.mark.parametrize( + "url", + [ + "http://unit.example.fi/scep", + "https:///scep", + "https://unit.example.fi", + "https://unit.example.fi/", + "https://evil.example\\@unit.example.fi/scep", + "https://unit.example.fi\\scep", + "https://user:pass@unit.example.fi/scep", # pragma: allowlist secret + "https://user@unit.example.fi/scep", + "https://unit.example.fi:8443/scep", + "https://unit.example.fi:/scep", + "https://unit.example.fi/scep?x=1", + "https://unit.example.fi/scep?", + "https://unit.example.fi/scep#x", + "https://[unit.example.fi/scep", + "ftp://unit.example.fi/scep", + "https://un\u0456t.example.fi/scep", + "https://\uff55nit.example.fi/scep", + "https://unit.example.fi\u200b/scep", + "https://unit%2eexample.fi/scep", + "https://unit.example.fi;x/scep", + "https://unit.example.fi\x7f/scep", + "https://unit_1.example.fi/scep", + "https://-unit.example.fi/scep", + "https://unit-.example.fi/scep", + "https://unit..example.fi/scep", + "https://unit.example.fi./scep", + "https://localhost/scep", + ], +) +def test_a_scep_url_that_is_not_just_a_host_and_a_path_is_refused(url: str) -> None: + line = f"ODMDM1 {url} {CHALLENGE} 2026-11-21T14:00:00Z" + + with pytest.raises(SettingsError) as raised: + parse(line, BEFORE) + + assert str(raised.value) == ( + "The SCEP URL in the settings line must be https:///, with a plain host name and nothing else " + "before the path." + ) + + +def test_a_host_in_capitals_is_the_same_host() -> None: + assert ( + parse(VECTOR.replace("unit.example.fi", "Unit.Example.FI"), BEFORE).scep_url == "https://unit.example.fi/scep" + ) + + +@pytest.mark.parametrize("host", ["unit.example.fi", "a.b", "x-1.unit-2.example.fi", "192.0.2.10"]) +def test_a_plain_host_is_taken(host: str) -> None: + assert parse(VECTOR.replace("unit.example.fi", host), BEFORE).scep_url == f"https://{host}/scep" + + +@pytest.mark.parametrize( + ("now", "at"), + [ + (CLOSES, "14:00"), + (CLOSES + datetime.timedelta(seconds=1), "14:00"), + (CLOSES.astimezone(datetime.timezone(datetime.timedelta(hours=2))), "16:00"), + ], +) +def test_a_closed_window_is_refused_at_the_operators_time(now: datetime.datetime, at: str) -> None: + with pytest.raises(SettingsError, match=f"^The enrolment window closed at {at}: open a new one in Deploy App.$"): + parse(VECTOR, now) + + +@pytest.mark.parametrize( + ("value", "line"), + [ + (VECTOR, True), + (" ODMDM2 x", True), + ("odmdm1 x", True), + (VECTOR.split(None, 1)[1], True), + (CHALLENGE, False), + (" " + CHALLENGE + "\n", False), + ("", False), + ], +) +def test_a_line_is_told_from_a_bare_challenge(value: str, line: bool) -> None: + assert is_line(value) is line diff --git a/tests/test_standard_library.py b/tests/test_standard_library.py new file mode 100644 index 0000000..fab4be1 --- /dev/null +++ b/tests/test_standard_library.py @@ -0,0 +1,53 @@ +"""The connector needs Python and nothing else, and runs from inside a zip file + +So it goes into a network without internet as one file, see README.rst. Its one dependency, keyring, +reaches the system's keychain for the MDM token, is imported in store.py alone, and the connector +runs without it. +""" + +import ast +import sys +from pathlib import Path + +import pytest + +PACKAGE = Path(__file__).parent.parent / "src" / "odmdm_connector" +MODULES = sorted(PACKAGE.rglob("*.py")) +#: The one module that may import something else, and what +ALLOWED = {PACKAGE / "store.py": {"keyring"}} + + +def _nodes(path: Path) -> list[ast.AST]: + return list(ast.walk(ast.parse(path.read_text(encoding="utf-8"), str(path)))) + + +def test_every_module_is_checked() -> None: + assert PACKAGE / "app.py" in MODULES + assert PACKAGE / "testing" / "contract.py" in MODULES + + +@pytest.mark.parametrize("path", MODULES, ids=lambda path: path.relative_to(PACKAGE).as_posix()) +def test_runtime_code_imports_only_the_standard_library(path: Path) -> None: + imported: set[str] = set() + for node in _nodes(path): + if isinstance(node, ast.Import): + imported.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + imported.add(node.module.split(".")[0]) + + assert imported - sys.stdlib_module_names - {"odmdm_connector"} - ALLOWED.get(path, set()) == set() + + +@pytest.mark.parametrize("path", MODULES, ids=lambda path: path.relative_to(PACKAGE).as_posix()) +def test_a_shipped_file_is_read_through_importlib_resources(path: Path) -> None: + """Never beside __file__, which is no directory when the package runs from a zip""" + assert "__file__" not in {node.id for node in _nodes(path) if isinstance(node, ast.Name)} + + +def test_keyring_is_imported_only_when_the_keychain_is_asked_for() -> None: + """Never when the module is, so that the connector runs without keyring""" + body = ast.parse((PACKAGE / "store.py").read_text(encoding="utf-8")).body + imported = {alias.name for node in body if isinstance(node, ast.Import) for alias in node.names} + imported |= {node.module or "" for node in body if isinstance(node, ast.ImportFrom)} + + assert not {name for name in imported if name.split(".")[0] == "keyring"} diff --git a/tests/test_store.py b/tests/test_store.py new file mode 100644 index 0000000..47af956 --- /dev/null +++ b/tests/test_store.py @@ -0,0 +1,242 @@ +"""The settings file and the keychain, against a temporary directory and a keychain in memory""" + +import datetime +import json +import logging +import os +import stat +import sys +from pathlib import Path + +import keyring +import keyring.core +import pytest + +from odmdm_connector import store + +TOKEN = "s3cret" # pragma: allowlist secret + + +class MemoryBackend: + """A keychain in memory; broken makes every call raise, as a keychain that does not answer does""" + + def __init__(self) -> None: + self.items: dict[tuple[str, str], str] = {} + self.broken = False + #: Deleting is refused while reading still answers, as a locked item is + self.undeletable = False + + def _check(self) -> None: + if self.broken: + raise RuntimeError(f"no keychain here for {TOKEN}") + + def get_password(self, service: str, username: str) -> str | None: + self._check() + return self.items.get((service, username)) + + def set_password(self, service: str, username: str, password: str) -> None: + self._check() + self.items[(service, username)] = password + + def delete_password(self, service: str, username: str) -> None: + self._check() + if self.undeletable or (service, username) not in self.items: + raise keyring.errors.PasswordDeleteError(username) + del self.items[(service, username)] + + +def test_settings_survive_a_restart(tmp_path: Path) -> None: + unit = store.Connection( + mdm="fleet", + values={"mdm_url": "https://mdm.example.fi"}, + closes="2026-11-21T14:00:00+00:00", + prefix="OTTER", + callsigns=["BEAR1", "BEAR2"], + ) + saved = store.Saved( + approved=["demo odmdm-connector-demo 1.0.0"], + connections={"unit.example.fi": unit, "other.example.fi": store.Connection(mdm="demo")}, + active="unit.example.fi", + ) + + store.Store(tmp_path / "config").save(saved) + + assert store.Store(tmp_path / "config").load() == saved + assert store.closes(unit) == datetime.datetime(2026, 11, 21, 14, tzinfo=datetime.UTC) + + +def test_the_file_holds_no_more_than_said(tmp_path: Path) -> None: + """Written whole, readable only by the user, nothing left beside it""" + settings = store.Store(tmp_path) + settings.save(store.Saved(active="")) + settings.save(store.Saved(connections={"unit.example.fi": store.Connection()}, active="unit.example.fi")) + + assert [path.name for path in tmp_path.iterdir()] == ["settings.json"] + assert json.loads(settings.path.read_text(encoding="utf-8"))["active"] == "unit.example.fi" + if os.name == "posix": + assert stat.S_IMODE(settings.path.stat().st_mode) == 0o600 + + +def test_no_file_is_empty_settings(tmp_path: Path) -> None: + assert store.Store(tmp_path).load() == store.Saved() + assert store.closes(store.Connection()) is None + assert store.closes(store.Connection(closes="soon")) is None + + +@pytest.mark.parametrize( + "text", + [ + "not json", + '{"version": 2}', + '{"version": 1, "active": 3}', + '{"version": 1, "approved": "demo"}', + '{"version": 1, "connections": []}', + '{"version": 1, "connections": {"unit.example.fi": "fleet"}}', + '{"version": 1, "connections": {"unit.example.fi": {"mdm": 3}}}', + '{"version": 1, "connections": {"unit.example.fi": {"values": {"team": 1}}}}', + '{"version": 1, "connections": {"unit.example.fi": {"callsigns": "BEAR1"}}}', + '{"version": 1, "connections": {}, "active": "unit.example.fi"}', + ], +) +def test_a_damaged_file_is_said_in_a_sentence(tmp_path: Path, text: str) -> None: + settings = store.Store(tmp_path) + settings.path.write_text(text, encoding="utf-8") + + with pytest.raises(store.StoreError, match=r"is damaged, so the app starts without it\.$"): + settings.load() + + +def test_a_file_that_cannot_be_read_or_written_is_said(tmp_path: Path) -> None: + (tmp_path / "settings.json").mkdir() + blocked = tmp_path / "blocked" + blocked.write_text("a file where the directory would be", encoding="utf-8") + + with pytest.raises(store.StoreError, match="cannot be read"): + store.Store(tmp_path).load() + with pytest.raises(store.StoreError, match="cannot be written"): + store.Store(blocked).save(store.Saved()) + with pytest.raises(store.StoreError, match="cannot be written"): + store.Store(tmp_path).save(store.Saved()) + assert [path.name for path in tmp_path.iterdir() if path.name.startswith(".")] == [] + + +@pytest.mark.parametrize( + ("platform", "environment", "expected"), + [ + ("win32", {"LOCALAPPDATA": "local"}, ("local", "odmdm-connector")), + ("win32", {}, ("home", "AppData", "Local", "odmdm-connector")), + ("darwin", {"XDG_CONFIG_HOME": "xdg"}, ("home", "Library", "Application Support", "odmdm-connector")), + ("linux", {"XDG_CONFIG_HOME": "xdg"}, ("xdg", "odmdm-connector")), + ("linux", {}, ("home", ".config", "odmdm-connector")), + ], +) +def test_the_directory_is_the_users_own( + monkeypatch: pytest.MonkeyPatch, platform: str, environment: dict[str, str], expected: tuple[str, ...] +) -> None: + """Named, not created""" + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setattr(Path, "home", lambda: Path("home")) + for name in ("LOCALAPPDATA", "XDG_CONFIG_HOME"): + monkeypatch.delenv(name, raising=False) + for name, value in environment.items(): + monkeypatch.setenv(name, value) + + assert store.directory() == Path(*expected) + + +def test_a_secret_kept_and_forgotten(caplog: pytest.LogCaptureFixture) -> None: + backend = MemoryBackend() + keychain = store.Keychain(backend) + + assert keychain.usable + assert keychain.keep("unit.example.fi:fleet:token", TOKEN) + assert backend.items == {("odmdm-connector", "unit.example.fi:fleet:token"): TOKEN} + assert store.Keychain(backend).get("unit.example.fi:fleet:token") == TOKEN + assert keychain.forget("unit.example.fi:fleet:token") + assert (backend.items, keychain.get("unit.example.fi:fleet:token")) == ({}, "") + with caplog.at_level(logging.WARNING): + assert keychain.forget("unit.example.fi:fleet:token") + assert not caplog.records, "nothing to forget is not a keychain that did not answer" + + +def test_a_keychain_that_does_not_answer_is_logged_by_its_kind_only(caplog: pytest.LogCaptureFixture) -> None: + backend = MemoryBackend() + backend.items[("odmdm-connector", "unit.example.fi:fleet:token")] = TOKEN + backend.broken = True + keychain = store.Keychain(backend) + + with caplog.at_level(logging.WARNING): + assert not keychain.keep("unit.example.fi:fleet:token", TOKEN) + assert keychain.get("unit.example.fi:fleet:token") == "" + assert not keychain.forget("unit.example.fi:fleet:token") + + assert [record.getMessage() for record in caplog.records] == ["The keychain did not answer: RuntimeError"] * 3 + assert all(record.exc_info is None for record in caplog.records) + + +def test_a_secret_the_keychain_will_not_delete_is_said_to_be_left() -> None: + backend = MemoryBackend() + backend.items[("odmdm-connector", "unit.example.fi:fleet:token")] = TOKEN + backend.undeletable = True + + assert not store.Keychain(backend).forget("unit.example.fi:fleet:token") + + +def test_no_back_end_is_no_keychain() -> None: + missing = store.Keychain(None) + + assert not missing.usable + assert not missing.keep("unit.example.fi:fleet:token", TOKEN) + assert missing.get("unit.example.fi:fleet:token") == "" + assert missing.forget("unit.example.fi:fleet:token"), "nothing is kept where there is no keychain" + + +def _chosen() -> type[keyring.backend.KeyringBackend]: + """keyring's back end for this system, as store names it""" + if sys.platform == "win32": + from keyring.backends.Windows import WinVaultKeyring + + return WinVaultKeyring + if sys.platform == "darwin": + from keyring.backends.macOS import Keyring as MacOS + + return MacOS + from keyring.backends.SecretService import Keyring as SecretService + + return SecretService + + +def test_the_systems_keychain_is_fixed_in_code(monkeypatch: pytest.MonkeyPatch) -> None: + """Neither the environment nor keyring's configuration chooses it; nothing is read or written""" + monkeypatch.setattr(keyring.core, "_keyring_backend", None) + monkeypatch.setenv("PYTHON_KEYRING_BACKEND", "keyring.backends.null.Keyring") + + backend = store.platform_backend() + + if backend is None: + pytest.skip(f"{_chosen().__name__} cannot be used on this machine") + assert type(backend) is _chosen() + assert keyring.get_keyring() is backend + + +def test_a_keychain_that_cannot_be_used_here_is_none(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(keyring.core, "_keyring_backend", None) + monkeypatch.setattr(_chosen(), "viable", False) + + assert store.platform_backend() is None + assert keyring.core._keyring_backend is None + + +def test_without_keyring_there_is_no_keychain( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """As in the one-file build, which leaves keyring out; said only to the debug log, as nothing is wrong""" + for name in [name for name in sys.modules if name == "keyring" or name.startswith("keyring.")]: + monkeypatch.setitem(sys.modules, name, None) + monkeypatch.setitem(sys.modules, "keyring", None) + caplog.set_level(logging.DEBUG) + + assert store.platform_backend() is None + assert [(record.levelno, record.getMessage()) for record in caplog.records] == [ + (logging.DEBUG, "keyring is not installed, so no keychain is used") + ] diff --git a/tests/test_template.py b/tests/test_template.py new file mode 100644 index 0000000..db22e0e --- /dev/null +++ b/tests/test_template.py @@ -0,0 +1,202 @@ +"""The template document + +What a deployment installs is data, not code. These tests pin that the connector stays ignorant +of it and that a malformed document is refused before it can reach an MDM. +""" + +import json +from pathlib import Path + +import pytest + +from odmdm_connector.template import EXAMPLE, TemplateError, load + +GOOD = { + "apps": [ + {"package": "com.example.one", "preinstall": True}, + { + "package": "com.example.two", + "preinstall": False, + "config": {"AutoSelectCertificateForUrls": ['{"pattern":"{mtls_url}","filter":{}}']}, + }, + ], + "link_app": {"title": "Deploy App", "url": "{mtls_url}/"}, + "policy": { + "choosePrivateKeyRules": [ + {"urlPattern": "{mtls_url}", "privateKeyAlias": "{key_alias}", "packageNames": ["com.example.two"]} + ], + "defaultPermissionPolicy": "GRANT", + }, +} + + +def _write(tmp_path: Path, body: object) -> Path: + path = tmp_path / "template.json" + path.write_text(json.dumps(body), encoding="utf-8") + return path + + +def test_placeholders_are_filled_at_every_depth(tmp_path: Path) -> None: + """The document is written once and used against whatever deployment it is pointed at""" + template = load(_write(tmp_path, GOOD), domain="example.fi", key_alias="rmscep") + + assert template.preinstall_packages == ("com.example.one",) + inside_a_list = template.apps[1].config["AutoSelectCertificateForUrls"][0] + assert json.loads(inside_a_list)["pattern"] == "https://mtls.example.fi" + assert template.policy["choosePrivateKeyRules"][0]["urlPattern"] == "https://mtls.example.fi" + assert template.policy["choosePrivateKeyRules"][0]["privateKeyAlias"] == "rmscep" + assert template.link_app is not None + assert template.link_app.url == "https://mtls.example.fi/" + + +@pytest.mark.parametrize( + ("body", "because"), + [ + ({"apps": []}, "a template that installs nothing is a mistake, not a choice"), + ({"apps": [{"preinstall": True}]}, "an app with no package cannot be acted on"), + ({"apps": [{"package": "x", "config": []}]}, "config must be an object"), + ({"apps": [{"package": "x"}], "policy": []}, "policy must be an object"), + ({"apps": [{"package": "x"}], "link_app": {"title": "t"}}, "a link with no url is useless"), + ([], "the document must be an object"), + ], +) +def test_a_malformed_document_is_refused(tmp_path: Path, body: object, because: str) -> None: + """A half applied template is worse than none: apps install at enrolment only, so a device + that joined against a broken one has to be enrolled again, and its callsign is spent.""" + with pytest.raises(TemplateError): + load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep") + + +NAMED = "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" + + +def _with(policy: dict[str, object] | None = None, subject: str = NAMED) -> dict[str, object]: + """GOOD with a certificate, and with these policy keys changed""" + certificate = {"name": "{key_alias}", "subject": subject, "authority": "RMSCEP"} + return {**GOOD, "certificate": certificate, "policy": {**GOOD["policy"], **(policy or {})}} # type: ignore[dict-item] + + +@pytest.mark.parametrize( + "subject", + [ + NAMED, + "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME", + "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID", + "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME,OU=$FLEET_VAR_HOST_UUID", + ], +) +def test_the_callsign_is_the_name_the_operator_gave(tmp_path: Path, subject: str) -> None: + template = load(_write(tmp_path, _with(subject=subject)), domain="example.fi", key_alias="rmscep") + assert template.certificate is not None and template.certificate.subject == subject + + +@pytest.mark.parametrize( + ("body", "says"), + [ + (_with(subject="CN=$FLEET_VAR_HOST_HARDWARE_SERIAL"), "certificate subject must be CN="), + (_with(subject="CN=OTTER1"), "certificate subject must be CN="), + (_with(subject=NAMED + ", OU=$FLEET_VAR_HOST_HARDWARE_SERIAL"), "certificate subject must be CN="), + (_with(subject="OU=$FLEET_VAR_HOST_UUID, " + NAMED), "certificate subject must be CN="), + ( + _with({"choosePrivateKeyRules": [{"urlPattern": "x", "privateKeyAlias": "rmscep"}]}), + "must name its apps in packageNames", + ), + ( + _with({"choosePrivateKeyRules": [{"urlPattern": "x", "packageNames": []}]}), + "must name its apps in packageNames", + ), + (_with({"choosePrivateKeyRules": {"packageNames": ["a"]}}), "choosePrivateKeyRules must be a list"), + (_with({"privateKeySelectionEnabled": True}), "privateKeySelectionEnabled must not be true"), + ( + _with({"advancedSecurityOverrides": {"untrustedAppsPolicy": "ALLOW_INSTALL_DEVICE_WIDE"}}), + "must not allow installs from unknown sources", + ), + ( + _with({"advancedSecurityOverrides": {"untrustedAppsPolicy": "ALLOW_INSTALL_IN_PERSONAL_PROFILE_ONLY"}}), + "must not allow installs from unknown sources", + ), + (_with({"installUnknownSourcesAllowed": True}), "must not allow installs from unknown sources"), + ], +) +def test_a_template_that_hands_out_too_much_is_refused(tmp_path: Path, body: object, says: str) -> None: + """A named phone's key for named apps only, and no side door onto the phone""" + with pytest.raises(TemplateError, match=says): + load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep") + + +def test_safe_settings_are_accepted(tmp_path: Path) -> None: + body = _with( + {"privateKeySelectionEnabled": False, "advancedSecurityOverrides": {"untrustedAppsPolicy": "DISALLOW_INSTALL"}} + ) + assert load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep").certificate is not None + + +def test_a_missing_file_is_refused(tmp_path: Path) -> None: + with pytest.raises(TemplateError): + load(tmp_path / "nope.json", domain="example.fi", key_alias="rmscep") + + +def test_not_json_is_refused(tmp_path: Path) -> None: + path = tmp_path / "template.json" + path.write_text("this is not json", encoding="utf-8") + with pytest.raises(TemplateError): + load(path, domain="example.fi", key_alias="rmscep") + + +def test_annotations_never_reach_the_device(tmp_path: Path) -> None: + """The document explains itself, and none of that explanation is a setting + + An annotation left in an app's configuration would be pushed to the phone as a real managed + configuration key. + """ + body = { + "_comment": "why this file exists", + "apps": [ + { + "_comment": "why this app", + "package": "com.example.one", + "config": {"_comment": "why this key", "real": "value", "nested": {"_x": 1, "keep": 2}}, + } + ], + "policy": {"_comment": "why this policy", "defaultPermissionPolicy": "GRANT"}, + "link_app": {"_comment": "why a link", "title": "Deploy App", "url": "{mtls_url}/"}, + } + template = load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep") + assert template.apps[0].config == {"real": "value", "nested": {"keep": 2}} + assert template.policy == {"defaultPermissionPolicy": "GRANT"} + assert template.link_app is not None and template.link_app.title == "Deploy App" + + +def test_the_example_is_a_template_we_accept() -> None: + """Operators start from it, so it must never drift out of what load() takes""" + template = load(EXAMPLE, domain="example.fi", key_alias="rmscep") + + assert template.certificate is not None + assert template.certificate.name == "rmscep", "the keystore alias comes from the setting" + assert not [p for p in ("{domain}", "{mtls_url}", "{key_alias}") if p in json.dumps(template.policy)] + assert template.policy["advancedSecurityOverrides"]["untrustedAppsPolicy"] == "DISALLOW_INSTALL" + assert template.policy["privateKeySelectionEnabled"] is False + assert "defaultPermissionPolicy" not in template.policy, "nothing granted to every app" + rules = template.policy["choosePrivateKeyRules"] + assert [r["packageNames"] for r in rules] == [["com.android.chrome", "com.atakmap.app.civ", "im.vector.app"]] + + +def test_the_shipped_template_names_no_authority() -> None: + """The connector finds a Deploy App's authority by its address, so one MDM can serve several""" + template = load(EXAMPLE, domain="example.fi", key_alias="rmscep") + + assert template.certificate is not None and template.certificate.authority == "" + + +def test_a_template_may_name_its_authority(tmp_path: Path) -> None: + template = load(_write(tmp_path, _with()), domain="example.fi", key_alias="rmscep") + + assert template.certificate is not None and template.certificate.authority == "RMSCEP" + + +def test_the_shipped_subject_carries_the_device_id() -> None: + """A subject cannot change once a team has phones, so the id is there from the first template""" + template = load(EXAMPLE, domain="example.fi", key_alias="rmscep") + + assert template.certificate is not None + assert template.certificate.subject == f"{NAMED}, OU=$FLEET_VAR_HOST_UUID" diff --git a/tests/test_testing.py b/tests/test_testing.py new file mode 100644 index 0000000..4a688f0 --- /dev/null +++ b/tests/test_testing.py @@ -0,0 +1,149 @@ +"""The plugin authors' test kit, run against the fake and against Fleet over the stub""" + +from collections.abc import Iterator, Mapping, Sequence +from typing import ClassVar + +import pytest + +from odmdm_connector.fleet_plugin import FleetPlugin +from odmdm_connector.mdm import CAPABILITIES, Mdm, MdmError, Phone, State, Step +from odmdm_connector.settings import Settings +from odmdm_connector.testing import FakeMdm, contract + +from .test_fleet import Request, Response, _Fleet, _host, _mdm + +NO_NAME = "Could not replace certificate variables: host 6f1c does not have an IDP user for variable FLEET_VAR_X" +CHECKS = pytest.mark.parametrize("check", contract.CHECKS, ids=lambda check: check.__name__) + + +def _fake(refuse_after: int | None = None) -> Mdm: + return FakeMdm({}, refuse_after=refuse_after) + + +def _lacking(refuse_after: int | None = None) -> Mdm: + return FakeMdm.lacking(*CAPABILITIES)({}, refuse_after=refuse_after) + + +@pytest.fixture +def fleet(monkeypatch: pytest.MonkeyPatch) -> contract.Factory: + """Fleet over the stub, two phones waiting for a name and one with its certificate""" + + def factory(refuse_after: int | None = None) -> Mdm: + stub = _Fleet() + stub.authorities = [{"id": 3, "name": "RMSCEP", "url": contract.WINDOW.scep_url}] + stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": "CN=$X", "certificate_authority_id": 3}] + stub.hosts = [ + _host(31, "failed", detail=NO_NAME), + _host(32, "failed", detail=NO_NAME), + _host(33, "verified", "A"), + ] + answer = stub.handler + named: list[str] = [] + + def refusing(request: Request) -> Response: + if request.url.path.endswith("/device_mapping"): + if refuse_after is not None and len(named) >= refuse_after: + return Response(500, text="database is locked") + named.append(request.url.path) + return answer(request) + + stub.handler = refusing # type: ignore[method-assign] + _mdm(stub, monkeypatch) + return FleetPlugin({"mdm_url": "https://mdm.test", "token": "token", "team": "rmscep"}) + + return factory + + +@CHECKS +def test_the_fake_keeps_the_contract(check: contract.Check) -> None: + check(_fake) + + +@CHECKS +def test_a_fake_lacking_every_capability_keeps_the_contract(check: contract.Check) -> None: + check(_lacking) + + +@CHECKS +def test_fleet_keeps_the_contract(check: contract.Check, fleet: contract.Factory) -> None: + check(fleet) + + +class _Careless(FakeMdm): + """Breaks the contract in every way a check looks for""" + + API_VERSION = 2 + title = "" + missing: ClassVar[Mapping[str, str]] = {"teleport": ""} + + def name(self, names: Mapping[str, str]) -> list[str]: + try: + return super().name(names) + except MdmError as exc: + raise MdmError(str(exc)) from exc + + def ask_again(self, ids: Sequence[str]) -> list[str]: + return [""] + + +class _Forcing(FakeMdm): + """Says it cannot send the policy again, then sets up with force anyway""" + + missing: ClassVar[Mapping[str, str]] = {"send_policy": "Not here"} + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + return super().setup(window, dry_run=dry_run) + + +class _Lying(FakeMdm): + """Says it lacks asking again, then does it anyway""" + + missing: ClassVar[Mapping[str, str]] = {"ask_again": "Not here", "set_challenge": "Not here"} + + def ask_again(self, ids: Sequence[str]) -> list[str]: + return [] + + def set_challenge(self, window: object) -> None: + raise MdmError("Something else") + + +@pytest.mark.parametrize( + ("factory", "check", "says"), + [ + (_Careless, contract.declares_the_contract_version, "API_VERSION must be 1"), + (_Careless, contract.says_what_it_lacks, "missing names only capabilities"), + (_Careless, contract.says_what_a_batch_stopped_half_way_named, "MdmError.named must be"), + (_Careless, contract.asks_again, "lines must be non-empty"), + (_Lying, contract.asks_again, "listed as missing but did not raise"), + (_Lying, contract.sets_the_challenge, "must raise MdmError with its sentence"), + (_Forcing, contract.sends_the_policy_again, "send_policy is listed as missing but did not raise"), + ], +) +def test_a_plugin_breaking_the_contract_fails_its_check( + factory: type[FakeMdm], check: contract.Check, says: str +) -> None: + with pytest.raises(AssertionError, match=says): + check(lambda refuse_after=None: factory({}, refuse_after=refuse_after)) + + +def test_the_phones_a_check_needs() -> None: + """Times an operator can read, and enough phones to name""" + odd = [Phone("a1", "", "m", "yesterday", State.NEEDS_NAME)] + + with pytest.raises(AssertionError, match="not an ISO time"): + contract.lists_its_phones(lambda refuse_after=None: FakeMdm({}, odd)) + with pytest.raises(AssertionError, match="at least two phones without a name"): + contract.names_phones(lambda refuse_after=None: FakeMdm({}, odd)) + + +def test_a_name_that_does_not_stick_fails() -> None: + class Forgetful(FakeMdm): + def name(self, names: Mapping[str, str]) -> list[str]: + return ["Named"] + + with pytest.raises(AssertionError, match="must show its callsign"): + contract.names_phones(lambda refuse_after=None: Forgetful({})) + with pytest.raises(AssertionError, match="must raise MdmError when the MDM refuses"): + contract.says_what_a_batch_stopped_half_way_named(lambda refuse_after=None: Forgetful({})) + with pytest.raises(AssertionError, match="name of an id not in the group"): + contract.refuses_an_unknown_id(lambda refuse_after=None: Forgetful({})) diff --git a/tests/test_web.py b/tests/test_web.py new file mode 100644 index 0000000..d181076 --- /dev/null +++ b/tests/test_web.py @@ -0,0 +1,1052 @@ +"""The page's server against the fake MDM: on a free port in a thread, with http.client as the browser""" + +import http.client +import json +import logging +import socket +import sys +import threading +import time +from collections.abc import Iterator +from dataclasses import replace +from pathlib import Path +from typing import Any + +import pytest + +from odmdm_connector import app, browser, console, store, web +from odmdm_connector.mdm import ASK_AGAIN, SEND_POLICY, State, Step +from odmdm_connector.settings import Settings +from odmdm_connector.testing import FakeMdm + +from .test_app import ( + CHALLENGE, + GOLDEN, + KEPT, + LINE, + NOW, + TOKEN_VALUES, + VALUES, + Addressed, + FleetFields, + HalfSetUp, + Rig, +) +from .test_store import MemoryBackend + +Answer = tuple[int, http.client.HTTPMessage, bytes] + + +class WebRig(Rig): + """The App of test_app's Rig, and a clock for the page that the test moves""" + + def __init__(self, directory: Path, backend: MemoryBackend | None = None) -> None: + self.ticks = 0.0 + super().__init__(directory, backend) + + +class Served: + """The page on a free port, and a browser that has opened the address printed""" + + def __init__(self, rig: WebRig) -> None: + self.rig = rig + self.page = web.Page(rig.app, 0, now=lambda: NOW, clock=lambda: rig.ticks) + self.host = f"127.0.0.1:{self.page.port}" + self.origin = f"http://{self.host}" + self.key = self.page.key + #: Every answer's body, to look for secrets in + self.bodies: list[bytes] = [] + threading.Thread(target=self.page.serve_forever, args=(0.01,), daemon=True).start() + + def request(self, method: str, path: str, body: bytes | None = None, **headers: str) -> Answer: + sent = {"Host": self.host, "X-ODMDM-Key": self.key, **headers} + connection = http.client.HTTPConnection("127.0.0.1", self.page.port, timeout=5) + try: + connection.request(method, path, body, {name.replace("_", "-"): value for name, value in sent.items()}) + response = connection.getresponse() + answer = (response.status, response.msg, response.read()) + finally: + connection.close() + self.bodies.append(answer[2]) + return answer + + def post(self, path: str, body: Any = None, status: int = 200) -> Any: + given = json.dumps({} if body is None else body).encode() + got, _, data = self.request("POST", path, given, Origin=self.origin, Content_Type="application/json") + assert got == status, data + return json.loads(data) + + def state(self) -> Any: + self.rig.app.worker.wait() + status, _, data = self.request("GET", "/api/state") + assert status == 200, data + return json.loads(data) + + +def _served(rig: WebRig) -> Iterator[Served]: + made = Served(rig) + yield made + made.page.shutdown() + made.page.server_close() + made.rig.app.close() + + +@pytest.fixture +def served(tmp_path: Path) -> Iterator[Served]: + yield from _served(WebRig(tmp_path / "config")) + + +@pytest.fixture +def keyed(tmp_path: Path) -> Iterator[Served]: + """The page on a computer with a keychain""" + yield from _served(WebRig(tmp_path / "config", MemoryBackend())) + + +def test_nothing_under_api_is_answered_without_the_key_header(served: Served) -> None: + status, _, body = served.request("GET", "/api/state", X_ODMDM_Key="") + assert (status, body.decode()) == ( + 403, + "Open the address that the connector printed when it started. This page then goes on by itself.", + ) + assert served.request("GET", "/api/state", X_ODMDM_Key="wrong")[0] == 403 + assert served.request("GET", "/api/nothing", X_ODMDM_Key="")[0] == 403 + assert served.request("POST", "/api/refresh", b"{}", X_ODMDM_Key="", Origin=served.origin)[0] == 403 + assert served.request("GET", "/api/state")[0] == 200 + + +def test_the_key_is_in_the_fragment_and_never_a_cookie(served: Served) -> None: + """A browser sends a cookie for 127.0.0.1 to every port of it, and a fragment to no server""" + assert served.page.address == f"http://127.0.0.1:{served.page.port}/#key={served.page.key}" + status, headers, body = served.request("GET", f"/?key={served.page.key}", X_ODMDM_Key="") + assert (status, headers["Set-Cookie"], headers["Location"]) == (200, None, None) + assert body.startswith(b"") + assert served.request("GET", "/api/state", X_ODMDM_Key="", Cookie=f"odmdm={served.page.key}")[0] == 403 + + +def test_two_key_headers_are_refused(served: Served) -> None: + with socket.create_connection(("127.0.0.1", served.page.port), timeout=5) as raw: + raw.sendall( + f"GET /api/state HTTP/1.1\r\nHost: {served.host}\r\nX-ODMDM-Key: {served.key}\r\n" + f"X-ODMDM-Key: {served.key}\r\nConnection: close\r\n\r\n".encode() + ) + answer = raw.recv(4096) + assert answer.startswith(b"HTTP/1.0 403") + + +@pytest.mark.parametrize("path", ["/", "/?key=wrong", "/app.css", "/app.js"]) +def test_the_three_files_need_no_key(served: Served, path: str) -> None: + """They are public code, and the page explains itself to a browser that has no key yet""" + status, headers, _ = served.request("GET", path, X_ODMDM_Key="") + + assert (status, headers["Set-Cookie"]) == (200, None) + + +def test_the_server_header_names_the_connector_alone(served: Served) -> None: + assert served.request("GET", "/app.css")[1]["Server"] == "odmdm-connector" + + +@pytest.mark.parametrize("host", ["example.fi", "127.0.0.1", "127.0.0.1:1", "attacker.example.fi:8737"]) +def test_another_host_is_refused(served: Served, host: str) -> None: + assert served.request("GET", "/", Host=host)[0] == 403 + assert served.request("GET", "/app.js", Host=host)[0] == 403 + assert served.request("GET", "/api/state", Host=host)[0] == 403 + assert served.request("POST", "/api/refresh", b"{}", Host=host, Origin=served.origin)[0] == 403 + + +@pytest.mark.parametrize("second", ["{host}", "example.fi"]) +def test_two_host_headers_are_refused(served: Served, second: str) -> None: + with socket.create_connection(("127.0.0.1", served.page.port), timeout=5) as raw: + raw.sendall( + f"GET /api/state HTTP/1.1\r\nHost: {served.host}\r\nHost: {second.format(host=served.host)}\r\n" + f"X-ODMDM-Key: {served.key}\r\nConnection: close\r\n\r\n".encode() + ) + answer = raw.recv(4096) + assert answer.startswith(b"HTTP/1.0 403") + + +def test_localhost_is_this_computer_too(served: Served) -> None: + host = f"localhost:{served.page.port}" + status, _, data = served.request("POST", "/api/refresh", b"{}", Host=host, Origin=f"http://{host}") + assert (status, json.loads(data)) == (200, {}) + + +@pytest.mark.parametrize("origin", [None, "http://example.fi", "null", "https://127.0.0.1:8737"]) +def test_a_post_from_anywhere_but_the_page_is_refused(served: Served, origin: str | None) -> None: + headers = {"Origin": origin} if origin else {} + status, _, body = served.request("POST", "/api/add", json.dumps({"line": LINE}).encode(), **headers) + + assert (status, body.decode()) == (403, web.FORBIDDEN) + assert served.rig.app.saved.connections == {} + + +@pytest.mark.parametrize( + ("body", "headers", "says"), + [ + (b"{}", {"Content-Length": str(web.LIMIT + 1)}, "The request has no length or is too large."), + (b"{", {}, "The request is not a JSON object."), + (b"[1]", {}, "The request is not a JSON object."), + (b"\xff", {}, "The request is not a JSON object."), + (b"[" * 5000 + b"]" * 5000, {}, "The request is not a JSON object."), + (b"{}", {"Content-Length": "-1"}, "The request has no length or is too large."), + ], +) +def test_a_broken_or_oversized_body_is_refused(served: Served, body: bytes, headers: dict[str, str], says: str) -> None: + status, _, answer = served.request("POST", "/api/refresh", body, Origin=served.origin, **headers) + + assert (status, answer.decode()) == (400, says) + + +def test_a_value_of_the_wrong_kind_is_said(served: Served) -> None: + assert served.post("/api/read", {"line": 1}, 400) == {"error": "The page sent line as something other than text."} + assert served.post("/api/again", {"ids": "a1"}, 400) == { + "error": "The page sent ids as something other than a list of text." + } + assert served.post("/api/connect", {"mdm": "fake", "values": {"group": 1}}, 400) == { + "error": "The page sent the values as something other than text." + } + assert served.post("/api/connect", {"mdm": "fake", "values": VALUES, "remember": "yes"}, 400) == { + "error": "The page sent remember as something other than yes or no." + } + assert served.post("/api/name", {"names": ["a1"]}, 400) == { + "error": "The page sent the names as something other than text." + } + assert served.post("/api/name", {"names": {}, "save": "yes"}, 400) == { + "error": "The page sent save as something other than yes or no." + } + + +@pytest.mark.parametrize( + ("path", "kind", "starts"), + [ + ("/", "text/html; charset=utf-8", b""), + ("/app.css", "text/css; charset=utf-8", b"/*"), + ("/app.js", "text/javascript; charset=utf-8", b'"use strict";'), + ], +) +def test_the_three_files_and_their_headers(served: Served, path: str, kind: str, starts: bytes) -> None: + status, headers, body = served.request("GET", path) + + assert (status, headers["Content-Type"]) == (200, kind) + assert body.startswith(starts) + for name, value in web.HEADERS.items(): + assert headers[name] == value + + +@pytest.mark.parametrize( + "path", ["/index.html", "/static/app.js", "/../pyproject.toml", "/%2e%2e/web.py", "/api/nothing", "/web.py"] +) +def test_nothing_else_is_served(served: Served, path: str) -> None: + status, headers, _ = served.request("GET", path) + + assert status == 404 + assert headers["Content-Security-Policy"] == web.HEADERS["Content-Security-Policy"] + assert served.request("POST", path, b"{}", Origin=served.origin)[0] == 404 + + +def test_http_servers_own_refusals_are_plain_and_carry_the_headers(served: Served) -> None: + status, headers, body = served.request("PUT", "/api/state") + assert (status, body) == (501, b"Unsupported method ('PUT')") + assert headers["X-Content-Type-Options"] == "nosniff" + + with socket.create_connection(("127.0.0.1", served.page.port), timeout=5) as raw: + raw.sendall(b"GET / HTTP/1.1\r\nX: " + b"a" * 70000 + b"\r\n\r\n") + answer = raw.recv(4096) + assert answer.startswith(b"HTTP/1.0 431") and b"Cache-Control: no-store" in answer + + +def test_an_idle_connection_does_not_delay_an_answer(served: Served) -> None: + """A browser opens spare connections and leaves them idle until the timeout""" + with ( + socket.create_connection(("127.0.0.1", served.page.port), timeout=5), + socket.create_connection(("127.0.0.1", served.page.port), timeout=5), + ): + began = time.monotonic() + assert served.request("GET", "/api/state")[0] == 200 + assert time.monotonic() - began < web.TIMEOUT / 2 + + +@pytest.mark.parametrize("failure", [ConnectionResetError(54, "Connection reset by peer"), TimeoutError("timed out")]) +def test_a_dropped_connection_is_one_line_naming_its_kind( + served: Served, caplog: pytest.LogCaptureFixture, failure: OSError +) -> None: + caplog.set_level(logging.DEBUG) + try: + raise failure + except OSError: + served.page.handle_error(None, ("127.0.0.1", 1)) + + [record] = caplog.records + assert record.getMessage() == f"A connection to the page ended: {type(failure).__name__}" + assert record.exc_info is None + + +def test_a_request_that_failed_otherwise_is_logged_whole(served: Served, caplog: pytest.LogCaptureFixture) -> None: + try: + raise RuntimeError("a bug") + except RuntimeError: + served.page.handle_error(None, ("127.0.0.1", 1)) + + [record] = caplog.records + assert (record.getMessage(), record.exc_info is not None) == ("The page could not answer a request", True) + + +def test_the_app_sees_one_caller_at_a_time(served: Served, monkeypatch: pytest.MonkeyPatch) -> None: + inside, most = [0], [0] + approval = served.rig.app.approval + + def slow(name: str) -> str: + inside[0] += 1 + most[0] = max(most[0], inside[0]) + time.sleep(0.05) + inside[0] -= 1 + return approval(name) + + monkeypatch.setattr(served.rig.app, "approval", slow) + callers = [threading.Thread(target=served.post, args=("/api/form", {"mdm": "fake"})) for _ in range(4)] + for each in callers: + each.start() + for each in callers: + each.join() + + assert most == [1] + + +def test_the_whole_flow(served: Served) -> None: + first = served.state() + assert (first["connections"], first["active"], first["connected"], first["needs"]) == ([], "", False, "") + assert first["keeps"] is False, "no keychain on this computer" + assert (first["steps"], first["setup_error"]) == ([], "") + assert [mdm["name"] for mdm in first["mdms"]] == ["fake", "demo"] + + reading = served.post("/api/read", {"line": LINE}) + assert reading == { + "host": "unit.example.fi", + "until": "Deploy App unit.example.fi accepts phones until 14:00.", + "known": False, + } + assert served.state()["connections"] == [], "reading takes nothing" + + added = served.post("/api/add", {"line": LINE}) + state = served.state() + assert added == {"said": "Deploy App unit.example.fi accepts phones until 14:00."} + assert (state["active"], state["needs"], state["banner"], state["mdm_page"]) == ( + "unit.example.fi", + "mdm", + {"level": "open", "text": "Deploy App unit.example.fi accepts phones until 14:00"}, + "https://mtls.unit.example.fi/mdm", + ) + + form = served.post("/api/form", {"mdm": "fake"}) + assert (form["title"], [(each["key"], each["value"], each["secret"], each["kept"]) for each in form["fields"]]) == ( + "Fake MDM", + [("group", "Deploy App", False, False), ("password", "", True, False)], + ) + + connected = served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + state = served.state() + assert connected == {"said": "Setting Fake MDM up for Deploy App unit.example.fi."} + assert [step["label"] for step in state["steps"]] == [ + "Group Deploy App enrols at https://unit.example.fi/scep", + "Certificate template stated", + ] + state = served.state() + assert (state["connected"], state["needs"], state["summary"]) == (True, "", "3 phones: 1 ready, 2 without a name") + assert state["rows"][2] == { + "id": "a3", + "callsign": "OTTER1", + "phone": "Pretend Tablet 2", + "joined": "2026-11-01 09:10", + "certificate": "has its certificate", + "waiting": False, + "failed": False, + "ready": True, + "askable": False, + } + assert served.post("/api/form", {"mdm": "fake"})["fields"][1]["kept"] is True + + numbered = {"ids": [], "how": "numbered", "prefix": "OTTER", "first": "", "list": ""} + preview = served.post("/api/preview", numbered) + assert (preview["ok"], preview["button"], preview["first"]) == (True, "Name 2 phones", 2) + assert [(row["id"], row["callsign"]) for row in preview["rows"]] == [("a1", "OTTER2"), ("a2", "OTTER3")] + + named = served.post("/api/name", {"names": {"a1": "OTTER2", "a2": "OTTER3"}, "how": "numbered", "prefix": "OTTER "}) + served.state() + state = served.state() + assert named == {"said": "Naming 2 phones."} + assert (state["status"], state["lines"]) == ("2 phones named.", ["Phone a1 is OTTER2", "Phone a2 is OTTER3"]) + assert (state["prefix"], state["callsigns"]) == ("OTTER", []) + + again = served.post("/api/again", {"ids": ["a1"]}) + assert again == {"said": "Asking again."} + detail = served.post("/api/detail", {"id": "a1"}) + assert (detail["callsign"], detail["state"], detail["can_ask_again"]) == ( + "OTTER2", + "requested, waiting for the phone", + True, + ) + + assert served.post("/api/remove", {"host": "unit.example.fi"}) == { + "said": "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + } + assert served.state()["connections"] == [] + + +def test_naming_from_a_list_names_what_the_preview_held(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + listed = {"ids": ["a1"], "how": "list", "list": "BEAR1\n\n BEAR2 \nBEAR3"} + shown = served.post("/api/preview", listed) + assert (shown["ok"], shown["rows"][0]["callsign"]) == (True, "BEAR1") + + named = served.post("/api/name", {"names": {"a1": "BEAR1"}, "how": "list", "list": listed["list"], "save": True}) + served.state() + state = served.state() + + assert named == {"said": "Naming 1 phone."} + assert (state["prefix"], state["callsigns"]) == ("", ["BEAR2", "BEAR3"]), "kept, less what was named" + + +def test_a_list_is_kept_only_when_saved(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + served.post("/api/preview", {"ids": ["a1"], "how": "list", "list": "BEAR1\nBEAR2"}) + + served.post("/api/name", {"names": {"a1": "BEAR1"}, "how": "list", "list": "BEAR1\nBEAR2", "save": False}) + + assert served.state()["callsigns"] == [] + + +def test_only_the_preview_that_passed_is_named(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + unseen = {"names": {"a1": "BEAR1"}, "how": "list", "list": "BEAR1", "save": True} + first = "Preview the callsigns first: nothing is named without a preview that passed." + + assert served.post("/api/name", unseen, 400) == {"error": first} + refused = served.post("/api/preview", {"ids": ["a1"], "how": "list", "list": "OTTER1"}) + assert (refused["ok"], refused["rows"][0]["refusal"]) == (False, "OTTER1 already belongs to phone a3") + assert served.post("/api/name", {**unseen, "names": {"a1": "OTTER1"}}, 400) == {"error": first} + served.post("/api/preview", {"ids": ["a1"], "how": "list", "list": "BEAR1"}) + assert served.post("/api/name", {**unseen, "names": {"a1": "BEAR2"}}, 400) == {"error": first} + too_few = served.post("/api/preview", {"ids": ["a1", "a2"], "how": "list", "list": "BEAR1"}) + assert (too_few["ok"], too_few["refusal"]) == (False, "2 phones to name, but only 1 callsign.") + assert served.post("/api/preview", {"how": "numbered", "prefix": "BEAR", "first": "x"}, 400) == { + "error": "The first number must be a whole number." + } + assert served.state()["callsigns"] == [], "nothing kept from a refusal" + assert served.request("POST", "/api/keep", b"{}", Origin=served.origin)[0] == 404 + + +def test_a_kept_secret_is_used_without_going_to_the_page(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + + served.post("/api/connect", {"mdm": "fake", "values": {"group": "Deploy App", "password": ""}}) + served.state() + + assert isinstance(served.rig.app.mdm, FakeMdm) + assert served.rig.app.mdm.values == VALUES + + +def test_a_kept_secret_is_not_sent_with_another_address(served: Served) -> None: + """Whoever can post to the page cannot have the kept token sent to a host of their choosing""" + served.rig.classes["fake"] = Addressed + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": TOKEN_VALUES}) + served.state() + Addressed.made.clear() + before = served.rig.app.saved + + moved = {**TOKEN_VALUES, "mdm_url": "https://attacker.example.fi", "token": ""} + refused = served.post("/api/connect", {"mdm": "fake", "values": moved}, 400) + + assert refused == {"error": "Type the Token again: the settings changed."} + assert Addressed.made == [] + assert served.rig.app.saved == before + + +def test_a_plugin_is_approved_and_its_challenge_given_by_hand(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + + asked = served.post("/api/form", {"mdm": "demo"}) + assert asked["approval"].startswith("The MDM demo comes from the package odmdm-connector-demo 1.0.0") + assert served.post("/api/approve", {"mdm": "demo"}) == {} + assert served.post("/api/form", {"mdm": "demo"})["title"] == "Fake MDM" + + served.post("/api/connect", {"mdm": "demo", "values": VALUES}) + state = served.state() + assert [(step["label"], step["done"]) for step in state["steps"]] == [("The fake MDM cannot setup", False)] + assert state["setup_error"] == "" + assert (state["challenge_note"], state["challenge"]) == ("The fake MDM cannot set_challenge", CHALLENGE) + assert served.post("/api/again", {"ids": []}, 400) == {"error": "The fake MDM cannot ask_again"} + + +def test_opening_a_deploy_app_and_the_refusals(served: Served) -> None: + other = LINE.replace("unit.example.fi", "other.example.fi") + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.post("/api/add", {"line": other}) + + assert served.post("/api/read", {"line": LINE})["known"] is True + assert served.post("/api/open", {"host": "unit.example.fi"}) == { + "said": "Deploy App unit.example.fi accepts phones until 14:00." + } + state = served.state() + assert state["connections"] == [ + {"host": "unit.example.fi", "level": "open", "short": "enrolment open until 14:00", "active": True}, + {"host": "other.example.fi", "level": "open", "short": "enrolment open until 14:00", "active": False}, + ] + assert state["mdm_page"] == "https://mtls.unit.example.fi/mdm" + assert state["connected"] + assert served.post("/api/open", {"host": "nowhere.example.fi"}, 400) == { + "error": "There is no Deploy App nowhere.example.fi in this app." + } + assert served.post("/api/read", {"line": "not a line"}, 400)["error"].startswith("This is not a settings line") + + +def test_the_page_that_sent_a_line_is_checked(served: Served) -> None: + sent = {"line": LINE, "from": "https://mtls.unit.example.fi"} + forged = {"line": LINE, "from": "https://other.example.fi"} + + assert served.post("/api/read", sent)["host"] == "unit.example.fi" + assert served.post("/api/add", forged, 400)["error"].startswith( + "These settings are for Deploy App unit.example.fi, but the page that sent them is https://other.example.fi" + ) + assert served.state()["connections"] == [] + assert served.post("/api/add", sent) == {"said": "Deploy App unit.example.fi accepts phones until 14:00."} + + +def test_the_phones_are_refreshed_every_minute_while_the_page_asks(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + fake = served.rig.app.mdm + assert isinstance(fake, FakeMdm) + fake.calls.clear() + + served.state() + served.rig.ticks += web.REFRESH + served.state() + served.state() + + assert fake.calls == ["phones"] + assert served.post("/api/refresh") == {} + served.state() + assert fake.calls == ["phones", "phones"] + + +def test_the_state_says_when_the_phones_were_last_listed(served: Served) -> None: + assert served.state()["updated"] == "" + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + + assert served.state()["updated"] == "12:00" + served.post("/api/add", {"line": LINE.replace("unit.example.fi", "other.example.fi")}) + assert served.state()["updated"] == "", "not the other Deploy App's" + + +def test_a_failure_is_one_sentence_pointing_at_the_log(served: Served, monkeypatch: pytest.MonkeyPatch) -> None: + def broken(name: str) -> str: + raise RuntimeError("a bug") + + monkeypatch.setattr(served.rig.app, "approval", broken) + + assert served.post("/api/form", {"mdm": "fake"}, 500) == { + "error": f"The connector failed; the log says more: {served.rig.app.log_path}" + } + + +def test_no_answer_and_no_log_line_holds_a_secret(served: Served, caplog: pytest.LogCaptureFixture) -> None: + caplog.set_level(logging.DEBUG) + served.post("/api/read", {"line": LINE}) + served.post("/api/add", {"line": LINE}) + served.post("/api/form", {"mdm": "fake"}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + served.post("/api/add", {"line": LINE}) + state = served.state() + served.post("/api/detail", {"id": "a1"}) + served.post("/api/read", {"line": LINE.replace("2026", "1999")}, 400) + + assert isinstance(served.rig.app.mdm, FakeMdm) + assert served.rig.app.mdm.challenge == CHALLENGE, "the MDM takes the challenge by API" + assert state["challenge"] == "" + logged = "\n".join(record.getMessage() for record in caplog.records) + for secret in (VALUES["password"], CHALLENGE, LINE, served.page.key): + assert secret not in logged + assert all(secret.encode() not in body for body in served.bodies) + + +def _web( + rig: WebRig, monkeypatch: pytest.MonkeyPatch, busy: bool = False, asked: threading.Event | None = None +) -> list[web.Page]: + """The web command will serve rig's App until a Ctrl+C, at once, with a job under way or none + + The connector's directory is rig's. Without asked, there is no desktop and no browser is asked; + with it, the Ctrl+C comes once the browser has been asked. + """ + monkeypatch.setattr(app.App, "default", lambda: rig.app) + monkeypatch.setattr(store, "directory", lambda: rig.directory) + if asked is None: + monkeypatch.setattr(browser, "can_open", lambda: False) + monkeypatch.setattr(rig.app, "busy", lambda job=None: busy) + started: list[web.Page] = [] + + def serve(page: web.Page, poll_interval: float = 0.5) -> None: + started.append(page) + if asked is not None: + assert asked.wait(5), "the browser was never asked" + raise KeyboardInterrupt + + monkeypatch.setattr(web.Page, "serve_forever", serve) + return started + + +def _free_port() -> int: + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port: int = probe.getsockname()[1] + return port + + +def test_the_web_command_prints_where_and_how_to_stop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + started = _web(WebRig(tmp_path / "config"), monkeypatch) + port = _free_port() + + assert console.main(["web", "--port", str(port)]) == 0 + printed = capsys.readouterr() + assert printed.out.splitlines() == [ + f"Open this address in your browser: http://127.0.0.1:{port}/#key={started[0].key}", + "Press Ctrl+C to stop it.", + ] + assert not printed.err + + +#: The real browser.can_open, which _web replaces +CAN_OPEN = browser.can_open + + +class Opener: + """The opener on a desktop: what it was handed and whether the file was there then, and its answer + + Once asked, it sets asked; it answers only once released is set. + """ + + def __init__(self, rig: WebRig, monkeypatch: pytest.MonkeyPatch, answer: bool = True) -> None: + self.rig, self.answer = rig, answer + self.handed: list[tuple[str, bool]] = [] + self.asked, self.released = threading.Event(), threading.Event() + self.released.set() + monkeypatch.setattr(browser, "can_open", CAN_OPEN) + monkeypatch.setattr(sys, "platform", "darwin") + monkeypatch.setattr("webbrowser.open", self) + + def __call__(self, url: str, new: int = 0, autoraise: bool = True) -> bool: + self.handed.append((url, (self.rig.directory / browser.NAME).is_file())) + self.asked.set() + self.released.wait(5) + return self.answer + + +def test_the_web_command_opens_the_page_in_the_browser_by_default( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + rig = WebRig(tmp_path / "config") + opener = Opener(rig, monkeypatch) + started = _web(rig, monkeypatch, asked=opener.asked) + port = _free_port() + + assert console.main(["web", "--port", str(port)]) == 0 + + assert opener.handed == [((rig.directory / browser.NAME).as_uri(), True)] + assert started[0].key not in opener.handed[0][0] + assert capsys.readouterr().out.splitlines() == [ + f"{console.OPENING} http://127.0.0.1:{port}/#key={started[0].key}", + "Press Ctrl+C to stop it.", + ] + assert not (rig.directory / browser.NAME).exists(), "removed when the connector stops" + + +def test_an_opener_that_waits_holds_up_neither_the_address_nor_the_page( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """A BROWSER command webbrowser does not know, a text browser or osascript waits for the browser""" + rig = WebRig(tmp_path / "config") + opener = Opener(rig, monkeypatch) + opener.released.clear() + monkeypatch.setattr(app.App, "default", lambda: rig.app) + monkeypatch.setattr(store, "directory", lambda: rig.directory) + pages: list[web.Page] = [] + serving = threading.Event() + serve = web.Page.serve_forever + + def watched(page: web.Page, poll_interval: float = 0.5) -> None: + pages.append(page) + serving.set() + serve(page, 0.01) + + monkeypatch.setattr(web.Page, "serve_forever", watched) + codes: list[int] = [] + command = threading.Thread(target=lambda: codes.append(console.main(["web", "--port", str(_free_port())]))) + command.start() + try: + assert opener.asked.wait(5) and serving.wait(5) + page = pages[0] + assert capsys.readouterr().out.splitlines() == [f"{console.OPENING} {page.address}", "Press Ctrl+C to stop it."] + connection = http.client.HTTPConnection("127.0.0.1", page.port, timeout=5) + try: + connection.request("GET", "/api/state", headers={"Host": f"127.0.0.1:{page.port}", "X-ODMDM-Key": page.key}) + assert connection.getresponse().status == 200 + finally: + connection.close() + assert command.is_alive() and not codes, "still serving while the opener waits" + finally: + opener.released.set() + if serving.wait(5): + pages[0].shutdown() + command.join(5) + assert codes == [0] + + +def test_without_a_desktop_the_address_is_printed_to_open( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + rig = WebRig(tmp_path / "config") + started = _web(rig, monkeypatch) + opener = Opener(rig, monkeypatch) + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.delenv("DISPLAY", raising=False) + monkeypatch.delenv("WAYLAND_DISPLAY", raising=False) + port = _free_port() + + assert console.main(["web", "--port", str(port)]) == 0 + + assert opener.handed == [] + assert capsys.readouterr().out.splitlines() == [ + f"{console.OPEN} http://127.0.0.1:{port}/#key={started[0].key}", + "Press Ctrl+C to stop it.", + ] + + +#: What a connector still running wrote into the file +RUNNING = "written by a connector still running" + + +def _running_connectors_file(rig: WebRig) -> Path: + """The file, as another connector on this computer wrote it and still needs it""" + rig.directory.mkdir(parents=True, exist_ok=True) + path = rig.directory / browser.NAME + path.write_text(RUNNING, encoding="utf-8") + return path + + +def test_with_no_browser_the_address_is_printed_to_open( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + rig = WebRig(tmp_path / "config") + started = _web(rig, monkeypatch) + opener = Opener(rig, monkeypatch) + running = _running_connectors_file(rig) + port = _free_port() + + assert console.main(["web", "--no-browser", "--port", str(port)]) == 0 + + assert opener.handed == [] + assert capsys.readouterr().out.splitlines() == [ + f"{console.OPEN} http://127.0.0.1:{port}/#key={started[0].key}", + "Press Ctrl+C to stop it.", + ] + assert running.read_text(encoding="utf-8") == RUNNING, "another connector's, left alone" + + +def test_when_the_browser_says_no_the_file_is_gone( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """The address was printed before the answer, with the sentence that says what to do if it does not open""" + rig = WebRig(tmp_path / "config") + opener = Opener(rig, monkeypatch, answer=False) + started = _web(rig, monkeypatch, asked=opener.asked) + port = _free_port() + + assert console.main(["web", "--port", str(port)]) == 0 + + assert len(opener.handed) == 1 + assert capsys.readouterr().out.splitlines()[0] == f"{console.OPENING} http://127.0.0.1:{port}/#key={started[0].key}" + assert not (rig.directory / browser.NAME).exists() + + +def test_ctrl_c_during_a_job_says_what_to_do_next( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """The MDM may be half way through it, and the phones' rows are from before""" + _web(WebRig(tmp_path / "config"), monkeypatch, busy=True) + + assert console.main(["web", "--port", str(_free_port())]) == 0 + assert capsys.readouterr().err == f"{console.STOPPED_BUSY}\n" + + +def test_the_web_command_says_when_the_port_is_taken( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """On a desktop: a connector may be running on that port, and its file is left alone""" + rig = WebRig(tmp_path / "config") + opener = Opener(rig, monkeypatch) + _web(rig, monkeypatch, asked=opener.asked) + running = _running_connectors_file(rig) + with socket.socket() as taken: + taken.bind(("127.0.0.1", 0)) + taken.listen() + port = taken.getsockname()[1] + + code = console.main(["web", "--port", str(port)]) + + said = capsys.readouterr().err + assert code == 1 + assert said.startswith(f"The page cannot listen on port {port} of this computer: ") + assert said.endswith(". Give another with --port.\n") + assert opener.handed == [] + assert running.read_text(encoding="utf-8") == RUNNING, "another connector's, left alone" + + +def test_the_web_command_says_the_connector_may_be_running_when_its_own_port_is_taken( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """Deploy App's button reaches the default port only, so another port is not the first advice""" + rig = WebRig(tmp_path / "config") + _web(rig, monkeypatch) + with socket.socket() as taken: + taken.bind(("127.0.0.1", 0)) + taken.listen() + monkeypatch.setattr(web, "PORT", taken.getsockname()[1]) + + code = console.main(["web"]) + + said = capsys.readouterr().err + assert code == 1 + assert "The connector may be running already: use its page." in said + assert said.endswith("as Deploy App's button reaches this port.\n") + + +def test_after_a_restart_the_token_is_typed_again_and_the_phones_listed(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + again = served.rig.start() + + page = web.Page(again, 0) + try: + needs = page.state()["needs"] + said = page.connect({"mdm": "fake", "values": VALUES}) + again.worker.wait() + again.drain() + assert needs == "secret" + assert said == {"said": "Connected to Fake MDM for Deploy App unit.example.fi."} + assert [row.id for row in again.rows(NOW)] == ["a1", "a2", "a3"], "listed once connected" + finally: + page.server_close() + again.close() + + +def test_a_failed_setup_is_said_beside_its_steps(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.rig.classes["fake"] = HalfSetUp + + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + state = served.state() + + assert [step["label"] for step in state["steps"]] == ["Group found"] + assert (state["setup_error"], state["connected"]) == ("The fake MDM refused the template", True) + served.rig.classes["fake"] = FakeMdm + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + assert served.state()["setup_error"] == "", "a new setup starts with no error" + + +def test_a_running_setups_steps_are_in_the_state_as_they_are_done(served: Served) -> None: + """A setup can take minutes: the page ticks each step when it is done, not all of them at the end""" + go = threading.Event() + + class Slow(FakeMdm): + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step("Group found", True) + go.wait(5) + yield Step("Certificate template stated", True) + + served.post("/api/add", {"line": LINE}) + served.rig.classes["fake"] = Slow + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + running: Any = {} + for _ in range(500): + running = json.loads(served.request("GET", "/api/state")[2]) + if running["steps"]: + break + time.sleep(0.01) + + assert ([step["label"] for step in running["steps"]], "setup" in running["busy"]) == (["Group found"], True) + go.set() + done = served.state() + assert [step["label"] for step in done["steps"]] == ["Group found", "Certificate template stated"] + assert "setup" not in done["busy"] + + +def test_the_token_is_kept_in_the_keychain_only_when_remembered(keyed: Served) -> None: + backend = keyed.rig.backend + assert backend is not None and keyed.state()["keeps"] is True + keyed.post("/api/add", {"line": LINE}) + + keyed.post("/api/connect", {"mdm": "fake", "values": VALUES, "remember": True}) + remembered = dict(backend.items) + said = [(each["kept"], each["remembered"]) for each in keyed.post("/api/form", {"mdm": "fake"})["fields"]] + keyed.post("/api/connect", {"mdm": "fake", "values": {"group": "Deploy App", "password": ""}}) + + assert remembered == {KEPT: VALUES["password"]} + assert said == [(False, False), (True, True)] + assert backend.items == {}, "remember left out is not remembered, and the kept copy goes" + assert keyed.post("/api/form", {"mdm": "fake"})["fields"][1]["remembered"] is False, ( + "held until the connector stops" + ) + assert keyed.state()["connected"] is True + + +@pytest.mark.parametrize(("mdm", "askable"), [(FakeMdm, True), (FakeMdm.lacking(ASK_AGAIN), False)]) +def test_the_phones_say_which_have_their_certificates_and_which_asking_again_can_help( + served: Served, mdm: type[FakeMdm], askable: bool +) -> None: + served.rig.classes["fake"] = mdm + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + fake = served.rig.app.mdm + assert isinstance(fake, FakeMdm) + fake.group = [replace(fake.group[0], callsign="OTTER2", state=State.REFUSED), *fake.group[1:]] + served.post("/api/refresh") + + rows = [(row["id"], row["ready"], row["askable"]) for row in served.state()["rows"]] + + assert rows == [("a1", False, askable), ("a2", False, False), ("a3", True, False)] + + +def test_the_policy_is_sent_again_from_the_page_its_steps_shown_as_a_setups(served: Served) -> None: + """Offered while the MDM connected can send it; its steps and its refusal take the setup's place""" + assert served.state()["policy"] == "" + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + offered = served.state()["policy"] + served.rig.classes["fake"] = HalfSetUp + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + assert served.state()["setup_error"] == "The fake MDM refused the template" + served.rig.classes["fake"] = FakeMdm + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + + said = served.post("/api/policy") + state = served.state() + + assert offered.startswith("For a phone whose browser refuses its certificate:") + assert said == {"said": "Sending the policy again for Deploy App unit.example.fi."} + assert [(step["label"], step["message"]) for step in state["steps"]] == [ + ("Group Deploy App enrols at https://unit.example.fi/scep", ""), + ("Certificate template stated", "forced"), + ] + assert (state["setup_error"], state["status"], "policy" in state["busy"]) == ( + "", + "Fake MDM has sent the policy again to the phones of Deploy App unit.example.fi.", + False, + ) + served.rig.classes["fake"] = HalfSetUp + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + served.post("/api/policy") + refused = served.state() + assert ([step["label"] for step in refused["steps"]], refused["setup_error"]) == ( + ["Group found"], + "The fake MDM refused the template", + ) + + +def test_the_policy_is_refused_for_an_mdm_that_cannot_send_it(served: Served) -> None: + served.rig.classes["fake"] = FakeMdm.lacking(SEND_POLICY) + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + + assert served.state()["policy"] == "" + assert served.post("/api/policy", status=400) == {"error": "The fake MDM cannot send_policy"} + + +class Terminal: + """A terminal's stdin or stdout, or a pipe's, as isatty says""" + + def __init__(self, tty: bool) -> None: + self.tty = tty + self.written: list[str] = [] + + def isatty(self) -> bool: + return self.tty + + def write(self, text: str) -> int: + self.written.append(text) + return len(text) + + def flush(self) -> None: + pass + + +@pytest.mark.parametrize( + ("command", "stdin", "stdout", "waits"), + [ + ([], True, True, True), + ([], False, True, False), + ([], True, False, False), + (["web"], True, True, False), + (["web", "--no-browser"], True, True, False), + ], +) +def test_a_second_start_by_a_double_click_waits_for_enter_on_a_terminal( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + command: list[str], + stdin: bool, + stdout: bool, + waits: bool, +) -> None: + """Its window on Windows would close before the sentence is read; with a command, a script must never hang""" + _web(WebRig(tmp_path / "config"), monkeypatch) + asked: list[str] = [] + + def enter(prompt: str = "") -> str: + asked.append(prompt) + raise EOFError + + monkeypatch.setattr("builtins.input", enter) + monkeypatch.setattr(sys, "stdin", Terminal(stdin)) + monkeypatch.setattr(sys, "stdout", Terminal(stdout)) + with socket.socket() as taken: + taken.bind(("127.0.0.1", 0)) + taken.listen() + monkeypatch.setattr(web, "PORT", taken.getsockname()[1]) + + code = console.main(command) + + assert code == 1 + assert "The connector may be running already: use its page." in capsys.readouterr().err + assert asked == ([console.PRESS_ENTER] if waits else []) + + +def test_the_team_card_suggests_the_deployments_team(served: Served) -> None: + served.rig.classes["fake"] = FleetFields + served.post("/api/add", {"line": GOLDEN}) + + [team] = [each for each in served.post("/api/form", {"mdm": "fake"})["fields"] if each["key"] == "team"] + + assert (team["value"], team["default"], team["required"]) == ( + "golden-monkey DeployApp", + "golden-monkey DeployApp", + True, + ) diff --git a/tox.ini b/tox.ini index 79e6235..6213311 100644 --- a/tox.ini +++ b/tox.ini @@ -13,7 +13,7 @@ passenv = SSH_AUTH_SOCK SKIP commands = - uv run docker/pre_commit_init.sh # also runs pre-commit + uv run prek run --all-files uv run pytest --junitxml=pytest-{envname}.xml tests/ # if pre-commit does not run these (or you don't run pre-commit here) enable at least these checks # uv run mypy src tests diff --git a/uv.lock b/uv.lock index 5185487..77e9c01 100644 --- a/uv.lock +++ b/uv.lock @@ -7,6 +7,15 @@ resolution-markers = [ "(python_full_version < '3.15' and sys_platform != 'emscripten') or (python_full_version < '3.12' and sys_platform == 'emscripten')", ] +[[package]] +name = "altgraph" +version = "0.17.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/f8/97fdf103f38fed6792a1601dbc16cc8aac56e7459a9fff08c812d8ae177a/altgraph-0.17.5.tar.gz", hash = "sha256:c87b395dd12fabde9c99573a9749d67da8d29ef9de0125c7f536699b4a9bc9e7", size = 48428, upload-time = "2025-11-21T20:35:50.583Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/ba/000a1996d4308bc65120167c21241a3b205464a2e0b58deda26ae8ac21d1/altgraph-0.17.5-py2.py3-none-any.whl", hash = "sha256:f3a22400bce1b0c701683820ac4f3b159cd301acab067c51c653e06961600597", size = 21228, upload-time = "2025-11-21T20:35:49.444Z" }, +] + [[package]] name = "annotated-types" version = "0.8.0" @@ -21,14 +30,23 @@ name = "anyio" version = "4.15.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.15'" }, + { name = "idna", marker = "python_full_version < '3.12' or python_full_version >= '3.15' or sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "(python_full_version < '3.15' and sys_platform != 'emscripten') or (python_full_version < '3.12' and sys_platform == 'emscripten')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, ] +[[package]] +name = "backports-tarfile" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/86/72/cd9b395f25e290e633655a100af28cb253e4393396264a98bd5f5951d50f/backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991", size = 86406, upload-time = "2024-05-28T17:01:54.731Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/fa/123043af240e49752f1c4bd24da5053b6bd00cad78c2be53c0d1e8b975bc/backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34", size = 30181, upload-time = "2024-05-28T17:01:53.112Z" }, +] + [[package]] name = "bandit" version = "1.9.4" @@ -91,6 +109,69 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "(python_full_version < '3.12' and implementation_name != 'PyPy') or (python_full_version >= '3.15' and implementation_name != 'PyPy') or (implementation_name != 'PyPy' and sys_platform != 'emscripten')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/5a/4707a0dc1f203f5dde5a907b0d4e3c25d71120241048bd5bc6f1bb9d4e71/cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0", size = 211805, upload-time = "2026-08-03T21:19:31.867Z" }, + { url = "https://files.pythonhosted.org/packages/ad/66/c19feabb28485b6e0bbaaafa90837a1ef5d302e90f2178bd33f17a49879b/cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813", size = 218716, upload-time = "2026-08-03T21:19:32.896Z" }, + { url = "https://files.pythonhosted.org/packages/a7/92/500760486c8baab49a7a8a58ba7fc3355ec3974b454b8a09e528efde9e1d/cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990", size = 205569, upload-time = "2026-08-03T21:19:34.142Z" }, + { url = "https://files.pythonhosted.org/packages/a5/a7/a67c733254d6e7373f7822f8082d8d6beade791e0cf12a7611f376fa61c7/cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af", size = 204907, upload-time = "2026-08-03T21:19:35.174Z" }, + { url = "https://files.pythonhosted.org/packages/f7/a4/4399daaf8f7dfee9d7c3327fdb0426ee041cc63edc358b93911ceb2bfc7a/cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632", size = 217807, upload-time = "2026-08-03T21:19:36.286Z" }, + { url = "https://files.pythonhosted.org/packages/28/f7/dabe6da2466ecbd82dc62e7342dc6b1065dad990c06f00f0ede9ebf2a0ed/cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd", size = 221252, upload-time = "2026-08-03T21:19:37.416Z" }, + { url = "https://files.pythonhosted.org/packages/ce/87/616202d8e51342c07d2534c510111c4cc37201775ce8f60802c9335d1edd/cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a", size = 214214, upload-time = "2026-08-03T21:19:38.507Z" }, + { url = "https://files.pythonhosted.org/packages/b4/c6/ab025d75d2c26c19b087c0124e75ee31cb65032f4fe345d356d8c507ab97/cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa", size = 219408, upload-time = "2026-08-03T21:19:39.809Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, +] + [[package]] name = "charset-normalizer" version = "3.5.2" @@ -382,6 +463,65 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c9/17/48032919343afa2906112d458aceda2043afdb24a2ee8eb4c60904d8ddf1/coverage-7.17.0-py3-none-any.whl", hash = "sha256:bac487dce0d2aff28ddf1a533a916f771416eee0e493960f611e49037b878e9d", size = 217383, upload-time = "2026-10-22T16:06:48.471Z" }, ] +[[package]] +name = "cryptography" +version = "50.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "(python_full_version < '3.12' and platform_python_implementation != 'PyPy') or (python_full_version >= '3.15' and platform_python_implementation != 'PyPy') or (platform_python_implementation != 'PyPy' and sys_platform != 'emscripten')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" }, + { url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" }, + { url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" }, + { url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" }, + { url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" }, + { url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" }, + { url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" }, + { url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" }, + { url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" }, + { url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" }, + { url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" }, + { url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" }, + { url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" }, + { url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" }, + { url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" }, + { url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" }, + { url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" }, + { url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" }, + { url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" }, + { url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" }, + { url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" }, + { url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" }, + { url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" }, + { url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" }, + { url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" }, + { url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" }, + { url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" }, +] + [[package]] name = "detect-secrets" version = "1.5.0" @@ -422,19 +562,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] -[[package]] -name = "httpcore" -version = "1.0.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "h11" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, -] - [[package]] name = "httpcore2" version = "2.16.0" @@ -448,21 +575,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" }, ] -[[package]] -name = "httpx" -version = "0.28.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "certifi" }, - { name = "httpcore" }, - { name = "idna" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, -] - [[package]] name = "httpx2" version = "2.16.0" @@ -498,6 +610,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, ] +[[package]] +name = "importlib-metadata" +version = "10.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "lazy-importer", marker = "(python_full_version < '3.15' and sys_platform != 'emscripten') or (python_full_version < '3.12' and sys_platform == 'emscripten')" }, + { name = "zipp", marker = "(python_full_version < '3.15' and sys_platform != 'emscripten') or (python_full_version < '3.12' and sys_platform == 'emscripten')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a6/91/0ef39e4ef4407de276289a3759977ac3a8cc546f59c55d725750eae3f41b/importlib_metadata-10.2.0.tar.gz", hash = "sha256:9413a2029fd9ca5669d27f1386071bbfe3c7ebca0545692ec975088241fe1d79", size = 72457, upload-time = "2026-11-09T19:09:10.915Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/61/0c0fae37eb561d8fddb788cbae0f227051628d70d67498a8a116c1f547d7/importlib_metadata-10.2.0-py3-none-any.whl", hash = "sha256:c7a4bf1c7479601f6b8e437cfc14f4f77028ba62a8f34ae95cd93d9774dfba51", size = 34109, upload-time = "2026-11-09T19:09:09.942Z" }, +] + [[package]] name = "iniconfig" version = "2.3.1" @@ -508,12 +633,75 @@ wheels = [ ] [[package]] -name = "libadvian" -version = "1.9.0" +name = "jaraco-classes" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "more-itertools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/c0/ed4a27bc5571b99e3cff68f8a9fa5b56ff7df1c2251cc715a652ddd26402/jaraco.classes-3.4.0.tar.gz", hash = "sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd", size = 11780, upload-time = "2024-03-31T07:27:36.643Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/66/b15ce62552d84bbfcec9a4873ab79d993a1dd4edb922cbfccae192bd5b5f/jaraco.classes-3.4.0-py3-none-any.whl", hash = "sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790", size = 6777, upload-time = "2024-03-31T07:27:34.792Z" }, +] + +[[package]] +name = "jaraco-context" +version = "6.1.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "backports-tarfile", marker = "python_full_version < '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/af/50/4763cd07e722bb6285316d390a164bc7e479db9d90daa769f22578f698b4/jaraco_context-6.1.2.tar.gz", hash = "sha256:f1a6c9d391e661cc5b8d39861ff077a7dc24dc23833ccee564b234b81c82dfe3", size = 16801, upload-time = "2026-03-20T22:13:33.922Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f2/58/bc8954bda5fcda97bd7c19be11b85f91973d67a706ed4a3aec33e7de22db/jaraco_context-6.1.2-py3-none-any.whl", hash = "sha256:bf8150b79a2d5d91ae48629d8b427a8f7ba0e1097dd6202a9059f29a36379535", size = 7871, upload-time = "2026-03-20T22:13:32.808Z" }, +] + +[[package]] +name = "jaraco-functools" +version = "4.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "more-itertools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6c/1f/c23395957d41ccf27c4e535c3d334c4051e5395b3752057ba4cbaec35c56/jaraco_functools-4.6.0.tar.gz", hash = "sha256:880c577ec9720b3a052d5bc611fb9f2269b3d87902ef42440df443b88e443280", size = 20837, upload-time = "2026-07-14T01:28:02.544Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/36/ecc85bc96c273dc8a11273ed4782272975e6338d4a3e9228621175edf0e3/jaraco_functools-4.6.0-py3-none-any.whl", hash = "sha256:99e3dc0060c5cbe8fcd1cdb36258e2a65ca40f1566b2033b12abb1bb44dd3c30", size = 11677, upload-time = "2026-07-14T01:28:01.59Z" }, +] + +[[package]] +name = "jeepney" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6f/357efd7602486741aa73ffc0617fb310a29b588ed0fd69c2399acbb85b0c/jeepney-0.9.0.tar.gz", hash = "sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732", size = 106758, upload-time = "2025-02-27T18:51:01.684Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", hash = "sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683", size = 49010, upload-time = "2025-02-27T18:51:00.104Z" }, +] + +[[package]] +name = "keyring" +version = "25.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "importlib-metadata", marker = "python_full_version < '3.12'" }, + { name = "jaraco-classes" }, + { name = "jaraco-context" }, + { name = "jaraco-functools" }, + { name = "jeepney", marker = "sys_platform == 'linux'" }, + { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" }, + { name = "secretstorage", marker = "sys_platform == 'linux'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/4b/674af6ef2f97d56f0ab5153bf0bfa28ccb6c3ed4d1babf4305449668807b/keyring-25.7.0.tar.gz", hash = "sha256:fe01bd85eb3f8fb3dd0405defdeac9a5b4f6f0439edbb3149577f244a2e8245b", size = 63516, upload-time = "2025-11-16T16:26:09.482Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/db/e655086b7f3a705df045bf0933bdd9c2f79bb3c97bfef1384598bb79a217/keyring-25.7.0-py3-none-any.whl", hash = "sha256:be4a0b195f149690c166e850609a477c532ddbfbaed96a404d4e43f8d5e2689f", size = 39160, upload-time = "2025-11-16T16:26:08.402Z" }, +] + +[[package]] +name = "lazy-importer" +version = "0.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f2/e9/86ce7c1ffb486abe8506909a8c41db6da2de9703a0326a10178b205d47ae/libadvian-1.9.0.tar.gz", hash = "sha256:97c78963cb08a70d856be409faa3c9f9bb088787d036dfce68b8e449a199b736", size = 14334, upload-time = "2025-05-23T13:38:27.089Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/23/d2c8308466a6831043ac3518e480c2e1a06b21a13e0a8f6542ab29cf592a/lazy_importer-0.1.0.tar.gz", hash = "sha256:b2e296716ce015c0cd80e57b940e52727c5b934b34b8656d5ce06bdd0ee5fbdd", size = 84008, upload-time = "2026-10-20T00:36:58.369Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/47/95f5435cd98c9fe52a8bfaeeaade1fc97ec75ee86f05c054c67b122af5d4/libadvian-1.9.0-py3-none-any.whl", hash = "sha256:2461145e0980c9af95480f063d565c01cd68f52c90f19818ec5efbc537d1f702", size = 16085, upload-time = "2025-05-23T13:38:26.018Z" }, + { url = "https://files.pythonhosted.org/packages/0a/28/7ded071d0975dcc6d5d106ffbf7b3ca420f7caa3b8a235fa604b6e37032a/lazy_importer-0.1.0-py3-none-any.whl", hash = "sha256:bd93fab7bef18e842eea02b839410954d37889140dc64ca4d9680aec6880c739", size = 12580, upload-time = "2026-10-20T00:36:57.176Z" }, ] [[package]] @@ -632,6 +820,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/69/7a5d10ac409c4da0355e054a14371871da9b5557fcc42772cd00181c6cce/librt-0.16.0-cp315-cp315t-win_arm64.whl", hash = "sha256:8ceafb70f2a4f0826f11031942e59c0728fd98da112dc346d4352bde1e486866", size = 116391, upload-time = "2026-09-29T00:55:07.484Z" }, ] +[[package]] +name = "macholib" +version = "1.16.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "altgraph", marker = "python_full_version < '3.12' or python_full_version >= '3.15' or sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/10/2f/97589876ea967487978071c9042518d28b958d87b17dceb7cdc1d881f963/macholib-1.16.4.tar.gz", hash = "sha256:f408c93ab2e995cd2c46e34fe328b130404be143469e41bc366c807448979362", size = 59427, upload-time = "2025-11-22T08:28:38.373Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/d1/a9f36f8ecdf0fb7c9b1e78c8d7af12b8c8754e74851ac7b94a8305540fc7/macholib-1.16.4-py2.py3-none-any.whl", hash = "sha256:da1a3fa8266e30f0ce7e97c6a54eefaae8edd1e5f86f3eb8b95457cae90265ea", size = 38117, upload-time = "2025-11-22T08:28:36.939Z" }, +] + [[package]] name = "markdown-it-py" version = "4.2.0" @@ -653,6 +853,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, ] +[[package]] +name = "more-itertools" +version = "11.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/52/b8/c63995bebbb9ac9c059350e0fb8c82c2420c85aeca7d34e40aecf3df9281/more_itertools-11.2.1.tar.gz", hash = "sha256:cbf08fd0af284dc69718b9b76a8e6203df624d70209ea511e4219d350c856f63", size = 154133, upload-time = "2026-10-14T18:50:30.407Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/57/3c4b1c6f2e0cc29ba023802458ea3d2a996f87085559e4a5f2192d549532/more_itertools-11.2.1-py3-none-any.whl", hash = "sha256:35a7377edd1dd6608dcb2cdf534ded55ea32d49448875ad042cd3f879fb1ded0", size = 74405, upload-time = "2026-10-14T18:50:29.116Z" }, +] + [[package]] name = "mypy" version = "1.20.2" @@ -713,13 +922,11 @@ wheels = [ ] [[package]] -name = "odmdm-fleet" -version = "0.1.0+261031" +name = "odmdm-connector" +version = "1.5.0+261122" source = { editable = "." } dependencies = [ - { name = "click" }, - { name = "httpx" }, - { name = "libadvian" }, + { name = "keyring" }, ] [package.dev-dependencies] @@ -736,13 +943,12 @@ dev = [ { name = "tox" }, { name = "tox-uv" }, ] +dist = [ + { name = "pyinstaller" }, +] [package.metadata] -requires-dist = [ - { name = "click", specifier = ">=8.1,<9.0" }, - { name = "httpx", specifier = ">=0.28,<1.0" }, - { name = "libadvian", specifier = ">=1.4,<2.0" }, -] +requires-dist = [{ name = "keyring", specifier = ">=25.6,<26.0" }] [package.metadata.requires-dev] dev = [ @@ -758,6 +964,7 @@ dev = [ { name = "tox", specifier = ">=4.0,<5.0" }, { name = "tox-uv", specifier = ">=1.0,<2.0" }, ] +dist = [{ name = "pyinstaller", specifier = ">=6.22,<7" }] [[package]] name = "packaging" @@ -777,6 +984,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, ] +[[package]] +name = "pefile" +version = "2024.8.26" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/03/4f/2750f7f6f025a1507cd3b7218691671eecfd0bbebebe8b39aa0fe1d360b8/pefile-2024.8.26.tar.gz", hash = "sha256:3ff6c5d8b43e8c37bb6e6dd5085658d658a7a0bdcd20b6a07b1fcfc1c4e9d632", size = 76008, upload-time = "2024-08-26T20:58:38.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/16/12b82f791c7f50ddec566873d5bdd245baa1491bac11d15ffb98aecc8f8b/pefile-2024.8.26-py3-none-any.whl", hash = "sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f", size = 74766, upload-time = "2024-08-26T21:01:02.632Z" }, +] + [[package]] name = "platformdirs" version = "4.14.2" @@ -824,6 +1040,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" }, ] +[[package]] +name = "pycparser" +version = "3.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cb/27/eeb9f307bf07060f3d9f9aa0fb8c15b01bdfded0a941e4b2719c7f94cacd/pycparser-3.12.tar.gz", hash = "sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6", size = 158785, upload-time = "2026-10-22T13:40:03.56Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/ae/315bbeee126a769cbde43cf4908acb4b40408d8bf8bbf334dd7368d8dadf/pycparser-3.12-py3-none-any.whl", hash = "sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e", size = 62600, upload-time = "2026-10-22T13:40:02.021Z" }, +] + [[package]] name = "pydantic" version = "2.14.2" @@ -1000,6 +1225,46 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, ] +[[package]] +name = "pyinstaller" +version = "6.22.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "altgraph" }, + { name = "macholib", marker = "sys_platform == 'darwin'" }, + { name = "packaging" }, + { name = "pefile", marker = "sys_platform == 'win32'" }, + { name = "pyinstaller-hooks-contrib" }, + { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" }, + { name = "setuptools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/63/41/f90302845945abd4ed647933ff5ee7c6ac93983187be67f897b6cb613331/pyinstaller-6.22.3.tar.gz", hash = "sha256:05eb2f5615503e72939a7224d68b4aff572c6b0438ee4a17d0a4b481f399362d", size = 4437180, upload-time = "2026-09-12T21:54:09.669Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/af/898f70947e27f8e65d55183c780e77112e023c0b4a6fba6255d4d563a27d/pyinstaller-6.22.3-py3-none-macosx_10_13_universal2.whl", hash = "sha256:052f4a1cd4f81092ccb7a18fe8ebc9ecf832a5917317e39fb3775af4e959b253", size = 1071847, upload-time = "2026-09-12T21:53:01.711Z" }, + { url = "https://files.pythonhosted.org/packages/c4/96/99f5184985141c2b024bfa61335e9142ae444555224f303186e59b7bb438/pyinstaller-6.22.3-py3-none-manylinux2014_aarch64.whl", hash = "sha256:312da84b4b31ab9750066a823734c11b7c68757fdd67c9f038bf19c330a954e4", size = 758172, upload-time = "2026-09-12T21:53:06.171Z" }, + { url = "https://files.pythonhosted.org/packages/69/9f/9ccb12cc1e6617042cb028fe79f0a756f5f03305bd14b584a4e043fe3844/pyinstaller-6.22.3-py3-none-manylinux2014_i686.whl", hash = "sha256:020d4fe0627f5c73dfbcfad1a6578ef354d5fe4bdccd9d8e5a615528f5a45d2b", size = 772135, upload-time = "2026-09-12T21:53:10.291Z" }, + { url = "https://files.pythonhosted.org/packages/c1/43/4b1d5193a88628c052db89f064433681076959a9f41d0d9f660001b49079/pyinstaller-6.22.3-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:9e4f7bd64b2103f14b4a6240fb9155e9fe7bc61391b4043bbddb7d3ebc8ab0fa", size = 770461, upload-time = "2026-09-12T21:53:14.592Z" }, + { url = "https://files.pythonhosted.org/packages/cb/83/f173f8757c618d83e116fa2b8e57c5cd796e5ad09792e664eabd6ac5edae/pyinstaller-6.22.3-py3-none-manylinux2014_s390x.whl", hash = "sha256:f82d0fb89f21c3ed6f482ee16f341bc59e8a31dbabb9bae9ef04e53ade4dc0d9", size = 764997, upload-time = "2026-09-12T21:53:19.079Z" }, + { url = "https://files.pythonhosted.org/packages/7b/b6/dd21d61fc5e25377be24eabf13e99e4e46548a5abe2bf7b15d8b3d9cc74a/pyinstaller-6.22.3-py3-none-manylinux2014_x86_64.whl", hash = "sha256:451a4ae14b719365bf1a2f0a99dae7b3463060061c3a394c70d5264cfb439528", size = 764974, upload-time = "2026-09-12T21:53:23.176Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fd/d9590942972b1fc205519f7ccffb0d5cd8eb1d6fa61edad319c71d25baed/pyinstaller-6.22.3-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:ea240b5dfa831ff673c97505eee0ec24670bccf71396c83109440348944c83d0", size = 764450, upload-time = "2026-09-12T21:53:27.419Z" }, + { url = "https://files.pythonhosted.org/packages/72/d6/f22c55d1768433b65c460b19a3136dd9769b6c74b786149b829344654c7d/pyinstaller-6.22.3-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:a2b6fc26601e8c2596c3d54981566934a3382e85d05d0fe91b55b6a8dcc6b282", size = 763863, upload-time = "2026-09-12T21:53:31.609Z" }, + { url = "https://files.pythonhosted.org/packages/c5/87/cf28cfd42ceca889171e6dd5e7f1553d4372db83d047049ffb7cf95fcbd4/pyinstaller-6.22.3-py3-none-win32.whl", hash = "sha256:46a3e30a118341a1ec20667a5a95aa7e0aa8c4fa129893c0151b3eb3f801a722", size = 1390905, upload-time = "2026-09-12T21:53:38.133Z" }, + { url = "https://files.pythonhosted.org/packages/24/83/c5422204772a27aef643280fdc887b7ef55679989096b21dceb1b9625fc4/pyinstaller-6.22.3-py3-none-win_amd64.whl", hash = "sha256:500bd58c7bf7e584a8435adccbd763a0b918d5c12b08d74ff50fd79b2915458b", size = 1454907, upload-time = "2026-09-12T21:53:44.812Z" }, + { url = "https://files.pythonhosted.org/packages/67/2e/ebc93968bf63f81b122e205da116b16036b653b7ce2cc8ad86e3ddd19586/pyinstaller-6.22.3-py3-none-win_arm64.whl", hash = "sha256:31df3cc4261e804a53d358b7897c293ec8b88b167a7cca06c78018085c855f97", size = 1402956, upload-time = "2026-09-12T21:53:51.369Z" }, +] + +[[package]] +name = "pyinstaller-hooks-contrib" +version = "2026.10" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/45/87/9a32062fb1296b43e866ec78313f887e12b09e6bc344c694647856bcd907/pyinstaller_hooks_contrib-2026.10.tar.gz", hash = "sha256:7e906c659522e592a1680f30f709ffb6333277141a695926aa7190592205c5e3", size = 181831, upload-time = "2026-11-10T00:20:01.695Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/08/10/4a6d13adaa93d0bbcfea082a78965e970cae7a8bfa82ac1557a1dc8f1cba/pyinstaller_hooks_contrib-2026.10-py3-none-any.whl", hash = "sha256:dfc3cde20a7ce6c92e803016e66eed4b7050467e2c5f886a3745d89b258c6d6d", size = 463652, upload-time = "2026-11-10T00:20:00.335Z" }, +] + [[package]] name = "pyproject-api" version = "1.12.2" @@ -1062,6 +1327,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" }, ] +[[package]] +name = "pywin32-ctypes" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471, upload-time = "2024-08-14T10:15:34.626Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756, upload-time = "2024-08-14T10:15:33.187Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -1196,6 +1470,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/99/d5/4ad4ed31413c301430918e70d3d38ae6f097af0766cb9ab8c9d502b2a4d6/ruff-0.17.3-py3-none-win_arm64.whl", hash = "sha256:81fce74bcd6be0e9da7c67c7553fd0f1f12964a2052cd728ef917b937a5ca1d9", size = 9854332, upload-time = "2026-10-27T00:34:03.847Z" }, ] +[[package]] +name = "secretstorage" +version = "3.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography", marker = "python_full_version < '3.12' or python_full_version >= '3.15' or sys_platform != 'emscripten'" }, + { name = "jeepney", marker = "python_full_version < '3.12' or python_full_version >= '3.15' or sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/46/f5af3402b579fd5e11573ce652019a67074317e18c1935cc0b4ba9b35552/secretstorage-3.5.0-py3-none-any.whl", hash = "sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137", size = 15554, upload-time = "2025-11-23T19:02:51.545Z" }, +] + +[[package]] +name = "setuptools" +version = "84.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" }, +] + [[package]] name = "stevedore" version = "5.9.1" @@ -1398,3 +1694,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4e/cc/7eeb28059186cae72a770df79e744f232ef068192a5a588b718473e35bb4/wcwidth-0.9.4-cp315-cp315t-win_arm64.whl", hash = "sha256:2cca7b5d0b9d0ae49068d3ce806e965326a987f555b62eaa322223396e10d01b", size = 605198, upload-time = "2026-10-24T18:11:33.75Z" }, { url = "https://files.pythonhosted.org/packages/6f/0c/309b1813b230d1dbbd6f2c2ab2bb21ef68992358977605d9ef289bbfedcc/wcwidth-0.9.4-py3-none-any.whl", hash = "sha256:901eace6d2dd25ebb917d0ce5db18e5c537e1504c905cf32f0d006c12098b05d", size = 301806, upload-time = "2026-10-24T18:10:52.651Z" }, ] + +[[package]] +name = "zipp" +version = "4.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/05/ba1458dee0ac485b2a01071c1b88f5199fe878a485df482e10e1ef2205cc/zipp-4.1.2.tar.gz", hash = "sha256:cf474b90b07ea932637e17c6b9479de2b2882900b0d311bdaf4f5c000a15a97f", size = 27864, upload-time = "2026-10-21T18:57:04.743Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/44/7bd2007260da11cccca29ba2d4c345f1287aa663db38ee7cefeabf6386a5/zipp-4.1.2-py3-none-any.whl", hash = "sha256:b30cb6cd253122169c47de245ca24a86bac2a5d3802ba15bf7ba6414eb9e144d", size = 10581, upload-time = "2026-10-21T18:57:03.79Z" }, +]