diff --git a/.github/workflows/data-machine-business.yml b/.github/workflows/data-machine-business.yml index 15ad35aa9..e6221abf5 100644 --- a/.github/workflows/data-machine-business.yml +++ b/.github/workflows/data-machine-business.yml @@ -27,6 +27,21 @@ permissions: issues: write jobs: + unit: + name: Unit (standalone PHP) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + tools: composer + # Stubs core's database classes, so it runs outside WordPress. + - name: Prepare in-tree Data Machine core + run: composer install --working-dir=plugins/data-machine --no-dev --no-interaction --no-progress --prefer-dist + - name: GitHub files unit test + run: php plugins/data-machine-business/tests/github-files-smoke.php + homeboy: name: Homeboy (${{ matrix.command }}) runs-on: ubuntu-latest diff --git a/plugins/data-machine-business/README.md b/plugins/data-machine-business/README.md index fe0f8f121..ddd92a98c 100644 --- a/plugins/data-machine-business/README.md +++ b/plugins/data-machine-business/README.md @@ -30,6 +30,7 @@ Data Machine Business connects WordPress automation, agents, and pipelines to an | Google Drive | List folders, export native Google files, download binaries, and feed files into pipelines | Abilities, fetch handler | | Slack | Fetch channel messages and publish messages or thread replies | Abilities, fetch/publish handlers | | Discord | Fetch channel messages and publish text or embeds | Abilities, fetch/publish handlers | +| GitHub | Fetch repository files, deduplicated by blob SHA, with removal tracking | Fetch handler (`github`) | | Amazon Associates | Search products and generate Creators API affiliate links | AI tool | | Sendy | Subscribe users, create or update campaigns, and read email-funnel metrics | Abilities | | Mediavine | Fetch page, aggregate, device, country, normalized-source, and ad-unit publisher revenue reports | Ability, WP-CLI | @@ -351,6 +352,10 @@ Create a Slack app with a bot token and grant the scopes needed by your flows: Add the bot to each channel it should access, then configure its `xoxb-...` token in Data Machine settings. +### GitHub + +A token is optional for public repositories. For private repositories, add a fine-grained token with read access to contents in the GitHub auth settings. See [docs/github.md](docs/github.md). + ### Discord Create a Discord application and bot, grant it Send Messages and Read Message History in the target channels, and configure the bot token in Data Machine settings. diff --git a/plugins/data-machine-business/data-machine-business.php b/plugins/data-machine-business/data-machine-business.php index e20418818..96ca2366b 100644 --- a/plugins/data-machine-business/data-machine-business.php +++ b/plugins/data-machine-business/data-machine-business.php @@ -2,7 +2,7 @@ /** * Plugin Name: Data Machine Business * Plugin URI: https://github.com/Extra-Chill/data-machine-business - * Description: Business and enterprise integrations for Data Machine. Adds support for Google Analytics, PageSpeed Insights, Google Sheets, Slack, Discord, and other business tools. + * Description: Business and enterprise integrations for Data Machine. Adds support for Google Analytics, PageSpeed Insights, Google Sheets, Slack, Discord, GitHub, and other business tools. * Version: 0.31.1 * Requires at least: 6.9 * Requires PHP: 8.2 diff --git a/plugins/data-machine-business/docs/github.md b/plugins/data-machine-business/docs/github.md new file mode 100644 index 000000000..283450f83 --- /dev/null +++ b/plugins/data-machine-business/docs/github.md @@ -0,0 +1,42 @@ +# GitHub Files fetch handler + +The `github` fetch handler reads the `files` data source from GitHub.com. It resolves the branch tip, reads its recursive Git tree, and downloads matching blobs by SHA so every file in a fetch comes from the same commit. + +## Configuration + +| Field | Default | Meaning | +| --- | --- | --- | +| `repo` | Required | GitHub repository in `owner/name` format, not a URL. | +| `branch` | Repository default | Use the exact branch name, such as `release/docs`. The default branch name is cached for five minutes. | +| `file_path` | `''` | Fetch from the whole repository, a directory and its descendants, or an exact file. `docs` does not match `docs-extra`. Leading and trailing slashes are ignored. | +| `file_pattern` | `''` | No glob filter. A glob without a slash, such as `*.md`, matches filenames at any depth. With a slash, it matches the path relative to `file_path`, and `*` does not cross a slash. Matching is case-sensitive. | +| `max_file_size` | `1048576` | Maximum file size in bytes (1–104857600). Larger files are skipped before download. | + +For public repositories no credential is required, even though Data Machine may show a **Requires Auth** badge to expose the provider settings. For private repositories, save a GitHub fine-grained personal access token with **Contents: Read-only** access to the selected repository in **Data Machine → Settings → Auth Providers**. The `github` provider stores the PAT as the encrypted `access_token` credential and sends it as a bearer token. Do not put the token in step settings. There is no OAuth flow. + +## Item contract + +The packet's `data.title` is the repository-relative file path (prefixed with `Removed:` for removals), and `data.body` is the decoded file content. A removal has an empty body; use `metadata.github_change` to distinguish it from an empty file. + +| Metadata | Meaning | +| --- | --- | +| `source_type` | `github` | +| `github_repo`, `github_branch` | Repository and resolved branch. | +| `github_commit_sha` | Commit examined by the fetch; for removals, the first commit seen without the file. | +| `github_file_path` | Full repository-relative path, e.g. `docs/setup/install.md`. | +| `github_relative_file_path` | Path relative to `file_path`, e.g. `setup/install.md` when `file_path` is `docs`. With an exact-file prefix this is the filename. | +| `github_file_sha` | Git blob SHA; for a removal, the last tracked blob SHA. | +| `github_url`, `source_url` | The same commit-pinned file URL. For a removal, the URL points at the last tracked revision where the file existed. | +| `github_change` | `added` when the file first enters the snapshot, `modified` when its blob SHA changes, or `removed` when a tracked file disappears. | +| `dedup_key`, `original_id` | `github__files__`, with the full repository-relative path and the blob SHA. | +| `item_identifier` | Internal key for Data Machine's processed-items lifecycle. Removals have a separate identity so a processed file does not suppress its removal. | + +For DocSync, route `removed` items to unpublish and use the repository and full file path to identify the destination. Use the file SHA or `dedup_key` to identify a revision, not as the stable destination key. + +## Change tracking and failures + +A flow step stores its snapshot in Data Machine's Tracked Items ledger. There are no removals on the first run. A successful fetch updates the snapshot; if a GitHub request fails or the tree is truncated, the prior snapshot is retained. Snapshots are separate for each flow step, repository, branch, prefix, and glob. An oversized file still present in the tree does not count as removed. + +The handler checks Data Machine's processed-items ledger before each batch of blob downloads. Once downstream processing completes, a repeat fetch of the same file path and blob SHA skips that revision, even if it reappears later. With an explicit or cached branch, an unchanged, fully processed fetch only requests the commit and tree. Unprocessed removals are retried while the path remains absent. Direct execution has no durable snapshot or deduplication. + +An existing path with no matching files can succeed with no items. A configured prefix that no longer exists fails with `github_missing_file_path`, rather than treating the entire source as removed. For example, to detect deletion of a directory and all its files, use a surviving ancestor (or the repository root) as `file_path`. GitHub API failures and truncated trees also fail the fetch step. diff --git a/plugins/data-machine-business/homeboy.json b/plugins/data-machine-business/homeboy.json index 543ddc1fd..dd408b09f 100644 --- a/plugins/data-machine-business/homeboy.json +++ b/plugins/data-machine-business/homeboy.json @@ -12,7 +12,8 @@ "tests/data-machine-http-client-contract-smoke.php", "tests/google-analytics-aggregate-schema-smoke.php", "tests/google-analytics-tool-schema-smoke.php", - "tests/sendy-list-campaigns-schema-smoke.php" + "tests/sendy-list-campaigns-schema-smoke.php", + "tests/github-handler-contract-smoke.php" ] } } diff --git a/plugins/data-machine-business/inc/Api/GitHubClient.php b/plugins/data-machine-business/inc/Api/GitHubClient.php new file mode 100644 index 000000000..7573e0958 --- /dev/null +++ b/plugins/data-machine-business/inc/Api/GitHubClient.php @@ -0,0 +1,139 @@ +get_string( $this->get( $repo ), 'default_branch' ); + } + + public function get_latest_commit_sha( string $repo, string $branch ): string|WP_Error { + return $this->get_string( $this->get_commit( $repo, $branch ), 'sha' ); + } + + /** Return both SHAs so the caller can fetch the pinned tree without another request. */ + public function get_commit( string $repo, string $branch ): array|WP_Error { + $result = $this->get( $repo, '/commits/' . rawurlencode( $branch ) ); + if ( is_wp_error( $result ) ) { + return $result; + } + foreach ( array( $result['sha'] ?? null, $result['commit']['tree']['sha'] ?? null ) as $sha ) { + if ( ! is_string( $sha ) || '' === $sha ) { + return $this->invalid_response(); + } + } + return $result; + } + + public function get_recursive_tree( string $repo, string $sha ): array|WP_Error { + $result = $this->get( $repo, '/git/trees/' . rawurlencode( $sha ) . '?recursive=1' ); + if ( is_wp_error( $result ) ) { + return $result; + } + if ( ! empty( $result['truncated'] ) ) { + return new WP_Error( 'github_tree_truncated', __( 'GitHub truncated the recursive tree. File changes cannot be determined from an incomplete tree.', 'data-machine-business' ) ); + } + if ( ! isset( $result['tree'] ) || ! is_array( $result['tree'] ) || ! array_is_list( $result['tree'] ) ) { + return $this->invalid_response(); + } + foreach ( $result['tree'] as $entry ) { + if ( ! is_string( $entry['path'] ?? null ) || '' === $entry['path'] || ! is_string( $entry['type'] ?? null ) ) { + return $this->invalid_response(); + } + if ( 'blob' === $entry['type'] && ( ! is_string( $entry['sha'] ?? null ) || '' === $entry['sha'] || ! is_int( $entry['size'] ?? null ) || $entry['size'] < 0 ) ) { + return $this->invalid_response(); + } + } + return $result['tree']; + } + + public function get_blob( string $repo, string $sha, int $max_bytes = 1048576 ): string|WP_Error { + // Allow room for base64, JSON escaping, and response metadata. + $result = $this->get( $repo, '/git/blobs/' . rawurlencode( $sha ), 3 * $max_bytes + 4096 ); + $content = $this->decode_contents( $result ); + if ( ! is_wp_error( $content ) && strlen( $content ) > $max_bytes ) { + return new WP_Error( 'github_blob_too_large', __( 'GitHub returned a blob larger than the configured file size limit.', 'data-machine-business' ) ); + } + return $content; + } + + public function get_file_contents( string $repo, string $path, string $ref = '' ): string|WP_Error { + $query = '' === $ref ? '' : '?ref=' . rawurlencode( $ref ); + return $this->decode_contents( $this->get( $repo, '/contents/' . self::encode_path( $path ) . $query ) ); + } + + private function decode_contents( array|WP_Error $result ): string|WP_Error { + if ( is_wp_error( $result ) ) { + return $result; + } + if ( 'base64' !== ( $result['encoding'] ?? null ) || ! is_string( $result['content'] ?? null ) ) { + return $this->invalid_response(); + } + $content = base64_decode( $result['content'], true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- GitHub returns base64-encoded content. + return false === $content ? $this->invalid_response() : $content; + } + + private function get_string( array|WP_Error $result, string $key ): string|WP_Error { + if ( is_wp_error( $result ) ) { + return $result; + } + return is_string( $result[ $key ] ?? null ) && '' !== $result[ $key ] ? $result[ $key ] : $this->invalid_response(); + } + + private function get( string $repo, string $endpoint = '', int $response_limit = 0 ): array|WP_Error { + if ( ! preg_match( '#^[a-zA-Z0-9-]+/(?!\.{1,2}$)[a-zA-Z0-9_.-]+$#D', $repo ) ) { + return new WP_Error( 'github_invalid_repo', __( 'GitHub repo must be in owner/name format.', 'data-machine-business' ) ); + } + + $result = HttpClient::get( + 'https://api.github.com/repos/' . self::encode_path( $repo ) . $endpoint, + array( + 'headers' => array( + 'Accept' => 'application/vnd.github+json', + 'X-GitHub-Api-Version' => '2022-11-28', + ), + 'auth' => array( + 'type' => 'bearer', + 'token' => $this->token, + ), + 'timeout' => 30, + 'context' => 'GitHub API', + 'limit_response_size' => $response_limit, + 'log_response_body_preview' => false, + ) + ); + + $status = (int) ( $result['status_code'] ?? 0 ); + if ( empty( $result['success'] ) || $status < 200 || $status >= 300 ) { + $message = $status > 0 + /* translators: %d: HTTP status code. */ + ? sprintf( __( 'GitHub API returned HTTP %d. Check repository access, branch or file references, and API rate limits.', 'data-machine-business' ), $status ) + : __( 'Could not connect to the GitHub API.', 'data-machine-business' ); + return new WP_Error( 'github_api_error', $message, array( 'status' => $status ) ); + } + + $data = json_decode( $result['data'], true ); + return is_array( $data ) ? $data : $this->invalid_response(); + } + + private function invalid_response(): WP_Error { + return new WP_Error( 'github_invalid_response', __( 'GitHub API returned an invalid or unsupported response.', 'data-machine-business' ) ); + } +} diff --git a/plugins/data-machine-business/inc/Bootstrap/ProviderModules.php b/plugins/data-machine-business/inc/Bootstrap/ProviderModules.php index d5cf526df..f53aa56a3 100644 --- a/plugins/data-machine-business/inc/Bootstrap/ProviderModules.php +++ b/plugins/data-machine-business/inc/Bootstrap/ProviderModules.php @@ -177,6 +177,12 @@ static function (): void { new \DataMachineBusiness\Handlers\Discord\DiscordFetch(); } ), + new ProviderModule( + 'github', + $fetch_handlers, + array( 'handler:github' ), + static fn() => new \DataMachineBusiness\Handlers\GitHub\GitHubFetch() + ), new ProviderModule( 'bing-webmaster', array_merge( $abilities, $tools ), diff --git a/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetch.php b/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetch.php new file mode 100644 index 000000000..805ddc3ba --- /dev/null +++ b/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetch.php @@ -0,0 +1,253 @@ + 'files' ) + ); + } + + protected function getDefaultMaxItems(): int { + return 0; + } + + protected function executeFetch( array $config, ExecutionContext $context ): array|WP_Error { + $repo = trim( (string) ( $config['repo'] ?? '' ) ); + $branch = trim( (string) ( $config['branch'] ?? '' ) ); + $prefix = trim( (string) ( $config['file_path'] ?? '' ), '/' ); + $pattern = (string) ( $config['file_pattern'] ?? '' ); + $limit = min( GitHubFetchSettings::MAX_FILE_SIZE, max( 1, (int) ( $config['max_file_size'] ?? GitHubFetchSettings::DEFAULT_MAX_FILE_SIZE ) ) ); + + $provider = $this->getAuthProvider( 'github' ); + $token = $provider instanceof GitHubAuth ? $provider->get_token( $config ) : ''; + $auth_error = $provider instanceof GitHubAuth ? $provider->get_last_decryption_error() : null; + if ( null !== $auth_error ) { + return $auth_error; + } + $client = new GitHubClient( $token ); + if ( '' === $branch ) { + $branch = $this->default_branch( $client, $repo, $token ); + if ( is_wp_error( $branch ) ) { + return $branch; + } + } + + $head = $client->get_commit( $repo, $branch ); + if ( is_wp_error( $head ) ) { + return $head; + } + $commit = $head['sha']; + $tree_sha = $head['commit']['tree']['sha']; + $tree = $client->get_recursive_tree( $repo, $tree_sha ); + if ( is_wp_error( $tree ) ) { + return $tree; + } + + $scope = wp_json_encode( array( $context->getFlowStepId(), strtolower( $repo ), $branch, $prefix, $pattern ), JSON_INVALID_UTF8_SUBSTITUTE ); + $namespace = 'github-files:' . hash( 'sha256', (string) $scope ); + $ledger = $context->isFlow() && $context->getFlowStepId() ? new TrackedItems() : null; + $snapshot = $ledger?->get( $namespace, 'snapshot' ); + $previous = $snapshot['metadata']['paths'] ?? array(); + $pending = $snapshot['metadata']['removals'] ?? array(); + $paths = array(); + $items = array(); + $candidates = array(); + $prefix_exists = '' === $prefix; + + foreach ( $tree as $entry ) { + $path = $entry['path']; + if ( '' !== $prefix && $path !== $prefix && ! str_starts_with( $path, $prefix . '/' ) ) { + continue; + } + $prefix_exists = true; + if ( 'blob' !== $entry['type'] ) { + continue; + } + // The file is still present even if it exceeds the configured download limit. + unset( $pending[ $path ] ); + $relative = self::relative_path( $path, $prefix ); + $subject = str_contains( $pattern, '/' ) ? $relative : self::filename( $relative ); + if ( '' !== $pattern && ! fnmatch( $pattern, $subject, FNM_PATHNAME ) ) { + continue; + } + if ( $entry['size'] > $limit ) { + if ( isset( $previous[ $path ] ) ) { + $paths[ $path ] = $previous[ $path ]; + } + continue; + } + + $sha = $entry['sha']; + $before = $previous[ $path ] ?? null; + $change = null === $before ? 'added' : ( $sha === $before['sha'] ? $before['change'] : 'modified' ); + $paths[ $path ] = array( + 'sha' => $sha, + 'change' => $change, + 'commit' => $commit, + ); + $candidates[ self::item_identifier( self::dedup_key( $repo, $path, $sha ) ) ] = $path; + } + + if ( ! $prefix_exists ) { + return new WP_Error( + 'github_missing_file_path', + /* translators: %s: configured repository path. */ + sprintf( __( 'GitHub file_path "%s" does not exist in the repository tree.', 'data-machine-business' ), $prefix ) + ); + } + + // Hold tombstones until the downstream pipeline marks them processed so + // caps, in-flight claims and downstream failures cannot drop removals. + foreach ( array_diff_key( $previous, $paths ) as $path => $entry ) { + $pending[ $path ] = array( + 'sha' => $entry['sha'], + 'old_commit' => $entry['commit'], + 'commit' => $commit, + ); + } + foreach ( $pending as $path => $entry ) { + $path = (string) $path; + $item = $this->file_item( $repo, $branch, $entry['commit'], $path, self::relative_path( $path, $prefix ), $entry['sha'], 'removed', $entry['old_commit'] ); + if ( $context->isItemProcessed( $item['metadata']['item_identifier'] ) ) { + unset( $pending[ $path ] ); + continue; + } + $items[] = $item; + } + + // Match the core batch cap without downloading blobs outside the batch. + $remaining = max( 0, (int) ( $config['max_items'] ?? 0 ) ); + if ( $remaining > 0 ) { + $removals = $context->classifySourceItems( array_column( array_column( $items, 'metadata' ), 'item_identifier' ) ); + $remaining -= count( $removals['selected_identifiers'] ); + if ( $remaining <= 0 ) { + $candidates = array(); + } + } + $selection = $context->classifySourceItems( array_keys( $candidates ), max( 0, $remaining ) ); + foreach ( $selection['selected_identifiers'] as $identifier ) { + $path = $candidates[ $identifier ]; + $entry = $paths[ $path ]; + $content = $client->get_blob( $repo, $entry['sha'], $limit ); + if ( is_wp_error( $content ) ) { + return $content; + } + $item = $this->file_item( $repo, $branch, $commit, $path, self::relative_path( $path, $prefix ), $entry['sha'], $entry['change'], $commit ); + $item['content'] = $content; + $items[] = $item; + } + + $state = array( + 'paths' => $paths, + 'removals' => $pending, + ); + if ( $ledger && ( $snapshot['metadata'] ?? null ) !== $state && null === $ledger->upsert( + array( + 'namespace' => $namespace, + 'item_id' => 'snapshot', + 'item_type' => 'github_files_snapshot', + 'source_ref' => $repo, + 'source_revision' => $commit, + 'metadata' => $state, + ) + ) ) { + return new WP_Error( 'github_snapshot_error', __( 'Could not save the GitHub file snapshot for this flow step.', 'data-machine-business' ) ); + } + + return array( 'items' => $items ); + } + + private function default_branch( GitHubClient $client, string $repo, string $token ): string|WP_Error { + $key = 'datamachine_github_branch_' . hash( 'sha256', strtolower( $repo ) . "\0" . $token ); + $branch = get_transient( $key ); + if ( is_string( $branch ) && '' !== $branch ) { + return $branch; + } + $branch = $client->get_default_branch( $repo ); + if ( ! is_wp_error( $branch ) ) { + set_transient( $key, $branch, 300 ); + } + return $branch; + } + + private static function relative_path( string $path, string $prefix ): string { + if ( '' === $prefix ) { + return $path; + } + return $path === $prefix ? self::filename( $path ) : substr( $path, strlen( $prefix ) + 1 ); + } + + private static function filename( string $path ): string { + $slash = strrpos( $path, '/' ); + return false === $slash ? $path : substr( $path, $slash + 1 ); + } + + private static function dedup_key( string $repo, string $path, string $sha ): string { + return "github_{$repo}_files_{$path}_{$sha}"; + } + + private static function item_identifier( string $key, string $removed_at = '' ): string { + // Core's processed-items index has a length limit and case-insensitive collation. + return hash( 'sha256', '' === $removed_at ? $key : "removed\0{$key}\0{$removed_at}" ); + } + + private function file_item( string $repo, string $branch, string $commit, string $path, string $relative, string $sha, string $change, string $url_commit ): array { + $key = self::dedup_key( $repo, $path, $sha ); + $url = 'https://github.com/' . GitHubClient::encode_path( $repo ) . '/blob/' . rawurlencode( $url_commit ) . '/' . GitHubClient::encode_path( $path ); + + return array( + 'title' => 'removed' === $change + /* translators: %s: removed repository path. */ + ? sprintf( __( 'Removed: %s', 'data-machine-business' ), $path ) + : $path, + 'content' => '', + 'metadata' => array( + 'source_type' => 'github', + 'github_repo' => $repo, + 'github_branch' => $branch, + 'github_commit_sha' => $commit, + 'github_file_path' => $path, + 'github_relative_file_path' => $relative, + 'github_file_sha' => $sha, + 'github_change' => $change, + 'github_url' => $url, + 'source_url' => $url, + 'dedup_key' => $key, + 'original_id' => $key, + 'item_identifier' => self::item_identifier( $key, 'removed' === $change ? $commit : '' ), + ), + ); + } +} diff --git a/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetchSettings.php b/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetchSettings.php new file mode 100644 index 000000000..ec04c731f --- /dev/null +++ b/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetchSettings.php @@ -0,0 +1,51 @@ + array( + 'type' => 'text', + 'label' => __( 'Repository', 'data-machine-business' ), + 'description' => __( 'GitHub repository in owner/name format.', 'data-machine-business' ), + 'required' => true, + ), + 'branch' => array( + 'type' => 'text', + 'label' => __( 'Branch', 'data-machine-business' ), + 'description' => __( 'Leave blank to use the repository default branch.', 'data-machine-business' ), + ), + 'file_path' => array( + 'type' => 'text', + 'label' => __( 'File Path', 'data-machine-business' ), + 'description' => __( 'Limit to a file or directory path. Leave blank for the entire repository.', 'data-machine-business' ), + ), + 'file_pattern' => array( + 'type' => 'text', + 'label' => __( 'File Pattern', 'data-machine-business' ), + 'description' => __( 'Optional glob, e.g. *.md. Patterns without a slash match filenames at any depth.', 'data-machine-business' ), + ), + 'max_file_size' => array( + 'type' => 'number', + 'label' => __( 'Maximum File Size (bytes)', 'data-machine-business' ), + 'default' => self::DEFAULT_MAX_FILE_SIZE, + 'min' => 1, + 'max' => self::MAX_FILE_SIZE, + ), + ); + } +} diff --git a/plugins/data-machine-business/inc/OAuth/Providers/GitHubAuth.php b/plugins/data-machine-business/inc/OAuth/Providers/GitHubAuth.php new file mode 100644 index 000000000..3256ddbcd --- /dev/null +++ b/plugins/data-machine-business/inc/OAuth/Providers/GitHubAuth.php @@ -0,0 +1,47 @@ + array( + 'label' => __( 'Personal Access Token', 'data-machine-business' ), + 'type' => 'password', + 'required' => false, + 'description' => __( 'Optional for public repositories. For private repositories, grant read access to repository contents.', 'data-machine-business' ), + ), + ); + } + + public function is_configured(): bool { + return '' !== $this->get_token(); + } + + public function is_authenticated(): bool { + return $this->is_configured(); + } + + /** The PAT lives in provider config, not an OAuth account slot. */ + public function clear_account(): bool { + return $this->save_config( array() ); + } + + public function get_token( array $context = array() ): string { + return trim( (string) ( $this->get_config( $context )['access_token'] ?? '' ) ); + } +} diff --git a/plugins/data-machine-business/tests/github-files-smoke.php b/plugins/data-machine-business/tests/github-files-smoke.php new file mode 100644 index 000000000..b2b76681e --- /dev/null +++ b/plugins/data-machine-business/tests/github-files-smoke.php @@ -0,0 +1,283 @@ +code; + } + public function get_error_message(): string { + return $this->message; + } + } + + function __( $message, $domain ) { + return $message; + } + function is_wp_error( $value ) { + return $value instanceof WP_Error; + } + function wp_json_encode( ...$args ) { + return json_encode( ...$args ); + } + function plugin_dir_path( $file ) { + return dirname( $file ) . '/'; + } + function plugin_dir_url( $file ) { + return 'https://example.test/wp-content/plugins/data-machine-business/'; + } + function home_url() { + return 'https://example.test'; + } + function add_filter( $tag, $callback, $priority = 10, $accepted_args = 1 ) { + $GLOBALS['hooks'][ $tag ][ $priority ][] = array( $callback, $accepted_args ); + } + function add_action( ...$args ) { + add_filter( ...$args ); + } + function apply_filters( $tag, $value, ...$args ) { + $hooks = $GLOBALS['hooks'][ $tag ] ?? array(); + ksort( $hooks ); + foreach ( $hooks as $group ) { + foreach ( $group as list( $callback, $accepted ) ) { + $value = $callback( ...array_slice( array( $value, ...$args ), 0, $accepted ) ); + } + } + return $value; + } + function do_action( $tag, ...$args ) { + foreach ( $GLOBALS['hooks'][ $tag ] ?? array() as $group ) { + foreach ( $group as list( $callback, $accepted ) ) { + $callback( ...array_slice( $args, 0, $accepted ) ); + } + } + } + function did_action( $tag ) { + return 0; + } + function doing_action( $tag ) { + return false; + } + function get_site_option( $name, $default ) { + return $GLOBALS['options'][ $name ] ?? $default; + } + function update_site_option( $name, $value ) { + $GLOBALS['options'][ $name ] = $value; + return true; + } + function wp_salt( $scheme ) { + return 'github-files-smoke-test-salt'; + } + function get_transient( $key ) { + return $GLOBALS['transients'][ $key ] ?? false; + } + function set_transient( $key, $value, $ttl ) { + $GLOBALS['transients'][ $key ] = $value; + } + function wp_remote_get( $url, $args ) { + $prefix = 'https://api.github.com/repos/owner/repo'; + check( str_starts_with( $url, $prefix ), 'Unexpected GitHub URL: ' . $url ); + $route = substr( $url, strlen( $prefix ) ); + $GLOBALS['requests'][] = array( $route, $args ); + check( isset( $GLOBALS['responses'][ $route ] ), 'Unexpected API request: ' . $route ); + list( $status, $body ) = $GLOBALS['responses'][ $route ]; + return array( 'status' => $status, 'body' => json_encode( $body ) ); + } + function wp_remote_retrieve_body( $response ) { + return $response['body']; + } + function wp_remote_retrieve_response_code( $response ) { + return $response['status']; + } + function wp_remote_retrieve_headers( $response ) { + return array(); + } + function check( $condition, $message ) { + if ( ! $condition ) { + fwrite( STDERR, $message . "\n" ); + exit( 1 ); + } + } + + $core = getenv( 'DATA_MACHINE_PATH' ) ?: dirname( __DIR__, 2 ) . '/data-machine'; + spl_autoload_register( + static function ( $class ) use ( $core ) { + if ( str_starts_with( $class, 'DataMachineBusiness\\' ) ) { + $file = dirname( __DIR__ ) . '/inc/' . str_replace( '\\', '/', substr( $class, strlen( 'DataMachineBusiness\\' ) ) ) . '.php'; + if ( is_file( $file ) ) { + require $file; + } + return; + } + if ( str_starts_with( $class, 'DataMachine\\' ) ) { + $file = $core . '/inc/' . str_replace( '\\', '/', substr( $class, strlen( 'DataMachine\\' ) ) ) . '.php'; + if ( is_file( $file ) ) { + require $file; + } + } + } + ); + new DataMachineBusiness\Handlers\GitHub\GitHubFetch(); + $registration = apply_filters( 'datamachine_handlers', array(), 'fetch' )['github']; + check( 'files' === $registration['meta']['data_source'], 'GitHub files source was not registered.' ); + $handler = new $registration['class'](); + $config = array( + 'repo' => 'owner/repo', + 'file_path' => 'docs/', + 'file_pattern' => '*.md', + 'max_file_size' => 20, + 'flow_id' => 1, + 'pipeline_id' => 1, + 'flow_step_id' => 'github-step', + ); + + function fixture( $commit, $files, $truncated = false, $include_docs = true ) { + $GLOBALS['requests'] = array(); + $GLOBALS['responses'] = array( + '' => array( 200, array( 'default_branch' => 'release/docs' ) ), + '/commits/release%2Fdocs' => array( 200, array( 'sha' => $commit, 'commit' => array( 'tree' => array( 'sha' => 'tree-' . $commit ) ) ) ), + '/git/trees/tree-' . $commit . '?recursive=1' => array( 200, array( 'truncated' => $truncated, 'tree' => array_merge( $include_docs ? array( array( 'path' => 'docs', 'type' => 'tree' ) ) : array(), $files ) ) ), + ); + } + function blob( $path, $sha, $size = 1 ) { + return array( 'path' => $path, 'sha' => $sha, 'type' => 'blob', 'size' => $size ); + } + function content( $sha, $body ) { + $GLOBALS['responses'][ '/git/blobs/' . $sha ] = array( 200, array( 'encoding' => 'base64', 'content' => base64_encode( $body ) ) ); + } + function run_fetch( $override = array() ) { + $packets = $GLOBALS['handler']->get_fetch_data( 1, array_replace( $GLOBALS['config'], $override ), '1' ); + return is_wp_error( $packets ) ? $packets : array_map( static fn ( $packet ) => $packet->addTo( array() )[0], $packets ); + } + function mark_processed( $packet ) { + ProcessedItems::$processed['github-step'][ $packet['metadata']['item_identifier'] ] = array( 'processed' => true ); + } + function routes() { + return array_column( $GLOBALS['requests'], 0 ); + } + + $first = array( blob( 'docs/nested/hello #.md', 'a' ), blob( 'docs/old.md', 'b' ), blob( 'docs/not.txt', 'c' ), blob( 'docs-extra/outside.md', 'd' ), blob( 'docs/large.md', 'e', 21 ) ); + fixture( 'one', $first ); + content( 'a', 'hello' ); + content( 'b', '' ); + $packets = run_fetch(); + check( is_array( $packets ) && 2 === count( $packets ), 'Prefix, glob or size filter picked the wrong files.' ); + check( array( '', '/commits/release%2Fdocs', '/git/trees/tree-one?recursive=1', '/git/blobs/a', '/git/blobs/b' ) === routes(), 'First fetch did not use default branch, pinned tree and matching blobs.' ); + $meta = $packets[0]['metadata']; + check( 'hello' === $packets[0]['data']['body'] && '' === $packets[1]['data']['body'], 'Blob contents (including empty files) were not emitted.' ); + check( 'nested/hello #.md' === $meta['github_relative_file_path'] && 'one' === $meta['github_commit_sha'] && 'release/docs' === $meta['github_branch'], 'File identity metadata is incomplete.' ); + check( 'https://github.com/owner/repo/blob/one/docs/nested/hello%20%23.md' === $meta['source_url'] && $meta['source_url'] === $meta['github_url'], 'URL is not pinned or encoded.' ); + check( 'github_owner/repo_files_docs/nested/hello #.md_a' === $meta['dedup_key'] && $meta['dedup_key'] === $meta['original_id'], 'DocSync identity is incorrect.' ); + foreach ( $packets as $packet ) { + check( 'added' === $packet['metadata']['github_change'], 'First run must only emit additions.' ); + mark_processed( $packet ); + } + check( ! isset( $GLOBALS['requests'][0][1]['headers']['Authorization'] ), 'Public fetch sent an auth header.' ); + + fixture( 'one', $first ); + check( array() === run_fetch(), 'An unchanged run emitted processed files.' ); + check( array( '/commits/release%2Fdocs', '/git/trees/tree-one?recursive=1' ) === routes(), 'An unchanged run requested more than commit and tree.' ); + + fixture( 'no-docs', array(), false, false ); + $error = run_fetch(); + check( is_wp_error( $error ) && 'github_missing_file_path' === $error->get_error_code(), 'A previously tracked prefix that disappears must fail, not emit mass removals.' ); + + $next = array( blob( 'docs/nested/hello #.md', 'f' ) ); + fixture( 'two', $next ); + $GLOBALS['responses']['/git/blobs/f'] = array( 503, array( 'message' => 'temporarily unavailable' ) ); + $error = run_fetch(); + check( is_wp_error( $error ) && 'github_api_error' === $error->get_error_code() && str_contains( $error->get_error_message(), '503' ), 'Non-2xx blob response did not fail the run.' ); + + fixture( 'two', $next ); + content( 'f', 'changed' ); + $packets = run_fetch(); + check( is_array( $packets ) && 2 === count( $packets ), 'Expected one removal and one modification after retry.' ); + $meta = $packets[0]['metadata']; + check( 'removed' === $meta['github_change'] && 'docs/old.md' === $meta['github_file_path'] && 'b' === $meta['github_file_sha'] && 'two' === $meta['github_commit_sha'] && '' === $packets[0]['data']['body'], 'Removal packet is incorrect.' ); + check( 'modified' === $packets[1]['metadata']['github_change'] && 'changed' === $packets[1]['data']['body'], 'Modified file packet is incorrect.' ); + mark_processed( $packets[1] ); + fixture( 'two', $next ); + $packets = run_fetch(); + check( 1 === count( $packets ) && 'removed' === $packets[0]['metadata']['github_change'], 'Unprocessed removals should be retried.' ); + mark_processed( $packets[0] ); + fixture( 'two', $next ); + check( array() === run_fetch(), 'A processed removal was repeated.' ); + + fixture( 'two', $next ); + $error = run_fetch( array( 'file_path' => 'missing' ) ); + check( is_wp_error( $error ) && 'github_missing_file_path' === $error->get_error_code(), 'A missing prefix must fail.' ); + check( array() === run_fetch( array( 'file_pattern' => '*.rst' ) ), 'An existing path with no matching glob should succeed empty.' ); + fixture( 'three', array(), true ); + $error = run_fetch(); + check( is_wp_error( $error ) && 'github_tree_truncated' === $error->get_error_code(), 'A truncated tree must fail.' ); + + $provider = apply_filters( 'datamachine_auth_providers', array() )['github']; + check( $provider->save_config( array( 'access_token' => 'test-private-token' ) ), 'Could not save GitHub token.' ); + check( ! str_contains( json_encode( $GLOBALS['options'] ), 'test-private-token' ), 'The GitHub token was stored in the clear.' ); + fixture( 'two', $next ); + content( 'f', 'changed' ); + $packets = run_fetch( array( 'flow_step_id' => 'private-step' ) ); + check( is_array( $packets ) && 1 === count( $packets ) && 'added' === $packets[0]['metadata']['github_change'], 'Private fetch or step isolation failed.' ); + foreach ( $GLOBALS['requests'] as list( $route, $args ) ) { + check( 'Bearer test-private-token' === ( $args['headers']['Authorization'] ?? '' ), 'Missing bearer token on ' . $route ); + } + + $GLOBALS['responses']['/contents/docs/a%20b.md?ref=release%2Fdocs'] = array( 200, array( 'encoding' => 'base64', 'content' => 'b2s=' ) ); + check( 'ok' === ( new GitHubClient() )->get_file_contents( 'owner/repo', 'docs/a b.md', 'release/docs' ), 'Contents-by-path API failed.' ); + echo "GitHub files smoke passed.\n"; +} diff --git a/plugins/data-machine-business/tests/github-handler-contract-smoke.php b/plugins/data-machine-business/tests/github-handler-contract-smoke.php new file mode 100644 index 000000000..8776c9377 --- /dev/null +++ b/plugins/data-machine-business/tests/github-handler-contract-smoke.php @@ -0,0 +1,70 @@ + array( 'get', 'upsert' ), + \DataMachine\Core\ExecutionContext::class => array( 'isFlow', 'getFlowStepId', 'isItemProcessed', 'classifySourceItems' ), + \DataMachine\Core\Steps\Fetch\Handlers\FetchHandler::class => array( 'getAuthProvider' ), +); +foreach ( $methods as $class => $names ) { + foreach ( $names as $name ) { + $check( method_exists( $class, $name ), "{$class}::{$name}() is missing." ); + } +} + +$upsert = ! class_exists( \DataMachine\Core\Database\TrackedItems\TrackedItems::class ) ? null : new ReflectionMethod( \DataMachine\Core\Database\TrackedItems\TrackedItems::class, 'upsert' ); +$check( $upsert && 1 === $upsert->getNumberOfRequiredParameters(), 'TrackedItems::upsert() no longer takes a single row array.' ); + +if ( $failures ) { + fwrite( STDERR, implode( "\n", $failures ) . "\n" ); + exit( 1 ); +} + +echo "GitHub handler contract smoke passed.\n"; diff --git a/plugins/data-machine-business/tests/provider-bootstrap-smoke.php b/plugins/data-machine-business/tests/provider-bootstrap-smoke.php index 7de887886..b23469c2c 100644 --- a/plugins/data-machine-business/tests/provider-bootstrap-smoke.php +++ b/plugins/data-machine-business/tests/provider-bootstrap-smoke.php @@ -111,6 +111,7 @@ static function (): void { 'google-search-console', 'slack', 'discord', + 'github', 'bing-webmaster', 'amazon-affiliate', 'media-hygiene',