commit 03a80187296b50572eb350485a28f80c89085c90 Author: MeghdadFadaee Date: Wed Aug 26 17:08:49 2026 +0330 Initial diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..93c0639 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.py] +indent_style = space +indent_size = 4 + +[*.{md,toml,yml,yaml}] +indent_style = space +indent_size = 2 + diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b9d4ba0 --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +# Copy this file to .env and replace every value. +# Never put the contents of the .p8 private key in this file. +ASC_ISSUER_ID="00000000-0000-0000-0000-000000000000" +ASC_KEY_ID="ABCDE12345" +ASC_PRIVATE_KEY_PATH="/absolute/path/to/AuthKey_ABCDE12345.p8" + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..af2773f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + name: Python ${{ matrix.python-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12", "3.13", "3.14"] + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + + - name: Install project + run: pip install -e '.[dev]' + + - name: Lint + run: ruff check . + + - name: Test + run: pytest + + - name: Build distributions + if: matrix.python-version == '3.14' + run: python -m build + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3ad1811 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.idea/ +.venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.coverage +htmlcov/ +.env +*.p8 +dist/ +build/ +private-keys/ +*.egg-info/ + diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c735fae --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +All notable changes to this project will be documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.1.0] - 2026-08-26 + +### Added + +- Rich member and invitation dashboard. +- Effective provisioning-access diagnostics. +- Member role, app visibility, and provisioning updates. +- User invitations, invitation cancellation, and guarded member removal. +- `.env` configuration with automatic `600` permissions. +- JSON output for automation. + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..8962a53 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,27 @@ +# Contributing + +Thanks for helping improve Apple Team CLI. + +## Local setup + +```bash +python3 -m venv .venv +. .venv/bin/activate +pip install -e '.[dev]' +ruff check . +pytest +python -m build +``` + +Tests must use `httpx.MockTransport` and must never contact Apple or require real credentials. + +## Pull requests + +- Keep changes focused and explain the user-facing behavior. +- Add or update tests for behavior changes. +- Never include Apple Account data, Issuer IDs, Key IDs, JWTs, `.env` files, or `.p8` keys. +- Preserve confirmations around destructive or externally mutating commands. +- Update the README when adding commands or configuration. + +By contributing, you agree that your contributions are licensed under the MIT License. + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..dc679f7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 Apple Team CLI contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..5f758a8 --- /dev/null +++ b/README.md @@ -0,0 +1,121 @@ +# Apple Team CLI + +A modern terminal dashboard for auditing and managing App Store Connect team access. It makes the effective permissions Apple returns—especially `provisioningAllowed`—visible instead of relying on role names alone. + +> [!IMPORTANT] +> This is an independent open-source project. It is not affiliated with, endorsed by, or supported by Apple Inc. + +![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-3776AB) + +## Features + +- Rich dashboard for active members and pending invitations +- Effective **Certificates, Identifiers & Profiles** status +- Individual-membership access diagnosis +- Search members by email, name, or Apple resource ID +- Update roles, all-app visibility, and provisioning access +- Invite users and cancel pending invitations +- Guarded member removal with interactive confirmation +- JSON output for scripts and CI +- Short-lived JWTs generated in memory; tokens and private-key contents are never stored + +## Install + +```bash +python3 -m venv .venv +. .venv/bin/activate +pip install -e . +``` + +## Configure with `.env` + +Create a **Team API Key** in [App Store Connect → Users and Access → Integrations](https://appstoreconnect.apple.com/access/integrations/api). An Admin key is needed for user management. + +Copy the template and set all three values: + +```bash +cp .env.example .env +``` + +```dotenv +ASC_ISSUER_ID="00000000-0000-0000-0000-000000000000" +ASC_KEY_ID="ABCDE12345" +ASC_PRIVATE_KEY_PATH="/absolute/path/to/AuthKey_ABCDE12345.p8" +``` + +Or generate `.env` interactively: + +```bash +apple-team configure \ + --issuer-id 00000000-0000-0000-0000-000000000000 \ + --key-id ABCDE12345 \ + --private-key ~/Downloads/AuthKey_ABCDE12345.p8 + +apple-team doctor +``` + +The configure command automatically applies `chmod 600` to both `.env` and the selected private key. The CLI finds `.env` from the current directory upward. Existing shell environment variables take precedence. The private key remains at the referenced path and is never copied into the repository. `.env` and all `.p8` files are gitignored. + +## Use + +```bash +# Team overview +apple-team dashboard +apple-team dashboard --json + +# Member audit +apple-team members list +apple-team members show developer@example.com + +# Access changes (previewed and confirmed) +apple-team members enable-provisioning developer@example.com +apple-team members update developer@example.com --role admin --all-apps --provisioning + +# Invitations +apple-team invites list +apple-team invites send \ + --email developer@example.com \ + --first-name Ada \ + --last-name Lovelace \ + --role admin \ + --all-apps \ + --provisioning + +# Destructive actions always prompt unless --yes is explicit +apple-team invites cancel developer@example.com +apple-team members remove developer@example.com +``` + +Run `apple-team COMMAND --help` for every option. + +## Apple limitations + +The CLI can request only what Apple's API and your API-key role permit. In particular: + +- Individual Apple Developer Program memberships can invite App Store Connect users, but those users aren't members of the Developer Program team and cannot receive Certificates, Identifiers & Profiles access. +- Only the Account Holder can accept agreements, renew membership, and perform other holder-only actions. +- Invitations expire after three days. +- Apple may reject incompatible role combinations or permissions. + +This tool surfaces Apple's error message without logging the JWT or private key. + +## Development + +```bash +pip install -e '.[dev]' +ruff check . +pytest +python -m build +``` + +Tests use an in-memory mock transport and never contact Apple. + +## Security + +Never commit `.env` files or `.p8` keys. If a key is exposed, revoke it immediately in App Store Connect and create a replacement. See [SECURITY.md](SECURITY.md) for vulnerability reporting. + +## License + +Released under the [MIT License](LICENSE). + +Apple, App Store Connect, and related marks are trademarks of Apple Inc. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..d0f64a4 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Reporting a vulnerability + +Please do not open a public issue for a vulnerability that could expose credentials or modify an App Store Connect account. Use GitHub's **Report a vulnerability** feature in the repository Security tab to submit a private report. + +Include the affected version, reproduction steps, expected impact, and any suggested mitigation. Do not include a working App Store Connect private key, JWT, or personal team data. + +## Credential handling + +- API JWTs are short-lived and generated only in memory. +- `.env` and `*.p8` are excluded from Git. +- `apple-team configure` restricts `.env` and the selected key to mode `600`. +- The CLI does not print JWTs or private-key contents. + +If a private key may have been exposed, revoke it immediately in **App Store Connect → Users and Access → Integrations**, then generate a replacement. + +## Supported versions + +Security fixes are provided for the latest release on the default branch while the project is in alpha. + diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..9d549b4 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,61 @@ +[build-system] +requires = ["hatchling>=1.26"] +build-backend = "hatchling.build" + +[project] +name = "apple-team-cli" +version = "0.1.0" +description = "A modern CLI for auditing and managing App Store Connect team access" +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +license-files = ["LICENSE"] +authors = [{ name = "Apple Team CLI contributors" }] +keywords = ["apple", "app-store-connect", "cli", "developer-tools"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Environment :: Console", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Software Development :: Build Tools", +] +dependencies = [ + "httpx>=0.27,<1", + "pyjwt[crypto]>=2.9,<3", + "python-dotenv>=1.0,<2", + "rich>=13.9,<15", + "typer>=0.15,<1", +] + +[project.optional-dependencies] +dev = [ + "build>=1.2,<2", + "pytest>=8.3,<10", + "pytest-cov>=6,<8", + "ruff>=0.12,<1", +] + +[project.scripts] +apple-team = "apple_team_cli.cli:app" + +[tool.hatch.build.targets.wheel] +packages = ["src/apple_team_cli"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-q" + +[tool.coverage.run] +source = ["apple_team_cli"] + +[tool.ruff] +target-version = "py311" +line-length = 100 + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B", "SIM"] diff --git a/src/apple_team_cli/__init__.py b/src/apple_team_cli/__init__.py new file mode 100644 index 0000000..1a687f9 --- /dev/null +++ b/src/apple_team_cli/__init__.py @@ -0,0 +1,4 @@ +"""Apple Team CLI.""" + +__version__ = "0.1.0" + diff --git a/src/apple_team_cli/__main__.py b/src/apple_team_cli/__main__.py new file mode 100644 index 0000000..5e9b514 --- /dev/null +++ b/src/apple_team_cli/__main__.py @@ -0,0 +1,5 @@ +from .cli import app + +if __name__ == "__main__": + app() + diff --git a/src/apple_team_cli/api.py b/src/apple_team_cli/api.py new file mode 100644 index 0000000..03fa2de --- /dev/null +++ b/src/apple_team_cli/api.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import time +from collections.abc import Iterable +from typing import Any + +import httpx + +from .auth import create_token +from .config import Settings +from .models import Invitation, TeamUser + + +class AppleAPIError(RuntimeError): + def __init__(self, status_code: int, message: str, details: tuple[str, ...] = ()) -> None: + super().__init__(message) + self.status_code = status_code + self.details = details + + +class AmbiguousMatchError(LookupError): + pass + + +class AppleClient: + def __init__(self, settings: Settings, transport: httpx.BaseTransport | None = None) -> None: + self.settings = settings + self._client = httpx.Client( + base_url=settings.base_url, + timeout=30, + headers={"Accept": "application/json"}, + transport=transport, + ) + + def __enter__(self) -> AppleClient: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def close(self) -> None: + self._client.close() + + def _request(self, method: str, url: str, **kwargs: Any) -> httpx.Response: + headers = dict(kwargs.pop("headers", {})) + headers["Authorization"] = f"Bearer {create_token(self.settings)}" + response: httpx.Response | None = None + for attempt in range(3): + try: + response = self._client.request(method, url, headers=headers, **kwargs) + except httpx.RequestError as exc: + raise AppleAPIError(0, f"Could not reach Apple: {exc}") from exc + if response.status_code != 429 and response.status_code < 500: + break + if attempt < 2: + retry_after = response.headers.get("retry-after", "") + delay = float(retry_after) if retry_after.isdigit() else 0.5 * (2**attempt) + time.sleep(min(delay, 5)) + + assert response is not None + if response.is_error: + details: list[str] = [] + try: + for item in response.json().get("errors", []): + title = item.get("title", "Apple API error") + detail = item.get("detail", "") + details.append(f"{title}: {detail}".rstrip(": ")) + except ValueError: + details.append(response.text[:500] or response.reason_phrase) + raise AppleAPIError( + response.status_code, + f"Apple API returned HTTP {response.status_code}", + tuple(details), + ) + return response + + def _list(self, url: str, params: dict[str, Any]) -> list[dict[str, Any]]: + resources: list[dict[str, Any]] = [] + next_url: str | None = url + next_params: dict[str, Any] | None = params + while next_url: + response = self._request("GET", next_url, params=next_params) + body = response.json() + resources.extend(body.get("data", [])) + next_url = body.get("links", {}).get("next") + next_params = None + return resources + + def list_users(self) -> list[TeamUser]: + fields = "username,firstName,lastName,roles,allAppsVisible,provisioningAllowed" + resources = self._list( + "/v1/users", + {"fields[users]": fields, "limit": 200, "sort": "lastName"}, + ) + return [TeamUser.from_resource(item) for item in resources] + + def get_user(self, identifier: str) -> TeamUser: + return _match(identifier, self.list_users(), "username") + + def update_user( + self, + user: TeamUser, + *, + roles: Iterable[str] | None = None, + provisioning_allowed: bool | None = None, + all_apps_visible: bool | None = None, + ) -> TeamUser: + attrs: dict[str, Any] = {} + if roles is not None: + attrs["roles"] = list(roles) + if provisioning_allowed is not None: + attrs["provisioningAllowed"] = provisioning_allowed + if all_apps_visible is not None: + attrs["allAppsVisible"] = all_apps_visible + body = {"data": {"type": "users", "id": user.id, "attributes": attrs}} + resource = self._request("PATCH", f"/v1/users/{user.id}", json=body).json()["data"] + return TeamUser.from_resource(resource) + + def remove_user(self, user: TeamUser) -> None: + self._request("DELETE", f"/v1/users/{user.id}") + + def list_invitations(self) -> list[Invitation]: + fields = ( + "email,firstName,lastName,expirationDate,roles,allAppsVisible," + "provisioningAllowed" + ) + resources = self._list( + "/v1/userInvitations", + {"fields[userInvitations]": fields, "limit": 200, "sort": "lastName"}, + ) + return [Invitation.from_resource(item) for item in resources] + + def get_invitation(self, identifier: str) -> Invitation: + return _match(identifier, self.list_invitations(), "email") + + def invite_user( + self, + *, + email: str, + first_name: str, + last_name: str, + roles: Iterable[str], + provisioning_allowed: bool, + all_apps_visible: bool, + ) -> Invitation: + body = { + "data": { + "type": "userInvitations", + "attributes": { + "email": email, + "firstName": first_name, + "lastName": last_name, + "roles": list(roles), + "provisioningAllowed": provisioning_allowed, + "allAppsVisible": all_apps_visible, + }, + } + } + resource = self._request("POST", "/v1/userInvitations", json=body).json()["data"] + return Invitation.from_resource(resource) + + def cancel_invitation(self, invitation: Invitation) -> None: + self._request("DELETE", f"/v1/userInvitations/{invitation.id}") + + +def _match(identifier: str, items: list[Any], email_attr: str) -> Any: + needle = identifier.casefold() + exact = [ + item + for item in items + if item.id.casefold() == needle or getattr(item, email_attr).casefold() == needle + ] + if len(exact) == 1: + return exact[0] + partial = [ + item + for item in items + if needle in getattr(item, email_attr).casefold() or needle in item.name.casefold() + ] + if len(partial) == 1: + return partial[0] + if not partial: + raise LookupError(f"No match for {identifier!r}.") + choices = ", ".join(getattr(item, email_attr) for item in partial) + raise AmbiguousMatchError(f"Multiple matches for {identifier!r}: {choices}") + diff --git a/src/apple_team_cli/auth.py b/src/apple_team_cli/auth.py new file mode 100644 index 0000000..942aa4d --- /dev/null +++ b/src/apple_team_cli/auth.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +import time + +import jwt + +from .config import Settings + + +def create_token(settings: Settings, lifetime_seconds: int = 600) -> str: + """Create an ES256 App Store Connect team JWT valid for at most 20 minutes.""" + now = int(time.time()) + payload = { + "iss": settings.issuer_id, + "iat": now, + "exp": now + min(lifetime_seconds, 1_200), + "aud": "appstoreconnect-v1", + } + private_key = settings.private_key_path.read_text(encoding="utf-8") + return jwt.encode( + payload, + private_key, + algorithm="ES256", + headers={"kid": settings.key_id, "typ": "JWT"}, + ) + diff --git a/src/apple_team_cli/cli.py b/src/apple_team_cli/cli.py new file mode 100644 index 0000000..57b8c14 --- /dev/null +++ b/src/apple_team_cli/cli.py @@ -0,0 +1,408 @@ +from __future__ import annotations + +import json +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Annotated, Any + +import typer +from rich import box +from rich.panel import Panel +from rich.table import Table + +from . import __version__ +from .api import AmbiguousMatchError, AppleAPIError, AppleClient +from .config import ConfigError, Settings, write_config +from .models import ROLE_VALUES, TeamUser +from .ui import ( + access_diagnostic, + console, + error_console, + invitations_table, + logo, + role_text, + summary_panel, + users_table, + yes_no, +) + +app = typer.Typer( + name="apple-team", + help="Audit and manage your App Store Connect team.", + no_args_is_help=True, + rich_markup_mode="rich", + pretty_exceptions_enable=False, +) +members_app = typer.Typer(help="Inspect and manage active team members.", no_args_is_help=True) +invites_app = typer.Typer(help="Send and manage team invitations.", no_args_is_help=True) +app.add_typer(members_app, name="members") +app.add_typer(invites_app, name="invites") + + +def version_callback(value: bool) -> None: + if value: + console.print(f"apple-team [bold cyan]{__version__}[/bold cyan]") + raise typer.Exit() + + +@app.callback() +def main( + version: Annotated[ + bool | None, + typer.Option("--version", callback=version_callback, is_eager=True, help="Show version."), + ] = None, +) -> None: + """A secure, modern terminal dashboard for Apple's team API.""" + + +@contextmanager +def client_session() -> Iterator[AppleClient]: + try: + settings = Settings.load() + with AppleClient(settings) as client: + yield client + except (ConfigError, AppleAPIError, LookupError, AmbiguousMatchError) as exc: + show_error(exc) + raise typer.Exit(1) from exc + + +def show_error(exc: Exception) -> None: + if isinstance(exc, AppleAPIError): + lines = list(exc.details) or [str(exc)] + if exc.status_code == 403: + lines.append("The API key role may not permit this operation.") + message = "\n".join(f"• {line}" for line in lines) + else: + message = str(exc) + error_console.print( + Panel(message, title="[bold red]Unable to continue[/bold red]", border_style="red") + ) + + +def normalize_roles(values: list[str]) -> tuple[str, ...]: + normalized = tuple(dict.fromkeys(value.strip().upper().replace("-", "_") for value in values)) + invalid = [value for value in normalized if value not in ROLE_VALUES] + if invalid: + allowed = ", ".join(role.lower() for role in ROLE_VALUES) + raise typer.BadParameter(f"Unknown role(s): {', '.join(invalid)}. Allowed: {allowed}") + return normalized + + +def print_json(data: Any) -> None: + console.print_json(json.dumps(data, default=str)) + + +@app.command() +def configure( + issuer_id: Annotated[str, typer.Option(prompt=True, help="App Store Connect issuer UUID.")], + key_id: Annotated[str, typer.Option(prompt=True, help="Ten-character API key ID.")], + private_key: Annotated[ + Path, + typer.Option(prompt=True, help="Path to the downloaded AuthKey_*.p8 file."), + ], + env_file: Annotated[ + Path, + typer.Option("--env-file", help="Destination .env file."), + ] = Path(".env"), +) -> None: + """Save all three authentication settings to a gitignored .env file.""" + try: + path = write_config(issuer_id, key_id, private_key, env_file) + settings = Settings( + issuer_id.strip(), key_id.strip(), private_key.expanduser().resolve() + ) + settings.validate() + settings.secure_private_key() + except (ConfigError, OSError) as exc: + show_error(exc) + raise typer.Exit(1) from exc + console.print( + Panel.fit( + f"Configuration saved to [cyan]{path}[/cyan]\n" + f"Private key protected: [green]chmod 600 {settings.private_key_path}[/green]", + border_style="green", + ) + ) + + +@app.command() +def doctor() -> None: + """Validate configuration, private-key security, and Apple connectivity.""" + try: + settings = Settings.load() + except ConfigError as exc: + show_error(exc) + raise typer.Exit(1) from exc + + checks = Table(box=box.ROUNDED, show_header=False) + checks.add_column("Check") + checks.add_column("Status") + checks.add_row("Configuration", "[green]● Valid[/green]") + checks.add_row( + "Private key permissions", + "[green]● Private[/green]" + if settings.key_permissions_are_private + else "[yellow]● Run chmod 600[/yellow]", + ) + try: + with AppleClient(settings) as client: + count = len(client.list_users()) + checks.add_row("Apple API", f"[green]● Connected ({count} members)[/green]") + except AppleAPIError as exc: + checks.add_row("Apple API", f"[red]● {exc}[/red]") + console.print(checks) + show_error(exc) + raise typer.Exit(1) from exc + console.print(Panel(checks, title=logo(), border_style="bright_blue")) + + +@app.command() +def dashboard( + as_json: Annotated[bool, typer.Option("--json", help="Emit machine-readable JSON.")] = False, +) -> None: + """Show team health, members, invitations, and access warnings.""" + with client_session() as client: + users = client.list_users() + invitations = client.list_invitations() + if as_json: + print_json( + { + "members": [user.as_dict() for user in users], + "invitations": [invite.as_dict() for invite in invitations], + } + ) + return + console.print(summary_panel(users, invitations)) + console.print(users_table(users)) + if invitations: + console.print("\n[bold bright_white]Pending invitations[/bold bright_white]") + console.print(invitations_table(invitations)) + diagnostic = access_diagnostic(users) + if diagnostic: + console.print(diagnostic) + + +@members_app.command("list") +def members_list( + as_json: Annotated[bool, typer.Option("--json", help="Emit machine-readable JSON.")] = False, +) -> None: + """List every active team member and their effective access.""" + with client_session() as client: + users = client.list_users() + if as_json: + print_json([user.as_dict() for user in users]) + else: + console.print(Panel.fit(logo(), border_style="bright_blue")) + console.print(users_table(users)) + + +@members_app.command("show") +def members_show( + member: Annotated[str, typer.Argument(help="Email, name fragment, or Apple resource ID.")], + as_json: Annotated[bool, typer.Option("--json", help="Emit machine-readable JSON.")] = False, +) -> None: + """Show one member's effective permissions.""" + with client_session() as client: + user = client.get_user(member) + if as_json: + print_json(user.as_dict()) + return + details = Table(box=None, show_header=False, padding=(0, 2)) + details.add_row("Apple Account", user.username) + details.add_row("Role", role_text(user.roles)) + details.add_row("App visibility", yes_no(user.all_apps_visible, "All apps", "Limited")) + details.add_row("Certificates & IDs", yes_no(user.provisioning_allowed)) + details.add_row("Resource ID", f"[dim]{user.id}[/dim]") + console.print(Panel(details, title=f"[bold]{user.name}[/bold]", border_style="bright_blue")) + + +@members_app.command("update") +def members_update( + member: Annotated[str, typer.Argument(help="Email, name fragment, or resource ID.")], + roles: Annotated[ + list[str] | None, + typer.Option("--role", help="Replacement role; repeat for multiple roles."), + ] = None, + provisioning: Annotated[ + bool | None, + typer.Option( + "--provisioning/--no-provisioning", + help="Certificates, IDs & Profiles access.", + ), + ] = None, + all_apps: Annotated[ + bool | None, + typer.Option("--all-apps/--limited-apps", help="Whether all apps are visible."), + ] = None, + yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation.")] = False, +) -> None: + """Change a member's roles and effective access.""" + if roles is None and provisioning is None and all_apps is None: + raise typer.BadParameter("Provide --role, --provisioning, or --all-apps.") + normalized_roles = normalize_roles(roles) if roles is not None else None + with client_session() as client: + user = client.get_user(member) + if user.is_holder: + show_error(ValueError("The Account Holder cannot be modified through this command.")) + raise typer.Exit(1) + console.print(_change_preview(user, normalized_roles, provisioning, all_apps)) + if not yes and not typer.confirm("Apply these changes?"): + raise typer.Abort() + updated = client.update_user( + user, + roles=normalized_roles, + provisioning_allowed=provisioning, + all_apps_visible=all_apps, + ) + console.print(f"[green]✓ Updated[/green] [bold]{updated.name}[/bold]") + console.print(users_table([updated])) + + +@members_app.command("enable-provisioning") +def enable_provisioning( + member: Annotated[str, typer.Argument(help="Email, name fragment, or resource ID.")], + yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation.")] = False, +) -> None: + """Grant Certificates, Identifiers & Profiles access when Apple permits it.""" + with client_session() as client: + user = client.get_user(member) + if user.provisioning_allowed: + console.print(f"[green]✓ {user.name} already has provisioning access.[/green]") + return + console.print( + Panel( + f"Enable provisioning for [bold]{user.name}[/bold] ({user.username})?", + border_style="yellow", + ) + ) + if not yes and not typer.confirm("Continue?"): + raise typer.Abort() + updated = client.update_user(user, provisioning_allowed=True) + console.print( + f"[green]✓ Provisioning enabled for {updated.name}.[/green]" + if updated.provisioning_allowed + else ( + "[yellow]Apple accepted the update, but effective provisioning " + "remains blocked.[/yellow]" + ) + ) + + +@members_app.command("remove") +def members_remove( + member: Annotated[str, typer.Argument(help="Email, name fragment, or resource ID.")], + yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation.")] = False, +) -> None: + """Permanently remove a member from the App Store Connect team.""" + with client_session() as client: + user = client.get_user(member) + if user.is_holder: + show_error(ValueError("The Account Holder cannot be removed.")) + raise typer.Exit(1) + console.print( + Panel( + f"Remove [bold]{user.name}[/bold]\n{user.username}\n\n" + "Their team access will be revoked.", + title="[bold red]Destructive action[/bold red]", + border_style="red", + ) + ) + if not yes and not typer.confirm("Remove this member?"): + raise typer.Abort() + client.remove_user(user) + console.print(f"[green]✓ Removed {user.username}[/green]") + + +@invites_app.command("list") +def invites_list( + as_json: Annotated[bool, typer.Option("--json", help="Emit machine-readable JSON.")] = False, +) -> None: + """List pending invitations and expiration status.""" + with client_session() as client: + invitations = client.list_invitations() + if as_json: + print_json([invite.as_dict() for invite in invitations]) + elif invitations: + console.print(invitations_table(invitations)) + else: + console.print(Panel.fit("[green]✓ No pending invitations[/green]", border_style="green")) + + +@invites_app.command("send") +def invites_send( + email: Annotated[str, typer.Option(prompt=True, help="Recipient email address.")], + first_name: Annotated[str, typer.Option(prompt=True, help="Recipient first name.")], + last_name: Annotated[str, typer.Option(prompt=True, help="Recipient last name.")], + roles: Annotated[ + list[str] | None, + typer.Option("--role", help="Role to grant; repeat for multiple roles."), + ] = None, + provisioning: Annotated[ + bool, + typer.Option("--provisioning/--no-provisioning", help="Request Certificates & IDs access."), + ] = False, + all_apps: Annotated[ + bool, + typer.Option("--all-apps/--limited-apps", help="Make every app visible."), + ] = True, + yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation.")] = False, +) -> None: + """Email a three-day App Store Connect team invitation.""" + normalized_roles = normalize_roles(roles or ["DEVELOPER"]) + preview = Table(box=box.ROUNDED, show_header=False) + preview.add_row("Invitee", f"[bold]{first_name} {last_name}[/bold]") + preview.add_row("Email", email) + preview.add_row("Roles", role_text(normalized_roles)) + preview.add_row("Apps", yes_no(all_apps, "All", "Limited")) + preview.add_row("Provisioning", yes_no(provisioning)) + console.print(Panel(preview, title="Invitation preview", border_style="bright_blue")) + if not yes and not typer.confirm("Send this invitation?"): + raise typer.Abort() + with client_session() as client: + invitation = client.invite_user( + email=email, + first_name=first_name, + last_name=last_name, + roles=normalized_roles, + provisioning_allowed=provisioning, + all_apps_visible=all_apps, + ) + console.print(f"[green]✓ Invitation sent to {invitation.email}[/green]") + + +@invites_app.command("cancel") +def invites_cancel( + invitation: Annotated[str, typer.Argument(help="Email, name fragment, or resource ID.")], + yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation.")] = False, +) -> None: + """Cancel a pending team invitation.""" + with client_session() as client: + invite = client.get_invitation(invitation) + if not yes and not typer.confirm(f"Cancel the invitation for {invite.email}?"): + raise typer.Abort() + client.cancel_invitation(invite) + console.print(f"[green]✓ Canceled invitation for {invite.email}[/green]") + + +def _change_preview( + user: TeamUser, + roles: tuple[str, ...] | None, + provisioning: bool | None, + all_apps: bool | None, +) -> Panel: + table = Table(box=box.SIMPLE, show_header=True, header_style="bold") + table.add_column("Permission") + table.add_column("Current") + table.add_column("Requested") + if roles is not None: + table.add_row("Roles", role_text(user.roles), role_text(roles)) + if provisioning is not None: + table.add_row("Provisioning", yes_no(user.provisioning_allowed), yes_no(provisioning)) + if all_apps is not None: + table.add_row( + "App visibility", + yes_no(user.all_apps_visible, "All", "Limited"), + yes_no(all_apps, "All", "Limited"), + ) + return Panel(table, title=f"Update {user.name}", border_style="yellow") diff --git a/src/apple_team_cli/config.py b/src/apple_team_cli/config.py new file mode 100644 index 0000000..7bc0439 --- /dev/null +++ b/src/apple_team_cli/config.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +import os +import re +import stat +import tomllib +from dataclasses import dataclass +from pathlib import Path + +from dotenv import find_dotenv, load_dotenv + +DEFAULT_CONFIG_PATH = Path("~/.config/apple-team/config.toml").expanduser() +DEFAULT_BASE_URL = "https://api.appstoreconnect.apple.com" +DEFAULT_ENV_PATH = Path(".env") +UUID_PATTERN = re.compile( + r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" +) +KEY_ID_PATTERN = re.compile(r"^[A-Z0-9]{10}$") + + +class ConfigError(ValueError): + """Raised when authentication configuration is missing or invalid.""" + + +@dataclass(frozen=True, slots=True) +class Settings: + issuer_id: str + key_id: str + private_key_path: Path + base_url: str = DEFAULT_BASE_URL + + @classmethod + def load(cls, config_path: Path = DEFAULT_CONFIG_PATH) -> Settings: + env_file = find_dotenv(usecwd=True) + if env_file: + load_dotenv(env_file, override=False) + + file_values: dict[str, str] = {} + if config_path.exists(): + try: + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + file_values = parsed.get("app_store_connect", {}) + except (OSError, tomllib.TOMLDecodeError) as exc: + raise ConfigError(f"Cannot read {config_path}: {exc}") from exc + + issuer_id = os.getenv("ASC_ISSUER_ID", file_values.get("issuer_id", "")).strip() + key_id = os.getenv("ASC_KEY_ID", file_values.get("key_id", "")).strip() + raw_key_path = os.getenv( + "ASC_PRIVATE_KEY_PATH", file_values.get("private_key_path", "") + ).strip() + base_url = os.getenv( + "ASC_BASE_URL", file_values.get("base_url", DEFAULT_BASE_URL) + ).rstrip("/") + + missing = [ + name + for name, value in ( + ("ASC_ISSUER_ID", issuer_id), + ("ASC_KEY_ID", key_id), + ("ASC_PRIVATE_KEY_PATH", raw_key_path), + ) + if not value + ] + if missing: + raise ConfigError( + "Missing configuration: " + + ", ".join(missing) + + ". Run `apple-team configure` or set the environment variables." + ) + + key_path = Path(raw_key_path).expanduser().resolve() + settings = cls(issuer_id, key_id, key_path, base_url) + settings.validate() + return settings + + def validate(self) -> None: + if not UUID_PATTERN.fullmatch(self.issuer_id): + raise ConfigError("Issuer ID must be an Apple UUID.") + if not KEY_ID_PATTERN.fullmatch(self.key_id): + raise ConfigError("Key ID must contain 10 uppercase letters or digits.") + if not self.private_key_path.is_file(): + raise ConfigError(f"Private key not found: {self.private_key_path}") + try: + first_line = self.private_key_path.read_text(encoding="utf-8").splitlines()[0] + except (OSError, IndexError, UnicodeDecodeError) as exc: + raise ConfigError(f"Cannot read private key: {exc}") from exc + if first_line != "-----BEGIN PRIVATE KEY-----": + raise ConfigError("The selected file is not an App Store Connect .p8 private key.") + + @property + def key_permissions_are_private(self) -> bool: + mode = stat.S_IMODE(self.private_key_path.stat().st_mode) + return mode & (stat.S_IRWXG | stat.S_IRWXO) == 0 + + def secure_private_key(self) -> None: + """Restrict the private key to its owner on POSIX systems.""" + self.private_key_path.chmod(0o600) + + +def write_config( + issuer_id: str, + key_id: str, + private_key_path: Path, + config_path: Path = DEFAULT_ENV_PATH, +) -> Path: + settings = Settings(issuer_id.strip(), key_id.strip(), private_key_path.expanduser().resolve()) + settings.validate() + config_path = config_path.expanduser().resolve() + config_path.parent.mkdir(parents=True, exist_ok=True) + body = ( + "# App Store Connect API credentials. This file is gitignored.\n" + f'ASC_ISSUER_ID="{settings.issuer_id}"\n' + f'ASC_KEY_ID="{settings.key_id}"\n' + f'ASC_PRIVATE_KEY_PATH="{settings.private_key_path}"\n' + ) + config_path.write_text(body, encoding="utf-8") + config_path.chmod(0o600) + return config_path diff --git a/src/apple_team_cli/models.py b/src/apple_team_cli/models.py new file mode 100644 index 0000000..d03b3c4 --- /dev/null +++ b/src/apple_team_cli/models.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +ROLE_VALUES = ( + "ADMIN", + "FINANCE", + "SALES", + "MARKETING", + "APP_MANAGER", + "DEVELOPER", + "CUSTOMER_SUPPORT", + "ACCESS_TO_REPORTS", + "CREATE_APPS", + "CLOUD_MANAGED_DEVELOPER_ID", + "CLOUD_MANAGED_APP_DISTRIBUTION", + "GENERATE_INDIVIDUAL_KEYS", +) + + +def display_role(role: str) -> str: + return role.replace("_", " ").title() + + +@dataclass(frozen=True, slots=True) +class TeamUser: + id: str + username: str + first_name: str + last_name: str + roles: tuple[str, ...] + all_apps_visible: bool + provisioning_allowed: bool + + @classmethod + def from_resource(cls, resource: dict[str, Any]) -> TeamUser: + attrs = resource.get("attributes", {}) + return cls( + id=resource["id"], + username=attrs.get("username", ""), + first_name=attrs.get("firstName", ""), + last_name=attrs.get("lastName", ""), + roles=tuple(attrs.get("roles", ())), + all_apps_visible=bool(attrs.get("allAppsVisible")), + provisioning_allowed=bool(attrs.get("provisioningAllowed")), + ) + + @property + def name(self) -> str: + return f"{self.first_name} {self.last_name}".strip() + + @property + def is_holder(self) -> bool: + return "ACCOUNT_HOLDER" in self.roles + + def as_dict(self) -> dict[str, Any]: + return { + "id": self.id, + "username": self.username, + "name": self.name, + "roles": list(self.roles), + "allAppsVisible": self.all_apps_visible, + "provisioningAllowed": self.provisioning_allowed, + } + + +@dataclass(frozen=True, slots=True) +class Invitation: + id: str + email: str + first_name: str + last_name: str + expiration_date: str + roles: tuple[str, ...] + all_apps_visible: bool + provisioning_allowed: bool + + @classmethod + def from_resource(cls, resource: dict[str, Any]) -> Invitation: + attrs = resource.get("attributes", {}) + return cls( + id=resource["id"], + email=attrs.get("email", ""), + first_name=attrs.get("firstName", ""), + last_name=attrs.get("lastName", ""), + expiration_date=attrs.get("expirationDate", ""), + roles=tuple(attrs.get("roles", ())), + all_apps_visible=bool(attrs.get("allAppsVisible")), + provisioning_allowed=bool(attrs.get("provisioningAllowed")), + ) + + @property + def name(self) -> str: + return f"{self.first_name} {self.last_name}".strip() + + @property + def expired(self) -> bool: + if not self.expiration_date: + return False + value = self.expiration_date.replace("Z", "+00:00") + return datetime.fromisoformat(value) < datetime.now().astimezone() + + def as_dict(self) -> dict[str, Any]: + return { + "id": self.id, + "email": self.email, + "name": self.name, + "expirationDate": self.expiration_date, + "roles": list(self.roles), + "allAppsVisible": self.all_apps_visible, + "provisioningAllowed": self.provisioning_allowed, + } diff --git a/src/apple_team_cli/ui.py b/src/apple_team_cli/ui.py new file mode 100644 index 0000000..aed9891 --- /dev/null +++ b/src/apple_team_cli/ui.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from collections.abc import Sequence + +from rich import box +from rich.console import Console +from rich.panel import Panel +from rich.table import Table +from rich.text import Text + +from .models import Invitation, TeamUser, display_role + +console = Console() +error_console = Console(stderr=True) + + +def logo() -> Text: + title = Text("● apple", style="bold bright_white") + title.append(" team", style="bold bright_cyan") + return title + + +def yes_no(value: bool, enabled: str = "Enabled", disabled: str = "Blocked") -> Text: + return Text(f"● {enabled}" if value else f"● {disabled}", style="green" if value else "red") + + +def role_text(roles: Sequence[str]) -> Text: + value = ", ".join(display_role(role) for role in roles) or "No role" + style = "bold magenta" if "ACCOUNT_HOLDER" in roles else "cyan" + return Text(value, style=style) + + +def users_table(users: Sequence[TeamUser]) -> Table: + table = Table(box=box.ROUNDED, header_style="bold bright_white", expand=True) + table.add_column("Member", min_width=18) + table.add_column("Apple Account", min_width=24) + table.add_column("Role", min_width=18) + table.add_column("Apps", justify="center") + table.add_column("Provisioning", justify="center") + for user in users: + name = Text(user.name or "—", style="bold white") + if user.is_holder: + name.append(" ◆", style="magenta") + table.add_row( + name, + user.username, + role_text(user.roles), + yes_no(user.all_apps_visible, "All", "Limited"), + yes_no(user.provisioning_allowed), + ) + return table + + +def invitations_table(invitations: Sequence[Invitation]) -> Table: + table = Table(box=box.ROUNDED, header_style="bold bright_white", expand=True) + table.add_column("Invitee", min_width=18) + table.add_column("Email", min_width=24) + table.add_column("Role", min_width=18) + table.add_column("Expires") + table.add_column("Provisioning", justify="center") + for invite in invitations: + expiry = Text(invite.expiration_date or "—", style="red" if invite.expired else "yellow") + table.add_row( + Text(invite.name or "—", style="bold white"), + invite.email, + role_text(invite.roles), + expiry, + yes_no(invite.provisioning_allowed), + ) + return table + + +def summary_panel(users: Sequence[TeamUser], invitations: Sequence[Invitation]) -> Panel: + admins = sum("ADMIN" in user.roles for user in users) + provisioning = sum(user.provisioning_allowed for user in users) + text = Text() + text.append(f"{len(users)}", style="bold bright_white") + text.append(" members ") + text.append(f"{admins}", style="bold bright_cyan") + text.append(" admins ") + text.append(f"{provisioning}", style="bold green") + text.append(" provisioning-enabled ") + text.append(f"{len(invitations)}", style="bold yellow") + text.append(" pending") + return Panel(text, title=logo(), border_style="bright_blue", padding=(1, 2)) + + +def access_diagnostic(users: Sequence[TeamUser]) -> Panel | None: + non_holders = [user for user in users if not user.is_holder] + admins_without_provisioning = [ + user for user in non_holders if "ADMIN" in user.roles and not user.provisioning_allowed + ] + if non_holders and len(admins_without_provisioning) == len(non_holders): + return Panel( + "All delegated admins are blocked from Certificates, Identifiers & Profiles.\n" + "This usually means the Developer Program membership is enrolled as an individual.", + title="[bold yellow]Access diagnostic[/bold yellow]", + border_style="yellow", + ) + return None + diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..f6ea1c7 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,123 @@ +from pathlib import Path + +import httpx +import pytest + +from apple_team_cli.api import AppleAPIError, AppleClient +from apple_team_cli.config import Settings + + +@pytest.fixture() +def settings(tmp_path: Path) -> Settings: + key = tmp_path / "key.p8" + key.write_text("-----BEGIN PRIVATE KEY-----\nfake\n", encoding="utf-8") + return Settings( + "11111111-2222-4333-8444-555555555555", + "ABCDE12345", + key, + "https://api.example.test", + ) + + +@pytest.fixture(autouse=True) +def fake_token(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("apple_team_cli.api.create_token", lambda settings: "short-lived-token") + + +def user_resource(**overrides: object) -> dict[str, object]: + attrs: dict[str, object] = { + "username": "dev@example.com", + "firstName": "Dev", + "lastName": "Example", + "roles": ["ADMIN"], + "allAppsVisible": True, + "provisioningAllowed": False, + } + attrs.update(overrides) + return {"type": "users", "id": "user-1", "attributes": attrs} + + +def test_list_users_and_find_by_email(settings: Settings) -> None: + def handler(request: httpx.Request) -> httpx.Response: + assert request.headers["authorization"] == "Bearer short-lived-token" + assert request.url.params["fields[users]"] + return httpx.Response(200, json={"data": [user_resource()], "links": {}}) + + with AppleClient(settings, transport=httpx.MockTransport(handler)) as client: + users = client.list_users() + match = client.get_user("DEV@example.com") + + assert len(users) == 1 + assert match.id == "user-1" + assert match.provisioning_allowed is False + + +def test_update_user_uses_json_api_shape(settings: Settings) -> None: + requests: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + if request.method == "GET": + return httpx.Response(200, json={"data": [user_resource()], "links": {}}) + body = __import__("json").loads(request.content) + assert body == { + "data": { + "type": "users", + "id": "user-1", + "attributes": {"provisioningAllowed": True}, + } + } + return httpx.Response( + 200, json={"data": user_resource(provisioningAllowed=True)} + ) + + with AppleClient(settings, transport=httpx.MockTransport(handler)) as client: + user = client.get_user("dev@example.com") + updated = client.update_user(user, provisioning_allowed=True) + + assert requests[-1].method == "PATCH" + assert updated.provisioning_allowed + + +def test_invitation_payload(settings: Settings) -> None: + def handler(request: httpx.Request) -> httpx.Response: + body = __import__("json").loads(request.content) + attrs = body["data"]["attributes"] + assert attrs["roles"] == ["DEVELOPER"] + assert attrs["provisioningAllowed"] is True + resource = { + "type": "userInvitations", + "id": "invite-1", + "attributes": {**attrs, "expirationDate": "2026-08-29T12:00:00Z"}, + } + return httpx.Response(201, json={"data": resource}) + + with AppleClient(settings, transport=httpx.MockTransport(handler)) as client: + invitation = client.invite_user( + email="new@example.com", + first_name="New", + last_name="User", + roles=["DEVELOPER"], + provisioning_allowed=True, + all_apps_visible=True, + ) + + assert invitation.email == "new@example.com" + + +def test_apple_errors_are_sanitized(settings: Settings) -> None: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 403, + json={"errors": [{"title": "Forbidden", "detail": "Role is insufficient"}]}, + ) + + with ( + AppleClient(settings, transport=httpx.MockTransport(handler)) as client, + pytest.raises(AppleAPIError) as raised, + ): + client.list_users() + + assert raised.value.status_code == 403 + assert raised.value.details == ("Forbidden: Role is insufficient",) + assert "short-lived-token" not in str(raised.value) diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..d4d5536 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,74 @@ +from pathlib import Path + +import pytest + +from apple_team_cli.config import ConfigError, Settings, write_config + + +@pytest.fixture() +def fake_key(tmp_path: Path) -> Path: + key = tmp_path / "AuthKey_ABCDE12345.p8" + key.write_text("-----BEGIN PRIVATE KEY-----\nnot-a-real-key\n", encoding="utf-8") + key.chmod(0o600) + return key + + +def test_write_and_load_config( + fake_key: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config_path = tmp_path / ".env" + write_config( + "11111111-2222-4333-8444-555555555555", + "ABCDE12345", + fake_key, + config_path, + ) + for name in ("ASC_ISSUER_ID", "ASC_KEY_ID", "ASC_PRIVATE_KEY_PATH", "ASC_BASE_URL"): + monkeypatch.delenv(name, raising=False) + + monkeypatch.chdir(tmp_path) + settings = Settings.load(tmp_path / "missing.toml") + + assert settings.key_id == "ABCDE12345" + assert settings.private_key_path == fake_key + assert settings.key_permissions_are_private + assert config_path.stat().st_mode & 0o777 == 0o600 + contents = config_path.read_text(encoding="utf-8") + assert "not-a-real-key" not in contents + assert 'ASC_ISSUER_ID="11111111-2222-4333-8444-555555555555"' in contents + assert 'ASC_KEY_ID="ABCDE12345"' in contents + assert f'ASC_PRIVATE_KEY_PATH="{fake_key}"' in contents + + +def test_missing_configuration_is_actionable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.chdir(tmp_path) + for name in ("ASC_ISSUER_ID", "ASC_KEY_ID", "ASC_PRIVATE_KEY_PATH"): + monkeypatch.delenv(name, raising=False) + + with pytest.raises(ConfigError, match="apple-team configure"): + Settings.load(tmp_path / "missing.toml") + + +def test_rejects_non_p8_file(tmp_path: Path) -> None: + key = tmp_path / "bad.p8" + key.write_text("secret", encoding="utf-8") + settings = Settings( + "11111111-2222-4333-8444-555555555555", "ABCDE12345", key + ) + + with pytest.raises(ConfigError, match="not an App Store Connect"): + settings.validate() + + +def test_secure_private_key_removes_group_and_world_access(fake_key: Path) -> None: + fake_key.chmod(0o644) + settings = Settings( + "11111111-2222-4333-8444-555555555555", "ABCDE12345", fake_key + ) + + settings.secure_private_key() + + assert fake_key.stat().st_mode & 0o777 == 0o600 + assert settings.key_permissions_are_private diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000..5af25dc --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,42 @@ +from datetime import UTC, datetime, timedelta + +from apple_team_cli.models import Invitation, TeamUser + + +def test_user_maps_effective_access() -> None: + user = TeamUser.from_resource( + { + "id": "user-1", + "attributes": { + "username": "dev@example.com", + "firstName": "Dev", + "lastName": "Example", + "roles": ["ADMIN"], + "allAppsVisible": True, + "provisioningAllowed": False, + }, + } + ) + + assert user.name == "Dev Example" + assert not user.provisioning_allowed + assert user.as_dict()["roles"] == ["ADMIN"] + + +def test_invitation_expiration() -> None: + expired_at = datetime.now(UTC) - timedelta(minutes=1) + invite = Invitation.from_resource( + { + "id": "invite-1", + "attributes": { + "email": "dev@example.com", + "firstName": "Dev", + "lastName": "Example", + "expirationDate": expired_at.isoformat(), + "roles": ["DEVELOPER"], + }, + } + ) + + assert invite.expired + diff --git a/tests/test_ui.py b/tests/test_ui.py new file mode 100644 index 0000000..ccf657f --- /dev/null +++ b/tests/test_ui.py @@ -0,0 +1,31 @@ +from apple_team_cli.models import TeamUser +from apple_team_cli.ui import access_diagnostic + + +def make_user(*, holder: bool, provisioning: bool) -> TeamUser: + return TeamUser( + id="1" if holder else "2", + username="holder@example.com" if holder else "admin@example.com", + first_name="Test", + last_name="User", + roles=("ACCOUNT_HOLDER", "ADMIN") if holder else ("ADMIN",), + all_apps_visible=True, + provisioning_allowed=provisioning, + ) + + +def test_diagnoses_likely_individual_membership() -> None: + panel = access_diagnostic( + [make_user(holder=True, provisioning=True), make_user(holder=False, provisioning=False)] + ) + + assert panel is not None + + +def test_no_diagnostic_when_delegated_admin_has_provisioning() -> None: + panel = access_diagnostic( + [make_user(holder=True, provisioning=True), make_user(holder=False, provisioning=True)] + ) + + assert panel is None +