diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 61d41da..4b5eaf3 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -2,12 +2,12 @@ name: Docker (GHCR) on: push: - branches: [main, release] + branches: [main] workflow_dispatch: concurrency: group: docker-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: false env: IMAGE: ghcr.io/${{ github.repository }} @@ -18,12 +18,15 @@ permissions: jobs: read-version: - if: github.ref == 'refs/heads/release' + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest outputs: version: ${{ steps.pkg.outputs.version }} + is_new_version: ${{ steps.version.outputs.is_new_version }} steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Read version id: pkg @@ -36,6 +39,22 @@ jobs: ") echo "version=$VERSION" >> $GITHUB_OUTPUT + - name: Check release version + id: version + env: + VERSION: ${{ steps.pkg.outputs.version }} + run: | + if git rev-parse "refs/tags/v${VERSION}" >/dev/null 2>&1; then + TAG_SHA=$(git rev-list -n 1 "v${VERSION}") + if [ "$TAG_SHA" = "$GITHUB_SHA" ]; then + echo "is_new_version=true" >> "$GITHUB_OUTPUT" + else + echo "is_new_version=false" >> "$GITHUB_OUTPUT" + fi + else + echo "is_new_version=true" >> "$GITHUB_OUTPUT" + fi + build-dev: if: github.ref == 'refs/heads/main' strategy: @@ -168,7 +187,7 @@ jobs: build-release: needs: read-version - if: github.ref == 'refs/heads/release' + if: github.ref == 'refs/heads/main' && needs.read-version.outputs.is_new_version == 'true' strategy: fail-fast: false matrix: @@ -235,7 +254,7 @@ jobs: merge-release: needs: [read-version, build-release] - if: ${{ !cancelled() && needs.read-version.result == 'success' && github.ref == 'refs/heads/release' }} + if: ${{ !cancelled() && needs.read-version.result == 'success' && github.ref == 'refs/heads/main' && needs.read-version.outputs.is_new_version == 'true' }} runs-on: ubuntu-latest steps: - name: Download digests @@ -268,7 +287,7 @@ jobs: merge-release-alpine: needs: [read-version, build-release] - if: ${{ !cancelled() && needs.read-version.result == 'success' && github.ref == 'refs/heads/release' }} + if: ${{ !cancelled() && needs.read-version.result == 'success' && github.ref == 'refs/heads/main' && needs.read-version.outputs.is_new_version == 'true' }} runs-on: ubuntu-latest steps: - name: Download digests diff --git a/.github/workflows/pypi.yml b/.github/workflows/pypi.yml index 12c204a..6848749 100644 --- a/.github/workflows/pypi.yml +++ b/.github/workflows/pypi.yml @@ -2,7 +2,7 @@ name: Publish to PyPI on: push: - branches: [release] + branches: [main] workflow_dispatch: concurrency: @@ -85,7 +85,7 @@ jobs: build: needs: preflight - if: github.ref == 'refs/heads/release' && (needs.preflight.outputs.publish_needed == 'true' || needs.preflight.outputs.release_assets_needed == 'true') + if: github.ref == 'refs/heads/main' && (needs.preflight.outputs.publish_needed == 'true' || needs.preflight.outputs.release_assets_needed == 'true') runs-on: ubuntu-latest steps: - name: Checkout @@ -132,7 +132,7 @@ jobs: publish: needs: [preflight, build] - if: github.ref == 'refs/heads/release' && needs.preflight.outputs.publish_needed == 'true' + if: github.ref == 'refs/heads/main' && needs.preflight.outputs.publish_needed == 'true' runs-on: ubuntu-latest environment: pypi permissions: @@ -176,7 +176,7 @@ jobs: github-release-assets: needs: [preflight, build] - if: github.ref == 'refs/heads/release' && needs.preflight.outputs.release_assets_needed == 'true' + if: github.ref == 'refs/heads/main' && needs.preflight.outputs.release_assets_needed == 'true' runs-on: ubuntu-latest permissions: contents: write diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 303edcc..83e3296 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,12 +1,12 @@ # ----------------------------------------------------------------------------- # Release - Create GitHub release from CHANGELOG, trigger Docker builds -# Runs on pushes to the release branch when version changes. +# Runs on pushes to main; existing versions are skipped. # ----------------------------------------------------------------------------- name: Release on: push: - branches: [release] + branches: [main] concurrency: group: release-${{ github.ref }} @@ -48,6 +48,7 @@ jobs: echo "Release v${{ steps.pkg.outputs.version }} already exists - skipping creation" else gh release create "v${{ steps.pkg.outputs.version }}" \ + --target "$GITHUB_SHA" \ --title "v${{ steps.pkg.outputs.version }}" \ --notes-file /tmp/release-notes.md fi diff --git a/CHANGELOG.md b/CHANGELOG.md index 03d0623..3bbfd3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,35 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [0.6.0] - 2026-10-21 + +### Added + +- **Gitea repositories**: sync files from public or private Gitea repositories, including servers you host yourself. Choose a branch or folder, exclude files, preview changes, and schedule updates. Each source can use a different server and sign-in. Supports Gitea 1.24.0 and later, with tests against 1.24.0, 1.26.4, and 28.2.0. +- **Gitea wikis**: sync built-in Markdown wiki pages, including sidebar and footer pages. Repository files and wiki pages can share a Knowledge Base, with separate destination folders to keep matching filenames apart. +- **Gitea change notifications**: repository pushes and wiki edits can start a sync automatically. Each notice is checked against the configured secret, server, repository, and selected branch where applicable. One change updates every matching Knowledge Base, including its other configured sources. +- **SharePoint folder selection**: sync one folder within a document library instead of the whole library. Uploaded paths start inside that folder, so selecting `Exceptions` uploads `Exceptions/report.xlsx` as `report.xlsx`. +- **SharePoint cloud settings per source**: use commercial, GCC High, and Department of Defense SharePoint sources together, each with its own cloud setting. +- **BookStack certificate setting**: added an option to turn off server certificate checks for installations using self-signed certificates. Certificate checks remain enabled by default. + +### Fixed + +- **Markdown uploads**: Markdown files are now identified as text when sent to Open WebUI, including from minimal Docker installations. This avoids sending them to a document converter that can fail to read them. +- **Nextcloud file listings**: accounts with usernames containing `@`, spaces, accented letters, or `%` no longer miss files because Nextcloud writes their folder addresses differently. Filenames with spaces or literal `%` characters are also preserved when downloading. +- **Separate sync status**: sources with the same address no longer overwrite each other's status and history labels. For example, two Gitea servers can both have `gitea:team/docs` and still report their results separately. +- **Configuration checks**: validation now uses each source's configured branch and folder, catches invalid Gitea wiki options and missing notification secrets, and closes source connections when finished. +- **Docker image publishing**: a failed Alpine build no longer prevents publishing a successfully built standard image, or vice versa. Each image still requires both its Intel/AMD and ARM builds to finish before publication. + +### Changed + +- **Repeated source names**: when the same source address appears more than once in the configuration, each entry now requires a distinct name. Those names identify its status and sync history. +- **Release publishing**: releases, Python packages, and versioned Docker images now publish from `main` instead of a separate `release` branch. GitHub releases point to the exact commit that started the release run, and a newer push no longer cancels an in-progress Docker build. + +### Notes + +- **Gitea sync checks**: if oikb cannot finish listing the repository, or detects that a wiki page changed while being read, it stops before changing the Knowledge Base. Repository downloads use the version selected at the start of the scan, even if someone pushes another change during the sync. +- **Gitea wiki limits**: blank pages, or pages too large for Gitea to return, stop the sync. Add text to or remove blank pages, and raise the server's page-size limit for larger pages. Wiki attachments are not included. See the [Gitea guide](docs/guide.md#gitea) for setup and other limits. + ## [0.5.0] - 2026-09-16 ### Added diff --git a/README.md b/README.md index 18f696a..e25b953 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 📚 oikb -Keep your [Open WebUI](https://github.com/open-webui/open-webui) Knowledge Bases in sync. Point it at a local directory, a GitHub repo, a Confluence space, an S3 bucket, Zotero, or any of 46 supported sources. Only new and modified files are uploaded via incremental SHA-256 diffing. +Keep your [Open WebUI](https://github.com/open-webui/open-webui) Knowledge Bases in sync. Point it at a local directory, a GitHub or Gitea repo, a Confluence space, an S3 bucket, Zotero, or any of 47 supported sources. Only new and modified files are uploaded via incremental source-checksum diffing. > [!IMPORTANT] > Requires **Open WebUI 0.9.6+** @@ -53,7 +53,7 @@ oikb daemon --port 8080 Features: - **Scheduled sync** — simple intervals (`30m`, `1h`) or cron expressions (`0 6 * * 1-5`) -- **Webhooks** — instant sync on push via `/webhooks/github`, `/webhooks/gitlab`, `/webhooks/slack`, `/webhooks/confluence` +- **Webhooks** — sync on source changes via `/webhooks/github`, `/webhooks/gitlab`, `/webhooks/gitea`, `/webhooks/slack`, `/webhooks/confluence` - **Health checks** — `GET /health` for Docker/K8s readiness probes - **Prometheus metrics** — `GET /metrics` exports sync counters, duration histograms, and error rates - **Sync history** — `GET /history` queryable log of all syncs @@ -136,11 +136,11 @@ services: start_period: 15s ``` -## 46 Connectors +## 47 Connectors | Category | Sources | |---|---| -| **Code Repos** | GitHub, GitLab, Bitbucket | +| **Code Repos** | GitHub, GitLab, Gitea, Bitbucket | | **Cloud Storage** | S3, GCS, Azure Blob, Dropbox, R2, Google Drive, SharePoint, Nextcloud, Egnyte, Oracle Cloud | | **Wikis & KBs** | Confluence, Notion, BookStack, Discourse, GitBook, Guru, Outline, Slab, Document360, DokuWiki, Google Sites | | **Ticketing** | Jira, Linear, Zendesk, Freshdesk, Asana, ClickUp, Airtable, ServiceNow, ProductBoard | @@ -162,6 +162,24 @@ oikb sync "zotero:Research%%Machine Learning" --kb-id your-kb-id Some connectors need an optional extra: `pip install oikb[gdrive]`, `pip install oikb[s3]`, `pip install oikb[zotero]`, or `pip install oikb[all]` for everything. +### Gitea + +Sync repository files or built-in wiki pages from Gitea 1.24.0+ (no extra dependency): + +```bash +export GITEA_URL=https://git.example.com # Instance root; /gitea subpaths work too +export GITEA_TOKEN=your-read-token # Optional for public repositories + +oikb sync gitea:engineering/docs/handbook --kb-id your-kb-id +oikb diff 'gitea:engineering/docs?wiki=true' --kb-id your-wiki-kb-id +``` + +Use a personal access token with `read:repository`. Per-source `auth.base_url` +and `auth.token` override the environment; `--url` and `--token` always configure +Open WebUI. Repository scans and downloads use the same pinned commit. Wiki +pages are checked and cached before syncing. See the [Gitea guide](docs/guide.md#gitea) +for shared KBs, webhooks, compatibility tests, and wiki limitations. + ### Zotero ```bash diff --git a/docs/guide.md b/docs/guide.md index f09f4db..4e831ee 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -19,6 +19,7 @@ A complete guide to syncing content into Open WebUI Knowledge Bases. - [Local Directories](#local-directories) - [GitHub](#github) - [GitLab / Bitbucket](#gitlab--bitbucket) + - [Gitea](#gitea) - [Confluence](#confluence) - [BookStack](#bookstack) - [Cloud Storage (S3 / GCS / Azure)](#cloud-storage-s3--gcs--azure) @@ -276,6 +277,117 @@ oikb sync bitbucket:owner/repo --kb-id your-kb-id Requires `GITLAB_TOKEN` or `BITBUCKET_TOKEN` respectively. +### Gitea + +Repository files and standard built-in Markdown wiki pages are supported through +the REST API, with no Git installation or optional Python dependency. API +compatibility targets Gitea 1.24.0 and later; use a maintained server release. +Forgejo compatibility is not claimed. + +```bash +export GITEA_URL=https://git.example.com +export GITEA_TOKEN=your-read-token + +oikb sync gitea:engineering/docs --branch main --path handbook --kb-id your-kb-id +oikb diff 'gitea:engineering/docs?wiki=true' --kb-id your-wiki-kb-id + +# Explicit credentials for a second instance: +oikb sync gitea:team/docs --kb-id your-kb-id \ + --auth base_url=https://other.example/gitea --auth token=your-other-token +``` + +Create a personal access token with `read:repository` and access to the selected +repositories. Public access may work without a token, depending on the instance. +Tokens are sent in an Authorization header. The URL is required: there is no +implicit public Gitea host. + +| Setting | Meaning | +|---|---| +| `auth.base_url` / `GITEA_URL` | Instance root, including an optional context path and port; omit `/api/v1`. | +| `auth.token` / `GITEA_TOKEN` | Source PAT; explicit `auth.token: ""` disables environment-token fallback. | +| `branch` / `--branch` | Branch name, including names with `/`; defaults to the repository default branch. | +| `path` / `--path` | Directory within the repository; overrides an inline source directory. An explicit empty path selects the root. | +| `?wiki=true` | Select the built-in wiki; branch and path options are not accepted in this mode. | +| `gitea_secret` | Required signing secret for a webhook-enabled Gitea source. | + +Explicit source settings take precedence over the environment. Top-level YAML +`url`/`token` and CLI `--url`/`--token` configure **Open WebUI**, not Gitea. +HTTPS certificate verification stays enabled; configure `SSL_CERT_FILE` for a +private certificate authority. Redirects are rejected: use the canonical +instance root and correct reverse-proxy configuration. + +To combine files and a wiki in one KB, configure both together and give them +distinct destination prefixes: + +```yaml +defaults: + interval: 30m + +sources: + - name: engineering-docs + source: gitea:engineering/docs/handbook + kb-id: shared-kb + target-path: handbook + branch: main + auth: + base_url: ${GITEA_URL} + token: ${GITEA_TOKEN} + filter: + include: ["*.md", "*.txt"] + max-size: 50mb + webhook: true + gitea_secret: ${GITEA_WEBHOOK_SECRET} + + - name: engineering-wiki + source: "gitea:engineering/docs?wiki=true" + kb-id: shared-kb + target-path: wiki + auth: + base_url: ${GITEA_URL} + token: ${GITEA_TOKEN} + webhook: true + gitea_secret: ${GITEA_WEBHOOK_SECRET} +``` + +Run `oikb validate`, then `oikb sync --name engineering-docs --dry-run` before +syncing. The named command processes the entire shared-KB group. `validate` +checks local Gitea configuration; `validate --deep` checks Open WebUI connectivity. +Use `diff` or a dry run to check Gitea access. + +Repository listing is fully paginated and downloads are pinned to the scanned +commit. Files retain their original bytes and use Git blob IDs as checksums. +Symlinks and submodules are skipped. LFS pointers are synced as pointer text; +LFS objects are not downloaded. A missing branch or directory, failed request, +or incomplete listing stops the scan before any destination diff or cleanup. + +Wiki documents use their canonical API page names plus `.md` (for example, +`Home.md` or `100%25+Free.md`). Escaped slashes remain part of the filename. +Markdown is preserved, including sidebar/footer pages when listed, without +repeating navigation content inside other documents. Existing filters can +exclude those files. Arbitrary wiki attachments and nested Git-only wiki files +are not supported. + +A wiki scan reads every page, verifies revisions against two complete metadata +passes, and caches its bytes for upload. Filters apply after this scan. If a +page changes during scanning, retry once the wiki settles. Gitea returns the +same empty content field for a blank page and a page exceeding +`[api] DEFAULT_MAX_BLOB_SIZE`; either stops the scan. Add content to/remove blank +pages, or raise that server limit for oversized pages. Disabled, external, or +uninitialized wikis are errors, not empty sources. + +An entirely empty combined manifest retains oikb's existing no-cleanup behavior. +An empty member of a nonempty shared-KB group can have its old files removed. +After a successful scan, the shared sync engine still deletes stale files before +uploading replacements; a later upload failure can temporarily leave files missing. + +The opt-in integration suite creates disposable Gitea 1.24.0, 1.26.4, and 28.2.0 +Docker containers, including a reverse-proxy subpath deployment. It uses isolated +test accounts and a mock Open WebUI destination, never ambient production credentials: + +```bash +OIKB_GITEA_INTEGRATION=1 python -m pytest tests/test_gitea_integration.py -v +``` + ### Confluence ```bash @@ -415,7 +527,7 @@ sources: ``` To sync only one folder of a library and drop that folder from the uploaded paths, -set `path` (or pass `--source-path`). Files are uploaded relative to that folder: +set `path` (or pass `--path`). Files are uploaded relative to that folder: ```yaml sources: @@ -487,11 +599,11 @@ Optional settings: ### All Connectors -46 connectors available. See the full list: +47 connectors available. See the full list: | Category | Sources | |---|---| -| **Git** | GitHub, GitLab, Bitbucket | +| **Git** | GitHub, GitLab, Gitea, Bitbucket | | **Cloud Storage** | S3, GCS, Azure Blob, Dropbox, R2, Google Drive, SharePoint, Nextcloud, Egnyte, Oracle Cloud | | **Wikis & KBs** | Confluence, Notion, BookStack, Discourse, GitBook, Guru, Outline, Slab, Document360, DokuWiki, Google Sites | | **Ticketing** | Jira, Linear, Zendesk, Freshdesk, Asana, ClickUp, Airtable, ServiceNow, ProductBoard | @@ -609,6 +721,7 @@ Both can be mixed in the same config. Auto-detected by field count. | `POST /sync/{id}?dry_run=true` | Preview changes without uploading | | `POST /webhooks/github` | GitHub push webhook | | `POST /webhooks/gitlab` | GitLab push webhook | +| `POST /webhooks/gitea` | Signed Gitea push and wiki webhook | | `POST /webhooks/slack` | Slack event webhook | | `POST /webhooks/confluence` | Confluence update webhook | @@ -640,7 +753,27 @@ sources: Then add a webhook in GitHub → Settings → Webhooks pointing to `http://your-daemon:8080/webhooks/github`. -Supported: GitHub, GitLab, Slack, Confluence. +Supported: GitHub, GitLab, Gitea, Slack, Confluence. + +For Gitea, enable `webhook: true` and set `gitea_secret` on each source (see the +[Gitea example](#gitea)). In the repository's Settings → Webhooks, choose the +**Gitea** type, POST, `application/json`, the same secret, and push/wiki events. +Set the target to `https://your-daemon/webhooks/gitea`. The route validates +`X-Gitea-Signature` independently of `OIKB_API_KEY`; it does not need the daemon's +administrative bearer token. No webhook is automatically created on the server. + +Each source keeps its own signing secret. Matching includes the canonical +instance URL/context path, exact owner/repository, and selected branch. Keep +`GITEA_URL` consistent with Gitea's configured `ROOT_URL`, which supplies webhook +repository URLs. Tag pushes, branch deletions, and unrelated events are ignored. +A matching event schedules each affected KB once and includes all sibling +sources in that KB. Concurrent triggers may be skipped while a sync is running; +keep periodic polling enabled to reconcile later changes. + +When multiple entries have the same source string (including the same repository +name on different instances), give them distinct nonempty `name` values. Those +names identify status, metrics, and history; unique source strings keep their +existing identifiers. Names must not collide with another effective status key. --- diff --git a/pyproject.toml b/pyproject.toml index 06439ed..ffb909f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "oikb" -version = "0.5.0" +version = "0.6.0" description = "Sync anything to Open WebUI Knowledge Bases" readme = "README.md" authors = [ @@ -55,3 +55,6 @@ oikb = "oikb.cli:cli" [build-system] requires = ["uv_build>=0.8.0,<0.9"] build-backend = "uv_build" + +[tool.pytest.ini_options] +markers = ["integration: opt-in tests using disposable Gitea Docker containers"] diff --git a/src/oikb/__init__.py b/src/oikb/__init__.py index 73e3673..7ff287a 100644 --- a/src/oikb/__init__.py +++ b/src/oikb/__init__.py @@ -1,3 +1,3 @@ """oikb — Open WebUI Knowledge Base CLI.""" -__version__ = "0.5.0" +__version__ = "0.6.0" diff --git a/src/oikb/cli.py b/src/oikb/cli.py index b962e2e..6143882 100644 --- a/src/oikb/cli.py +++ b/src/oikb/cli.py @@ -62,6 +62,12 @@ def _resolve_connector( """ auth = auth or {} + if source.startswith("gitea:"): + from oikb.connectors.gitea import GiteaConnector, parse_gitea_source + parsed = parse_gitea_source(source) + parsed["path"] = path if path is not None else parsed["path"] + return GiteaConnector(**parsed, branch=branch, **auth) + if source.startswith("github:"): from oikb.connectors.github import GitHubConnector, parse_github_source parsed = parse_github_source(source) @@ -419,7 +425,7 @@ def _parse_auth_option(pairs: tuple[str, ...]) -> dict[str, str]: @cli.command() @click.argument("source", required=False) @common_options -@click.option("--branch", default=None, help="Branch for GitHub sources.") +@click.option("--branch", default=None, help="Branch for repository sources (GitHub, GitLab, Gitea, Bitbucket).") @click.option("--path", "source_path", default=None, help="Subdirectory within the source.") @click.option("--dry-run", is_flag=True, help="Preview changes without uploading.") @click.option("-v", "--verbose", is_flag=True, help="Show detailed progress.") @@ -452,7 +458,7 @@ def sync( ): """Incremental sync from a source to a Knowledge Base. - SOURCE can be a local directory, github:owner/repo, or s3://bucket/prefix. + SOURCE can be a local directory, github:owner/repo, gitea:owner/repo, or s3://bucket/prefix. If omitted, reads .oikb.yaml from the current directory. """ quiet = ctx.obj.get("quiet", False) @@ -544,6 +550,7 @@ def sync( try: client = _make_client(url, token) except ValueError as e: + connector.close() click.echo(click.style(str(e), fg="red"), err=True) sys.exit(1) @@ -586,7 +593,7 @@ def sync( @cli.command() @click.argument("source") @common_options -@click.option("--branch", default=None, help="Branch for GitHub sources.") +@click.option("--branch", default=None, help="Branch for repository sources (GitHub, GitLab, Gitea, Bitbucket).") @click.option("--path", "source_path", default=None, help="Subdirectory within the source.") @click.option("-v", "--verbose", is_flag=True, help="Show detailed output.") @click.option( @@ -624,6 +631,7 @@ def diff( try: client = _make_client(url, token) except ValueError as e: + connector.close() click.echo(click.style(str(e), fg="red"), err=True) sys.exit(1) @@ -942,6 +950,14 @@ def validate(config_file: str | None, deep: bool): click.echo(click.style("No .oikb.yaml found or file is empty.", fg="red"), err=True) sys.exit(1) + from oikb.config import source_status_keys + from oikb.webhooks import prepare_webhook_entries + try: + source_status_keys(entries) + prepare_webhook_entries(entries) + except (ValueError, TypeError) as exc: + raise click.ClickException(str(exc)) from exc + # Deep validation: create a client and verify connectivity first. client = None if deep: @@ -970,7 +986,9 @@ def validate(config_file: str | None, deep: bool): # Syntax check: resolve the connector (using its configured auth, # since some connectors — e.g. SharePoint — authenticate eagerly). try: - _resolve_connector(source, auth=entry.get("auth", {})) + with _resolve_connector(source, branch=entry.get("branch"), + path=entry.get("path"), auth=entry.get("auth", {})): + pass except Exception as e: click.echo(click.style(f" ✗ {entry_name}: {e}", fg="red")) has_errors = True diff --git a/src/oikb/config.py b/src/oikb/config.py index 68142b5..f6b7fc2 100644 --- a/src/oikb/config.py +++ b/src/oikb/config.py @@ -9,6 +9,7 @@ Resolution order (highest priority first): from __future__ import annotations import os +from collections import Counter from pathlib import Path import yaml @@ -17,6 +18,21 @@ CONFIG_DIR = Path(os.environ.get("OIKB_CONFIG_DIR", Path.home() / ".config" / "o CONFIG_FILE = CONFIG_DIR / "config.yaml" +def source_status_keys(entries: list[dict]) -> list[str]: + """Keep existing status keys unless repeated sources need named identities.""" + counts = Counter(entry.get("source") for entry in entries) + keys = [] + for entry in entries: + source = entry.get("source") + key = entry.get("name") if counts[source] > 1 else source + if not isinstance(key, str) or not key.strip(): + raise ValueError("Sources require source strings; repeated sources also require distinct nonempty names") + if key in keys: + raise ValueError(f"Duplicate source status key: {key}. Choose distinct source names.") + keys.append(key) + return keys + + def _load_config_file() -> dict: """Load config from disk. Returns empty dict if file doesn't exist.""" if CONFIG_FILE.exists(): diff --git a/src/oikb/connectors/__init__.py b/src/oikb/connectors/__init__.py index cfb59ca..aff9d6b 100644 --- a/src/oikb/connectors/__init__.py +++ b/src/oikb/connectors/__init__.py @@ -14,7 +14,7 @@ class ManifestEntry: filename: Basename of the file (e.g. "readme.md"). path: Directory path relative to source root (e.g. "docs/api"). Empty string for root-level files. - checksum: SHA-256 hex digest of the file content. + checksum: Stable source checksum or version fingerprint (e.g. a Git blob ID). size: File size in bytes. """ diff --git a/src/oikb/connectors/gitea.py b/src/oikb/connectors/gitea.py new file mode 100644 index 0000000..7d71b48 --- /dev/null +++ b/src/oikb/connectors/gitea.py @@ -0,0 +1,297 @@ +"""Gitea repository files and built-in Markdown wikis via REST API v1.""" + +from __future__ import annotations + +import base64 +import hashlib +import logging +import os +import re +from urllib.parse import parse_qsl, quote, unquote, urlsplit, urlunsplit + +import httpx + +from oikb.connectors import BaseConnector, ManifestEntry + +log = logging.getLogger(__name__) +_OID = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z") + + +def _relative_path(value: str, *, empty: bool = False) -> str: + if not isinstance(value, str) or "\\" in value or any(ord(c) < 32 or ord(c) == 127 for c in value): + raise ValueError("Gitea paths must be relative paths without control characters") + if empty and not value: + return value + if any(p in {"", ".", ".."} for p in value.split("/")): + raise ValueError("Gitea paths must not contain empty or traversal components") + return value + + +def resolve_gitea_url(base_url: str | None = None) -> str: + """Resolve an instance root without making requests or inspecting credentials.""" + value = base_url if base_url is not None else os.environ.get("GITEA_URL", "") + if not isinstance(value, str) or not value or any(c.isspace() for c in value) or "\\" in value: + raise ValueError("Gitea instance URL required: set GITEA_URL or auth.base_url") + parsed = urlsplit(value) + if (parsed.scheme not in {"http", "https"} or not parsed.hostname + or parsed.username is not None or parsed.password is not None + or "?" in value or "#" in value): + raise ValueError("Gitea URL must be an HTTP(S) instance root without credentials, query, or fragment") + # Accessing port validates malformed port values too. + port = parsed.port + path = parsed.path.rstrip("/") + if path: + _relative_path(unquote(path.removeprefix("/"))) + if path.endswith("/api/v1"): + raise ValueError("Use the Gitea instance root, without /api/v1") + host = parsed.hostname.lower() + host = f"[{host}]" if ":" in host else host + if port is not None and port != (443 if parsed.scheme == "https" else 80): + host += f":{port}" + return urlunsplit((parsed.scheme, host, path, "", "")) + + +def parse_gitea_source(source: str) -> dict[str, str | bool | None]: + if not source.startswith("gitea:"): + raise ValueError("Expected gitea:owner/repo[/path][?wiki=true]") + location, _, query = source.removeprefix("gitea:").partition("?") + options = parse_qsl(query, keep_blank_values=True, strict_parsing=True) + if len(options) > 1 or any(k != "wiki" or v not in {"true", "false"} for k, v in options): + raise ValueError("Gitea supports only one wiki=true or wiki=false query option") + parts = location.split("/", 2) + if len(parts) < 2: + raise ValueError("Expected gitea:owner/repo[/path]") + owner, repo = parts[:2] + for component in (owner, repo): + _relative_path(component) + if any(c in component for c in ":?#"): + raise ValueError("Gitea source requires an owner and repository, not a clone URL") + path = parts[2] if len(parts) == 3 else None + if path is not None: + path = _relative_path(path.rstrip("/")) + wiki = bool(options and options[0][1] == "true") + if wiki and path is not None: + raise ValueError("Gitea wiki sources do not support branch or path options") + return {"owner": owner, "repo": repo, "path": path, "is_wiki": wiki} + + +def _object_id(value: object) -> str: + if not isinstance(value, str) or not _OID.fullmatch(value): + raise ValueError("Invalid Gitea Git object ID") + return value + + +def _integer(value: object) -> int: + if type(value) is not int or value < 0: + raise ValueError("Invalid Gitea size or pagination count") + return value + + +class GiteaConnector(BaseConnector): + def __init__( + self, owner: str, repo: str, branch: str | None = None, + path: str | None = None, token: str | None = None, + base_url: str | None = None, is_wiki: bool = False, + ): + for component in (owner, repo): + _relative_path(component) + if any(c in component for c in "/:?#"): + raise ValueError("Gitea owner and repository must be single path components") + if is_wiki and (branch is not None or path is not None): + raise ValueError("Gitea wiki sources do not support branch or path options") + if branch is not None: + _relative_path(branch) + self.owner, self.repo, self.branch = owner, repo, branch + self.path = _relative_path(path.rstrip("/"), empty=True) if path is not None else "" + self.is_wiki = is_wiki + self._base_url = resolve_gitea_url(base_url) + self._endpoint = f"repos/{quote(owner, safe='')}/{quote(repo, safe='')}" + token = token if token is not None else os.environ.get("GITEA_TOKEN", "") + if not isinstance(token, str) or any(ord(c) < 32 or ord(c) == 127 for c in token): + raise ValueError("Gitea token must be a string without control characters") + headers = {"Accept": "application/json"} + if token: + headers["Authorization"] = f"token {token}" + self._http = httpx.Client( + base_url=self._base_url + "/api/v1/", headers=headers, + timeout=60.0, follow_redirects=False, + ) + self._commit: str | None = None + self._files: dict[str, tuple[str, ManifestEntry]] = {} + self._wiki: dict[str, bytes] = {} + + def _get(self, suffix: str = "", **kwargs) -> httpx.Response: + response = self._http.get(self._endpoint + suffix, **kwargs) + if response.is_redirect: + raise ValueError("Gitea redirected the request; check the canonical instance URL and proxy configuration") + response.raise_for_status() + return response + + def build_manifest(self) -> list[ManifestEntry]: + self._commit = None + self._files.clear() + self._wiki.clear() + log.info("Scanning Gitea %s/%s/%s (%s)", self._base_url, self.owner, self.repo, + "wiki" if self.is_wiki else "files") + metadata = self._get().json() + if not isinstance(metadata, dict): + raise ValueError("Invalid Gitea repository metadata") + if self.is_wiki: + if metadata.get("has_wiki") is not True or metadata.get("external_wiki"): + raise ValueError("Gitea built-in wiki is disabled or external") + return self._build_wiki_manifest() + if type(metadata.get("empty")) is not bool: + raise ValueError("Gitea repository metadata is missing the empty flag") + if metadata["empty"]: + if self.branch is not None or self.path: + raise ValueError("Gitea repository is empty; requested branch or directory does not exist") + return [] + branch = self.branch or metadata.get("default_branch") + if not isinstance(branch, str) or not branch: + raise ValueError("Gitea repository has no default branch") + _relative_path(branch) + commit = _object_id(self._get(f"/branches/{quote(branch, safe='')}").json()["commit"]["id"]) + log.info("Gitea %s/%s/%s tree at commit %s", self._base_url, self.owner, self.repo, commit) + files: dict[str, tuple[str, ManifestEntry]] = {} + seen: set[str] = set() + page, total, tree_id = 1, None, None + found_scope = not self.path + while True: + data = self._get(f"/git/trees/{commit}", params={ + "recursive": "true", "per_page": 1000, "page": page, + }).json() + if not isinstance(data, dict) or type(data.get("truncated")) is not bool: + raise ValueError("Invalid Gitea tree pagination response") + current_total = _integer(data.get("total_count")) + current_id = _object_id(data.get("sha")) + if _integer(data.get("page")) != page: + raise ValueError("Gitea tree pagination did not advance") + if total is None: + total, tree_id = current_total, current_id + if total != current_total or tree_id != current_id: + raise ValueError("Gitea tree identity or pagination total changed") + items = data.get("tree") + if items is None and total == 0: + items = [] # Gitea encodes an empty Git tree as null. + if not isinstance(items, list) or (not items and data["truncated"]): + raise ValueError("Incomplete Gitea tree pagination") + for item in items: + original = _relative_path(item["path"]) + if original in seen: + raise ValueError("Repeated Gitea tree path in pagination") + seen.add(original) + mode = item.get("mode") + kinds = {"100644": "blob", "100755": "blob", "120000": "blob", + "040000": "tree", "160000": "commit"} + if mode not in kinds or item.get("type") != kinds[mode]: + raise ValueError("Invalid Gitea tree entry mode or type") + sha, size = _object_id(item.get("sha")), _integer(item.get("size")) + if original == self.path and mode == "040000": + found_scope = True + if self.path and not original.startswith(self.path + "/"): + continue + found_scope = True + if mode not in {"100644", "100755"}: + continue + relative = original[len(self.path) + 1:] if self.path else original + directory, _, filename = relative.rpartition("/") + entry = ManifestEntry(filename, directory, sha, size) + files[relative] = (original, entry) + if len(seen) > total: + raise ValueError("Contradictory Gitea tree pagination total") + # Gitea 1.24 leaves truncated=true on the final populated page. + # A verified stable total and unique paths establish completeness. + if len(seen) == total: + break + if not data["truncated"]: + raise ValueError("Incomplete Gitea tree pagination") + page += 1 + if not found_scope: + raise ValueError(f"Gitea directory does not exist: {self.path}") + self._commit, self._files = commit, files + return sorted((entry for _, entry in files.values()), key=lambda e: e.display_path) + + def _list_wiki(self) -> dict[str, str]: + pages: dict[str, str] = {} + page, limit, total = 1, 50, None + while True: + response = self._get("/wiki/pages", params={"page": page, "limit": limit}) + items = response.json() + count = response.headers.get("x-total-count", "") + if not count.isdecimal() or not isinstance(items, list): + raise ValueError("Gitea wiki pagination requires a valid X-Total-Count and page list") + if total is None: + total = int(count) + if total != int(count) or len(items) > limit: + raise ValueError("Gitea wiki pagination total changed or is invalid") + for item in items: + name = item["sub_url"] + _relative_path(name) + if any(c in name for c in "/?#") or re.search(r"%(?![0-9A-Fa-f]{2})", name): + raise ValueError("Invalid Gitea wiki page identifier") + if name in pages: + raise ValueError("Repeated Gitea wiki page in pagination") + pages[name] = _object_id(item["last_commit"]["sha"]) + if len(pages) > total: + raise ValueError("Contradictory Gitea wiki pagination total") + next_url = response.links.get("next", {}).get("url") + if next_url: + pairs = parse_qsl(urlsplit(next_url).query, keep_blank_values=True) + values = dict(pairs) + if len(values) != len(pairs) or not values.get("page", "").isdecimal(): + raise ValueError("Invalid Gitea wiki pagination link") + next_page = int(values["page"]) + next_limit = values.get("limit", str(limit)) + if not next_limit.isdecimal() or int(next_limit) < 1 or next_page != page + 1: + raise ValueError("Gitea wiki pagination did not advance") + effective_limit = int(next_limit) + if (page > 1 and effective_limit != limit) or len(items) > effective_limit: + raise ValueError("Gitea wiki pagination limit changed") + if page * effective_limit >= total: + raise ValueError("Contradictory Gitea wiki pagination link") + page, limit = next_page, effective_limit + elif page * limit < total: + page += 1 # Older servers have a total count but no Link header. + else: + break + return pages + + def _build_wiki_manifest(self) -> list[ManifestEntry]: + revisions = self._list_wiki() + content: dict[str, bytes] = {} + entries = [] + for name, revision in revisions.items(): + data = self._get("/wiki/page/" + name).json() + if data.get("sub_url") != name or data.get("last_commit", {}).get("sha") != revision: + raise ValueError("Gitea wiki changed during scanning; retry the sync") + encoded = data.get("content_base64") + if not isinstance(encoded, str) or not encoded: + raise ValueError(f"Gitea wiki page {name} is blank or exceeds the server blob limit; " + "add content, remove the blank page, or increase DEFAULT_MAX_BLOB_SIZE") + try: + raw = base64.b64decode(encoded, validate=True) + except (ValueError, UnicodeEncodeError) as exc: + raise ValueError(f"Invalid Base64 content for Gitea wiki page {name}") from exc + filename = name + ".md" + content[filename] = raw + entries.append(ManifestEntry(filename, "", hashlib.sha256(raw).hexdigest(), len(raw))) + if self._list_wiki() != revisions: + raise ValueError("Gitea wiki changed during scanning; retry the sync") + self._wiki = content + return sorted(entries, key=lambda e: e.display_path) + + def read_file(self, path: str, filename: str) -> bytes: + key = f"{path}/{filename}" if path else filename + if self.is_wiki: + return self._wiki[key] + original, entry = self._files[key] + raw = self._get("/raw/" + quote(original, safe="/"), params={"ref": self._commit}, + headers={"Accept": "application/octet-stream"}).content + algorithm = "sha1" if len(entry.checksum) == 40 else "sha256" + digest = hashlib.new(algorithm, b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest() + if len(raw) != entry.size or digest != entry.checksum: + raise ValueError(f"Gitea file does not match the scanned Git object: {original}") + return raw + + def close(self) -> None: + self._http.close() diff --git a/src/oikb/daemon.py b/src/oikb/daemon.py index 44126a6..44f0278 100644 --- a/src/oikb/daemon.py +++ b/src/oikb/daemon.py @@ -40,7 +40,7 @@ async def verify_api_key( app = FastAPI( title="oikb", description="Sync engine for Open WebUI Knowledge Bases. Trigger syncs, check status, and query history.", - version="0.3.5", + version=__version__, ) # Runtime state populated by start_daemon(). @@ -51,6 +51,13 @@ _entries: list[dict] = [] _shutdown_event: asyncio.Event | None = None +def _status_key(entry: dict) -> str: + # Startup validates names for repeated sources; retain old keys otherwise. + if sum(member["source"] == entry["source"] for member in _entries) > 1: + return entry["name"] + return entry["source"] + + # ── Interval / cron parser ─────────────────────────────────────── @@ -267,14 +274,14 @@ async def _run_entry_locked(entry: dict, dry_run: bool = False) -> dict | None: from oikb.sync import SyncCancelled entries = [e for e in _entries if e.get("kb-id") == entry["kb-id"]] or [entry] - source = ", ".join(e["source"] for e in entries) + source = ", ".join(_status_key(e) for e in entries) kb_id = entry["kb-id"] started_at = time.time() client = None def set_state(**state): for member in entries: - _scheduler_state[member["source"]] = { + _scheduler_state[_status_key(member)] = { "name": member.get("name", member["source"]), **state, } @@ -394,7 +401,7 @@ async def _schedule_entry(entry: dict) -> None: ('0 */6 * * *', '0 6 * * 1-5'). """ raw_interval = entry.get("interval", "30m") - source = entry.get("source", "unknown") + source = _status_key(entry) use_cron = _is_cron(str(raw_interval)) if use_cron: @@ -457,7 +464,11 @@ def start_daemon( configure_logging(log_format=log_format) from oikb.kb_sync import group_entries_by_kb + from oikb.config import source_status_keys + from oikb.webhooks import prepare_webhook_entries group_entries_by_kb(entries) # Validate shared destinations before starting tasks. + source_status_keys(entries) + prepare_webhook_entries(entries) _entries = entries _history = SyncHistory() set_build_info(__version__) @@ -508,7 +519,7 @@ def start_daemon( click.echo(f" GET http://localhost:{port}/history") click.echo(f" POST http://localhost:{port}/sync/{{kb_id}}") if webhook_entries: - click.echo(f" POST http://localhost:{port}/webhooks/github|gitlab|slack|confluence") + click.echo(f" POST http://localhost:{port}/webhooks/github|gitlab|gitea|slack|confluence") click.echo(f"\n OpenAPI spec: http://localhost:{port}/openapi.json") click.echo(f" Add as Tool Server in Open WebUI → Settings → Connections") diff --git a/src/oikb/webhooks.py b/src/oikb/webhooks.py index 8715dec..dd7b4a4 100644 --- a/src/oikb/webhooks.py +++ b/src/oikb/webhooks.py @@ -6,6 +6,7 @@ import asyncio import hashlib import hmac import logging +from urllib.parse import unquote, urlsplit from fastapi import APIRouter, Request, HTTPException @@ -14,24 +15,128 @@ log = logging.getLogger(__name__) router = APIRouter(prefix="/webhooks", include_in_schema=False) # Set by daemon.py on startup. -_entries: list[dict] = [] +_hooks: list[dict] = [] _run_entry = None # async callable _secrets: dict[str, str] = {} def configure(entries: list[dict], run_entry, secrets: dict[str, str]) -> None: """Called by daemon on startup to wire webhook state.""" - global _entries, _run_entry, _secrets - _entries = entries + global _hooks, _run_entry, _secrets + hooks = prepare_webhook_entries(entries) + _hooks = hooks _run_entry = run_entry _secrets = secrets +def prepare_webhook_entries(entries: list[dict]) -> list[dict]: + """Prepare one registry of enabled sources and their provider-specific metadata.""" + hooks = [] + for entry in entries: + if not entry.get("webhook"): + continue + hook = {"entry": entry, "provider": str(entry.get("source", "")).partition(":")[0]} + if hook["provider"] == "gitea": + hook.update(_prepare_gitea_metadata(entry)) + hooks.append(hook) + return hooks + + +def _prepare_gitea_metadata(entry: dict) -> dict: + """Validate Gitea identity and signing configuration without making requests.""" + from oikb.connectors.gitea import GiteaConnector, parse_gitea_source + + secret = entry.get("gitea_secret") + if not isinstance(secret, str) or not secret.strip() or "${" in secret: + raise ValueError("Gitea webhook sources require a nonempty resolved gitea_secret") + if not entry.get("kb-id"): + raise ValueError("Gitea webhook sources require kb-id") + parsed = parse_gitea_source(entry["source"]) + parsed["path"] = entry.get("path") if entry.get("path") is not None else parsed["path"] + with GiteaConnector(**parsed, branch=entry.get("branch"), **entry.get("auth", {})) as connector: + return {"secret": secret, "base_url": connector._base_url, + "full_name": f"{connector.owner}/{connector.repo}".casefold(), + "wiki": connector.is_wiki, "branch": connector.branch} + + +def _gitea_repository_matches(hook: dict, html_url: str) -> bool: + """Compare origin, context path, and repository; never follow payload URLs.""" + try: + actual, base = urlsplit(html_url), urlsplit(hook["base_url"]) + if actual.username is not None or actual.password is not None or actual.query or actual.fragment: + return False + port = lambda u: u.port or (443 if u.scheme == "https" else 80) + if (actual.scheme, actual.hostname, port(actual)) != (base.scheme, base.hostname, port(base)): + return False + context, owner, repo = actual.path.rstrip("/").rsplit("/", 2) + return (context == base.path.rstrip("/") + and f"{unquote(owner)}/{unquote(repo)}".casefold() == hook["full_name"]) + except ValueError: + return False + + +@router.post("/gitea") +async def gitea_webhook(request: Request): + body = await request.body() + signature = request.headers.get("X-Gitea-Signature", "") + if len(signature) != 64 or not signature.isascii(): + raise HTTPException(status_code=403, detail="Invalid signature") + hooks = [hook for hook in _hooks if hook["provider"] == "gitea"] + verified = { + secret for secret in {hook["secret"] for hook in hooks} + if hmac.compare_digest(hmac.new(secret.encode(), body, hashlib.sha256).hexdigest(), signature) + } + if not verified: + raise HTTPException(status_code=403, detail="Invalid signature") + try: + data = await request.json() + except ValueError as exc: + raise HTTPException(status_code=400, detail="Invalid JSON payload") from exc + if not isinstance(data, dict): + raise HTTPException(status_code=400, detail="Expected a JSON object") + event = request.headers.get("X-Gitea-Event") + if event not in {"push", "wiki"}: + return {"status": "ignored"} + repo = data.get("repository") + if (not isinstance(repo, dict) or not isinstance(repo.get("full_name"), str) + or not repo["full_name"] or not isinstance(repo.get("html_url"), str) or not repo["html_url"]): + raise HTTPException(status_code=400, detail="Missing repository full_name or html_url") + if event == "push": + ref, after = data.get("ref"), data.get("after") + if not isinstance(ref, str) or not ref or not isinstance(after, str) or not after: + raise HTTPException(status_code=400, detail="Missing push ref or after") + if not ref.startswith("refs/heads/") or set(after) == {"0"}: + return {"status": "ignored"} + elif not isinstance(data.get("action"), str) or data["action"] not in {"created", "edited", "deleted"}: + raise HTTPException(status_code=400, detail="Invalid wiki action") + + matches = {} + for hook in hooks: + if (hook["secret"] not in verified or repo["full_name"].casefold() != hook["full_name"] + or not _gitea_repository_matches(hook, repo["html_url"]) or hook["wiki"] != (event == "wiki")): + continue + if event == "push": + branch = hook["branch"] or repo.get("default_branch") + if not isinstance(branch, str) or not branch: + raise HTTPException(status_code=400, detail="Missing repository default_branch") + if ref != "refs/heads/" + branch: + continue + entry = hook["entry"] + matches.setdefault(entry["kb-id"], entry) + if not matches or not _run_entry: + return {"status": "ignored"} + for entry in matches.values(): + log.info("Gitea %s webhook for %s -> %s", event, entry.get("name", entry["source"]), entry["kb-id"]) + asyncio.create_task(_run_entry(entry)) + return {"status": "accepted", "scheduled": len(matches)} + + def _find_entry_by_source(prefix: str, match: str) -> dict | None: """Find a .oikb.yaml entry matching a source and with webhook: true.""" - for entry in _entries: + for hook in _hooks: + entry = hook["entry"] source = entry.get("source", "") - if source.startswith(prefix) and match in source and entry.get("webhook"): + if source.startswith(prefix) and match in source: return entry return None