Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Serve synced documentation images from the instance

Guido Boyke4bec8339deb5
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index b99ce3f..4e6ccdc 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -725,6 +725,7 @@ jobs:
spec/models/ticket_attribute_definition_spec.rb
spec/requests/organisations/file_downloads_spec.rb
spec/requests/organisations/file_downloads_post_ticket_spec.rb
+ spec/requests/organisations/file_downloads_documentation_asset_spec.rb
spec/requests/organisations/documents_version_authorization_spec.rb
spec/requests/organisations/documents_write_actions_spec.rb
spec/requests/webhooks/repositories_spec.rb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6087c4c..3923f64 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,19 @@ starts (`db:prepare lalabase:data_backfills`). Without Docker, run
## [Unreleased]
+### Changed
+
+- Synced documentation pages show their images from your instance. The sync copies them
+ out of the repository, and they are served behind the right to read the documentation,
+ so a reader no longer contacts the repository host and images from private repositories
+ show. An image that cannot be served shows as its alt text, one with a full address
+ becomes a link. SVG is not shown yet. Limits: 5 MB per image, 200 images per set.
+
+### Upgrade notes
+
+- Run `bin/rails documentation:resync_all` once after updating. Until then a page keeps
+ its old image addresses, unless its repository receives a new commit.
+
## [2026.11.0] - 2026-10-31
<!-- drafted from d31c38282b6a52e09e33ebbe4195546d11421234 -->
diff --git a/CLAUDE.md b/CLAUDE.md
index d92c365..9a27eb8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -325,11 +325,13 @@ The guard asks three questions:
* ⚠️ **The content security policy stops none of this.** It runs in report-only mode
(`config/initializers/content_security_policy.rb`): it logs a violation and lets the request
through. Do not count on it until that line says `false`.
-* ⚠️ **Content is not covered, and it does load from elsewhere.** A synced documentation page
- shows its images from the repository host (`ProjectRepository#raw_file_url`,
- raw.githubusercontent.com), and a Markdown image with an absolute address stays as its
- author wrote it (`Documentation::MarkdownRenderer`). `img-src` allows any https. That is a
- decision about content, and an open one; this guard is about what the application ships.
+* **Synced documentation pages load nothing from elsewhere either**, since 2026-11-01.
+ The sync copies the images a page shows out of the clone (`Documentation::AssetCollector`) and the file proxy serves them behind the right of
+ the documentation; an image that is not served shows as its alt text, one with a foreign
+ address becomes a link. Until then every reader of such a page contacted
+ raw.githubusercontent.com. Held by `documentation_sync_job_spec` ("names no repository
+ host and no address outside the instance").
+* ⚠️ Other content is not covered by this guard, and `img-src` still allows any https.
* Not seen either: an address built at run time (a host in a constant, an interpolated string).
* One named exception, `SAMPLES`: the code samples of the style guide are printed as text, and
one of them shows the forbidden thing on purpose. A comment that quotes a foreign tag or
diff --git a/app/controllers/organisations/file_downloads_controller.rb b/app/controllers/organisations/file_downloads_controller.rb
index 3e1e5ef..ee7e786 100644
--- a/app/controllers/organisations/file_downloads_controller.rb
+++ b/app/controllers/organisations/file_downloads_controller.rb
@@ -37,9 +37,27 @@ module Organisations
model: -> { TicketDocument },
attachment: :ticket_document_file,
authorize_target: ->(record) { record.ticket }
+ },
+ # An image of a synced documentation page is as readable as the documentation:
+ # DocumentationSetPolicy#show? (area :documentation). The cached page HTML holds
+ # this address by id and without a signature, so every request is checked here.
+ # `version` lets the browser keep the file for a moment (VERSIONED_MAX_AGE): the
+ # address does not change when the file does, the version does.
+ 'documentation_asset' => {
+ model: -> { DocumentationAsset },
+ attachment: :file,
+ authorize_target: ->(record) { record.documentation_set },
+ version: ->(record) { record.git_blob_sha }
}
}.freeze
+ # How long a browser may show a versioned file without asking. Short, because the
+ # address stays the same when the file changes; after that it asks with the ETag and
+ # gets a 304. One image is one request through Rails, and the general throttle counts
+ # each (rack_attack, requests/ip): a page with thirty images must not cost thirty
+ # requests on every visit.
+ VERSIONED_MAX_AGE = 5.minutes
+
# Missing access, unknown kind and foreign/tampered IDs all respond UNIFORMLY
# with 404 — so the response does not reveal the existence of foreign files (no 403/404 leak).
rescue_from Pundit::NotAuthorizedError, with: :not_found
@@ -61,6 +79,9 @@ module Organisations
attachment = record.public_send(config.fetch(:attachment))
raise ActiveRecord::RecordNotFound unless attachment.attached?
+ # AFTER the right and the file were checked: a 304 is an answer about this file too.
+ return if fresh_version?(config, record)
+
# Streams from the service (no full load into memory); content type and
# filename come from the blob metadata. We REQUEST inline so previewable
# files (PDF, images) open in the browser instead of force-downloading.
@@ -103,6 +124,16 @@ module Organisations
redirect_to new_user_session_path unless signed_in
end
+ # For a kind that names a version: says so to the browser, and answers 304 (true)
+ # when the browser already holds it.
+ def fresh_version?(config, record)
+ version = config[:version]&.call(record)
+ return false if version.blank?
+
+ expires_in VERSIONED_MAX_AGE, public: false
+ !stale?(etag: version, public: false)
+ end
+
def not_found
head :not_found
end
diff --git a/app/jobs/documentation_sync_job.rb b/app/jobs/documentation_sync_job.rb
index 3cfed5f..f93b087 100644
--- a/app/jobs/documentation_sync_job.rb
+++ b/app/jobs/documentation_sync_job.rb
@@ -90,7 +90,8 @@ class DocumentationSyncJob < ApplicationJob
stamp_set(set, sync_status: 'ready', last_synced_at: Time.current, last_synced_commit: result[:commit])
record_run(context, status: 'ready', commit_sha: result[:commit],
- pages_synced: result[:synced], pages_removed: result[:removed])
+ pages_synced: result[:synced], pages_removed: result[:removed],
+ assets_synced: result[:assets_synced], assets_skipped: result[:assets_skipped])
# Chat-grounding ingestion (Slice 3): fan out embedding jobs only AFTER the
# sync is recorded ready, and only for pages that actually changed this run.
enqueue_embedding_jobs(result[:changed_page_ids])
@@ -111,12 +112,13 @@ class DocumentationSyncJob < ApplicationJob
end
# Clones the repo and upserts every markdown page. Returns counts + commit +
- # the ids of the pages that actually changed (for the embedding fan-out).
+ # the ids of the pages whose markdown changed (for the embedding fan-out).
def clone_and_upsert(set)
synced = 0
seen_paths = []
changed_page_ids = []
commits = []
+ assets = nil
# Preload every existing page once (keyed by path) to avoid a per-file query.
existing_pages = set.documentation_pages.index_by(&:path)
cloner = Lalabase::Indexer::GitCloner.new(set.project_repository, depth: CLONE_DEPTH)
@@ -131,14 +133,22 @@ class DocumentationSyncJob < ApplicationJob
raise path_not_found_error(set) unless contained_in?(repo_path, docs_dir)
raise path_not_found_error(set) unless docs_dir.directory?
+ # The images the pages show are copied out of the clone while it is there:
+ # the renderer asks the collector per image.
+ assets = Documentation::AssetCollector.new(documentation_set: set, repo_path: repo_path)
+
markdown_files(docs_dir).each do |file|
relative = file.relative_path_from(docs_dir).to_s
- changed = upsert_page(set, existing_pages[relative], relative, file.read)
+ changed = upsert_page(set, existing_pages[relative], relative, file.read, assets)
changed_page_ids << changed.id if changed
seen_paths << relative
synced += 1
end
+ # After the pages: what no page showed in this run goes, and no saved page still
+ # points at it.
+ assets.finish
+
# Read inside the block (the clone dir is wiped afterwards); persist
# outside, after the pages are settled.
commits = read_commit_log(set, repo_path)
@@ -146,7 +156,8 @@ class DocumentationSyncJob < ApplicationJob
removed = mark_missing_removed(set, seen_paths)
store_commits(set, commits)
- { synced: synced, removed: removed, commit: cloner.cloned_commit, changed_page_ids: changed_page_ids }
+ { synced: synced, removed: removed, commit: cloner.cloned_commit, changed_page_ids: changed_page_ids,
+ assets_synced: assets&.synced.to_i, assets_skipped: assets&.skipped.to_i }
rescue Lalabase::Indexer::GitCloner::Error => e
raise SyncError.new(e.message, error_class: classify_clone_error(e))
end
@@ -183,22 +194,29 @@ class DocumentationSyncJob < ApplicationJob
end
end
- # Upserts one page. Returns the page WHEN it changed (created, content updated,
- # or revived from removed) so the caller can enqueue its embedding; returns nil
- # for the unchanged skip, which enqueues nothing.
- def upsert_page(set, existing_page, relative_path, content)
- blob_sha = git_blob_sha(content)
+ # Upserts one page. Returns the page WHEN its MARKDOWN changed (created, content
+ # updated, or revived from removed) so the caller can enqueue its embedding; returns
+ # nil otherwise, which enqueues nothing.
+ #
+ # Rendered on every run, written only when something differs. The HTML of a page
+ # depends on more than its own markdown: an image arrives or goes, a knowledge link
+ # finds its target, the renderer itself changes. A page skipped for its unchanged blob
+ # SHA kept the HTML of the day it was last edited, and a manual sync, the repair tool,
+ # repaired nothing. The cost is one render per page per run, beside a git clone.
+ def upsert_page(set, existing_page, relative_path, content, assets)
+ blob_sha = Documentation::GitBlob.sha(content)
# Build the new page standalone (NOT via set.documentation_pages.build): if a
# later page fails to render mid-loop, a half-built page must not sit in the
# set's in-memory association, or the failure path's set.update!(sync_status:)
# would try to autosave that invalid page and raise instead of recording the
# failure cleanly.
page = existing_page || DocumentationPage.new(documentation_set: set, path: relative_path)
+ markdown_changed = page.new_record? || page.git_blob_sha != blob_sha || page.removed_at.present?
- # Unchanged and still present → nothing to do (cheap incremental skip).
- return nil if page.persisted? && page.git_blob_sha == blob_sha && page.removed_at.nil?
+ rendered = render_page(set, relative_path, content, assets)
+ # Unchanged in every respect → nothing to write.
+ return nil unless markdown_changed || page.rendered_html != rendered.html
- rendered = render_page(set, relative_path, content)
page.assign_attributes(
# Reuse the already-loaded tenant so the belongs_to presence check on save
# does not re-query organisations per page.
@@ -211,10 +229,10 @@ class DocumentationSyncJob < ApplicationJob
)
page.save!
# Rebuild the page's outgoing knowledge links (Slice 4) from the targets the
- # renderer just resolved. Reached ONLY on a changed page — the blob-SHA skip
- # above returns nil for an unchanged one, so its references are left untouched.
+ # renderer just resolved. Reached whenever the page was written, so the link index
+ # says what the saved HTML says; an unchanged page returned above and keeps its rows.
rebuild_references(page, rendered.references)
- page
+ page if markdown_changed
end
# Mirror of Note#rebuild_wiki_references: delete + insert keeps a page's outgoing
@@ -260,8 +278,9 @@ class DocumentationSyncJob < ApplicationJob
# Renders the page AND collects the knowledge targets its lalabase:// links
# resolved to (one pass, no second parse). Returns the renderer's Result
# (html + references).
- def render_page(set, relative_path, content)
- Documentation::MarkdownRenderer.new(documentation_set: set, page_path: relative_path).render_with_references(content)
+ def render_page(set, relative_path, content, assets)
+ Documentation::MarkdownRenderer.new(documentation_set: set, page_path: relative_path, asset_resolver: assets)
+ .render_with_references(content)
rescue StandardError => e
raise SyncError.new("failed to render '#{relative_path}': #{e.message}", error_class: 'markdown_invalid')
end
@@ -305,14 +324,6 @@ class DocumentationSyncJob < ApplicationJob
missing_ids.size
end
- # Git blob SHA of the file content (matches `git hash-object`), computed in
- # Ruby so no per-file shell-out is needed.
- def git_blob_sha(content)
- bytes = content.to_s.b
- header = "blob #{bytes.bytesize}\0".b
- Digest::SHA1.hexdigest(header + bytes)
- end
-
def extract_title(content, relative_path)
heading = content.to_s.lines.find { |line| line.start_with?('# ') }
return heading.sub(/\A#\s+/, '').strip if heading
diff --git a/app/models/CLAUDE.md b/app/models/CLAUDE.md
index 2deda0b..9511320 100644
--- a/app/models/CLAUDE.md
+++ b/app/models/CLAUDE.md
@@ -180,7 +180,10 @@ Verzeichnis-Layout nicht ablesbar — diese Karte gruppiert sie:
Selbst-Erwähnung hat keinen Verweis und bleibt liegen. Specs:
`spec/models/action_text/rich_text_embed_key_rotation_spec.rb`,
`spec/services/rich_text_sgid_resign_spec.rb`.
-* **Dokumente/Doku/Codebase**: `document`, `document_version`, `documentation_*`, `codebase_*`,
+* **Dokumente/Doku/Codebase**: `document`, `document_version`, `documentation_*`
+ (`documentation_asset` = ein Bild einer synchronisierten Doku, aus dem Repository kopiert;
+ die gecachte Seite zeigt per ID darauf, ausgeliefert nur über `FileDownloadsController`),
+ `codebase_*`,
`code_symbol`, `project_index{,_run}`, `project_repository`, `project_capability`,
`project_layer4_vision`, `reference`, `fragment`, `imported_object`, `product_knowledge_entry`
(Lalabases eigene Hilfetexte als Suchtabelle, tenant-frei, siehe Falle 3)
diff --git a/app/models/documentation_asset.rb b/app/models/documentation_asset.rb
new file mode 100644
index 0000000..f734251
--- /dev/null
+++ b/app/models/documentation_asset.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+# One image of a DocumentationSet, copied from the repository at sync time and served by
+# the instance through the authorized file proxy.
+#
+# The cached HTML of a page points at this row BY ID, without a signature, so:
+# * the row is upserted per (set, path) and keeps its id when the file changes
+# (Documentation::AssetCollector);
+# * reading it is decided by the proxy, per request: DocumentationSetPolicy#show?.
+#
+# content_type comes from the bytes (Marcel), never from the file name: repository
+# content is not ours, and a page of HTML named logo.png must not be served as one.
+# == Schema Information
+#
+# Table name: documentation_assets
+#
+# id :uuid not null, primary key
+# byte_size :bigint not null
+# content_type :string not null
+# git_blob_sha :string not null
+# path :string not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# documentation_set_id :uuid not null
+# organisation_id :uuid not null
+#
+# Indexes
+#
+# idx_documentation_assets_set_path (documentation_set_id,path) UNIQUE
+# index_documentation_assets_on_organisation_id (organisation_id)
+#
+# Foreign Keys
+#
+# fk_rails_... (documentation_set_id => documentation_sets.id)
+# fk_rails_... (organisation_id => organisations.id)
+#
+class DocumentationAsset < ApplicationRecord
+ acts_as_tenant(:organisation)
+
+ belongs_to :documentation_set
+
+ has_one_attached :file
+
+ validates :path, presence: true, uniqueness: { scope: :documentation_set_id }
+ validates :git_blob_sha, presence: true
+ validates :content_type, presence: true
+ validates :byte_size, numericality: { only_integer: true, greater_than: 0 }
+end
diff --git a/app/models/documentation_set.rb b/app/models/documentation_set.rb
index e51db0b..80c5061 100644
--- a/app/models/documentation_set.rb
+++ b/app/models/documentation_set.rb
@@ -54,6 +54,9 @@ class DocumentationSet < ApplicationRecord
has_many :documentation_sync_runs, dependent: :delete_all
has_many :documentation_set_views, dependent: :delete_all
has_many :documentation_commits, dependent: :delete_all
+ # destroy, not delete_all: the rows are small (no bodies), and only a destroy purges the
+ # file. A disconnected set must not leave a private repository's images in the storage.
+ has_many :documentation_assets, dependent: :destroy
# prepend: true is LOAD-BEARING — it forces this to run BEFORE the association's
# own dependent: :delete_all callback. Without it the pages would be gone by the
diff --git a/app/models/documentation_sync_run.rb b/app/models/documentation_sync_run.rb
index 1a74f96..9c6fbe8 100644
--- a/app/models/documentation_sync_run.rb
+++ b/app/models/documentation_sync_run.rb
@@ -8,6 +8,8 @@
# Table name: documentation_sync_runs
#
# id :uuid not null, primary key
+# assets_skipped :integer default(0), not null
+# assets_synced :integer default(0), not null
# commit_sha :string
# error_class :string
# error_message :text
diff --git a/app/models/project_repository.rb b/app/models/project_repository.rb
index 3bbe277..11ef590 100644
--- a/app/models/project_repository.rb
+++ b/app/models/project_repository.rb
@@ -78,17 +78,6 @@ class ProjectRepository < ApplicationRecord
SecureRandom.hex(WEBHOOK_SECRET_BYTES)
end
- # Public raw-content URL for one file in this repo (used e.g. to display
- # images referenced by synced documentation pages). Lives HERE, next to
- # `provider`, so host-specific URL knowledge has a single home: GitHub-only
- # for now — the same v1 limitation as Lalabase::Indexer::GitCloner. When
- # GitLab support lands, branch on `provider` in this one method.
- # NOTE: unauthenticated by design; files in private repos will 404 (accepted
- # v1 trade-off, see design OQ6 "images not guaranteed").
- def raw_file_url(path_in_repo)
- "https://raw.githubusercontent.com/#{full_name}/#{default_branch}/#{path_in_repo}"
- end
-
validates :provider, presence: true, inclusion: { in: PROVIDERS }
validates :provider_repo_id, presence: true, uniqueness: { scope: %i[provider organisation_id] }
validates :full_name, presence: true, format: { with: FULL_NAME_PATTERN, message: :invalid_full_name }
diff --git a/app/services/CLAUDE.md b/app/services/CLAUDE.md
index cb80c1e..8c7fbe7 100644
--- a/app/services/CLAUDE.md
+++ b/app/services/CLAUDE.md
@@ -508,7 +508,12 @@ Verzeichnis-Übersicht (Auswahl):
„kein Paket" — still und plausibel.
* `codebase_import/`, `user_data_exports/`, `subscriptions/`, `overview/`, `dashboard/`
* **Achtung, zwei ähnlich benannte Domänen:** `documentation/` = aus Repos synchronisierte
- `.md`-Doku (eigener `MarkdownRenderer`, eigene `Navigation`), `product_knowledge/` =
+ `.md`-Doku (eigener `MarkdownRenderer`, eigene `Navigation`; `asset_collector.rb` kopiert
+ beim Sync die Bilder aus dem Klon und ist die EINE Stelle, die entscheidet, was davon
+ ausgeliefert wird: innerhalb des Klons nach Auflösen der Symlinks, Typ aus den Bytes, eine
+ Typliste `RichTextEmbeds::IMAGE_CONTENT_TYPES`; ⚠️ nach einer Änderung am Renderer
+ `bin/rails documentation:resync_all`, ein Poll überspringt unveränderte Repos),
+ `product_knowledge/` =
Lalabases eigene Texte als Tabelle für die Suche. Die dritte, `docs/`, rendert seit **D5
(21.09.2026) kein Markdown mehr** und ist nur noch die LESESCHICHT auf eine fremde Datei
(`doc/docs_delivery_plan.md`).
diff --git a/app/services/documentation/asset_collector.rb b/app/services/documentation/asset_collector.rb
new file mode 100644
index 0000000..6d52c17
--- /dev/null
+++ b/app/services/documentation/asset_collector.rb
@@ -0,0 +1,126 @@
+# frozen_string_literal: true
+
+# Copies the images that the pages of a documentation set refer to out of the cloned
+# repository into the instance, so that a reader's browser asks the instance for them
+# and not the repository host.
+#
+# One collector per sync run. The renderer asks it for every relative image it meets;
+# the job calls #finish after the last page.
+#
+# Entry point: address_for
+#
+# The repository is not ours. Everything accepted here is served from our own origin to
+# everybody who may read the documentation, so an image is taken only if it
+# * lies inside the clone AFTER symlinks are resolved (a link to /etc/hosts is a file
+# "inside" the repository until it is followed),
+# * is a regular, non-empty file of at most MAX_BYTES,
+# * IS an image by its bytes, of a type on the one list of images the application
+# shows inline (RichTextEmbeds::IMAGE_CONTENT_TYPES). The name does not count, and
+# SVG is not on the list: it can carry script.
+# and as long as the set holds fewer than MAX_ASSETS.
+#
+# A refusal is not an error. The page shows the image's alt text instead, and the run
+# counts it (#skipped). The same goes for a storage that fails: the pages are the
+# product, an image must not cost the run.
+module Documentation
+ class AssetCollector
+ MAX_BYTES = 5.megabytes
+ MAX_ASSETS = 200
+ CONTENT_TYPES = RichTextEmbeds::IMAGE_CONTENT_TYPES
+
+ PROXY_KIND = 'documentation_asset'
+
+ def initialize(documentation_set:, repo_path:)
+ @set = documentation_set
+ @root = Pathname.new(repo_path).realpath
+ @addresses = {}
+ @existing = nil
+ end
+
+ # The address of the image at this path of the repository, or nil when it is not
+ # served. Asked once per image and page; answered from memory after the first time.
+ def address_for(repo_relative)
+ path = repo_relative.to_s
+ return @addresses[path] if @addresses.key?(path)
+
+ @addresses[path] = store(path)
+ end
+
+ def synced
+ @addresses.values.count(&:present?)
+ end
+
+ def skipped
+ @addresses.values.count(&:nil?)
+ end
+
+ # Destroys the images of the set that no page asked about in this run. Called after
+ # the pages were rendered and saved, so no saved page points at what goes here.
+ def finish
+ kept = @addresses.select { |_, address| address }.keys
+ @set.documentation_assets.where.not(path: kept).find_each(&:destroy!)
+ end
+
+ private
+
+ def store(path)
+ file = file_inside_the_clone(path)
+ return nil unless file
+
+ bytes = file.binread
+ content_type = Marcel::MimeType.for(StringIO.new(bytes))
+ return nil unless CONTENT_TYPES.include?(content_type)
+
+ asset = existing[path]
+ return nil if asset.nil? && kept_count >= MAX_ASSETS
+
+ proxy_address(upsert(asset, path, bytes, content_type))
+ rescue StandardError => e
+ Rails.logger.warn("Documentation::AssetCollector: skipped '#{path}' of set #{@set.id} — #{e.class}: #{e.message}")
+ nil
+ end
+
+ # The file the path names, or nil. realpath follows every symlink on the way and
+ # raises for a path that does not exist.
+ def file_inside_the_clone(path)
+ return nil if path.blank? || path.start_with?('/')
+
+ file = @root.join(path).realpath
+ return nil unless file.to_s.start_with?("#{@root}/")
+ return nil unless file.file?
+ return nil unless file.size.between?(1, MAX_BYTES)
+
+ file
+ rescue SystemCallError
+ nil
+ end
+
+ def upsert(asset, path, bytes, content_type)
+ sha = GitBlob.sha(bytes)
+ asset ||= DocumentationAsset.new(documentation_set: @set, organisation: @set.organisation, path: path)
+ return asset if asset.persisted? && asset.git_blob_sha == sha && asset.file.attached?
+
+ asset.assign_attributes(git_blob_sha: sha, content_type: content_type, byte_size: bytes.bytesize)
+ # identify: false, because the type was just read from the bytes: Rails would
+ # otherwise guess again, and from the file name too.
+ asset.file.attach(io: StringIO.new(bytes), filename: File.basename(path), content_type: content_type, identify: false)
+ asset.save!
+ existing[path] = asset
+ end
+
+ # The set's images as they are before this run, read once.
+ def existing
+ @existing ||= @set.documentation_assets.with_attached_file.index_by(&:path)
+ end
+
+ def kept_count
+ @addresses.values.count(&:present?)
+ end
+
+ def proxy_address(asset)
+ Rails.application.routes.url_helpers.organisation_file_download_path(
+ organisation_id: @set.organisation_id, kind: PROXY_KIND, id: asset.id
+ )
+ end
+ end
+end
diff --git a/app/services/documentation/git_blob.rb b/app/services/documentation/git_blob.rb
new file mode 100644
index 0000000..f511e1f
--- /dev/null
+++ b/app/services/documentation/git_blob.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+# The SHA git gives a file's content (`git hash-object`), computed in Ruby so that no
+# shell-out per file is needed. The sync uses it to tell whether a page or an image
+# changed since the last run.
+#
+# Entry point: sha
+module Documentation
+ module GitBlob
+ module_function
+
+ # The header counts BYTES, not characters.
+ def sha(content)
+ bytes = content.to_s.b
+ Digest::SHA1.hexdigest("blob #{bytes.bytesize}\0".b + bytes)
+ end
+ end
+end
diff --git a/app/services/documentation/markdown_renderer.rb b/app/services/documentation/markdown_renderer.rb
index 1c6e018..4f6dec9 100644
--- a/app/services/documentation/markdown_renderer.rb
+++ b/app/services/documentation/markdown_renderer.rb
@@ -10,9 +10,12 @@ module Documentation
# * knowledge links (lalabase://…) → the in-app note/document page, and
# the resolved target is collected so the sync job can index a Reference row
# (Slice 4; see KnowledgeLinkResolver for the tenant/project isolation)
- # * relative image sources → the repo's raw file URL (best
- # effort; private-repo images may not load — images are not guaranteed
- # in v1, a full authenticated asset server is a later slice)
+ # * images → served by the instance, or not shown:
+ # a relative image gets the address the asset resolver gives (the sync hands
+ # in Documentation::AssetCollector, which copies the file out of the clone);
+ # one that is not served shows as its alt text; one with a foreign address
+ # becomes a link. A page makes no browser load from the repository host or
+ # from anywhere else.
class MarkdownRenderer
ALLOWED_TAGS = %w[
p br strong em code pre ul ol li blockquote a img
@@ -28,9 +31,12 @@ module Documentation
# documentation_set: the set the page belongs to (for route + repo context).
# page_path: the page's path relative to the set's path_prefix.
- def initialize(documentation_set:, page_path:)
+ # asset_resolver: answers #address_for(path in the repository) with the address an
+ # image is served from, or nil. Without one no relative image is shown.
+ def initialize(documentation_set:, page_path:, asset_resolver: nil)
@documentation_set = documentation_set
@page_path = page_path
+ @asset_resolver = asset_resolver
end
# Backward-compatible string entry point (browsing preview, tests): the HTML only.
@@ -89,10 +95,7 @@ module Documentation
end
end
- fragment.css('img[src]').each do |node|
- rewritten = raw_asset_src(node['src'])
- node['src'] = rewritten if rewritten
- end
+ fragment.css('img').each { |node| rewrite_image(node) }
# Dedup: two links to the same note yield one Reference row (the DB unique index
# is the second line of defense). An UNRESOLVED lalabase:// link contributes
@@ -122,16 +125,73 @@ module Documentation
anchor.present? ? "#{path}##{anchor}" : path
end
- # A relative image source becomes the repo's raw file URL (host-specific URL
- # building lives on ProjectRepository). Absolute/data URIs are left untouched.
- def raw_asset_src(src)
- return nil if src.blank? || absolute_or_anchor?(src)
+ # An image is shown from the instance, or it is not shown as an image:
+ # * data: carries its bytes itself and stays;
+ # * a foreign address would make every reader's browser fetch it from there, so it
+ # becomes a link, a request only on a click;
+ # * a relative one gets the address the resolver gives, or shows as its alt text.
+ def rewrite_image(node)
+ src = node['src'].to_s.strip
+ return if src.start_with?('data:')
+
+ if src.start_with?('http://', 'https://', '//')
+ replace_image(node, foreign_image_link(node, src))
+ elsif (address = asset_address(src))
+ node['src'] = address
+ else
+ replace_image(node, image_text(node, src))
+ end
+ end
- resolved = resolve_relative(src)
- return nil if resolved.nil?
+ def asset_address(src)
+ path = repository_path(src)
+ path && @asset_resolver&.address_for(path)
+ end
+
+ # The file an image source names, as a path from the root of the REPOSITORY (an image
+ # often lives beside the documentation folder, not in it), or nil when the source
+ # names none or climbs out of the repository. A leading slash means the root of the
+ # repository, as it does on the repository host. Query string and fragment are not
+ # part of a file name; percent escapes are.
+ def repository_path(src)
+ file = src.split(/[?#]/, 2).first.to_s
+ return nil if file.blank? || file.match?(/\A[a-z][a-z0-9+.-]*:/i)
+
+ file = URI.decode_uri_component(file)
+ base = file.start_with?('/') ? Pathname.new('.') : page_directory_in_repository
+ candidate = (base + file.delete_prefix('/')).cleanpath.to_s
+ return nil if candidate.start_with?('..', '/') || candidate == '.'
+
+ candidate
+ rescue ArgumentError
+ nil
+ end
- repo_relative = File.join(@documentation_set.path_prefix.to_s.chomp('/'), resolved)
- @documentation_set.project_repository.raw_file_url(repo_relative)
+ def page_directory_in_repository
+ Pathname.new(@documentation_set.path_prefix.to_s) + Pathname.new(@page_path).dirname
+ end
+
+ def foreign_image_link(node, src)
+ Nokogiri::XML::Node.new('a', node.document).tap do |link|
+ link['href'] = src
+ link.content = node['alt'].presence || src
+ end
+ end
+
+ def image_text(node, src)
+ Nokogiri::XML::Node.new('em', node.document).tap do |text|
+ text.content = node['alt'].presence || File.basename(src.split(/[?#]/, 2).first.to_s)
+ end
+ end
+
+ # An image that already sits in a link (a badge that links to its build) gives its
+ # text to that link: a link inside a link is not HTML.
+ def replace_image(node, replacement)
+ if node.ancestors('a').any?
+ node.replace(Nokogiri::XML::Text.new(replacement.content, node.document))
+ else
+ node.replace(replacement)
+ end
end
def absolute_or_anchor?(value)
diff --git a/app/services/documentation/resync_all.rb b/app/services/documentation/resync_all.rb
new file mode 100644
index 0000000..f508399
--- /dev/null
+++ b/app/services/documentation/resync_all.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+# Enqueues a full sync of every documentation set of every organisation.
+#
+# For the day the RENDERER changes: the HTML of a page is a cache written at sync time,
+# and a poll skips every set whose repository did not move. Without this step a page
+# keeps what the older code wrote, until somebody commits to its repository. A MANUAL
+# sync always runs in full, so that is what this asks for.
+#
+# Run once after the deploy that needs it: `bin/rails documentation:resync_all`.
+module Documentation
+ class ResyncAll
+ def self.call = new.call
+
+ # @return [Integer] the number of sets a sync was enqueued for
+ def call
+ # Across all tenants on purpose: this is an operator's step, outside any request.
+ ids = ActsAsTenant.without_tenant { DocumentationSet.order(:created_at).pluck(:id) }
+ ids.each { |id| DocumentationSyncJob.perform_later(id, trigger: 'manual') }
+ ids.size
+ end
+ end
+end
diff --git a/app/views/organisations/documentation_sets/history.html.erb b/app/views/organisations/documentation_sets/history.html.erb
index a8ed8bc..0c3e1eb 100644
--- a/app/views/organisations/documentation_sets/history.html.erb
+++ b/app/views/organisations/documentation_sets/history.html.erb
@@ -56,6 +56,12 @@
<% if run.duration_seconds %>
&middot; <%= t('views.organisations.documentation.history.run_duration', seconds: run.duration_seconds) %>
<% end %>
+ <% if run.assets_synced.positive? %>
+ &middot; <%= t('views.organisations.documentation.history.run_assets', count: run.assets_synced) %>
+ <% end %>
+ <% if run.assets_skipped.positive? %>
+ &middot; <%= t('views.organisations.documentation.history.run_assets_skipped', count: run.assets_skipped) %>
+ <% end %>
</span>
<% if run.failed? %>
<span class="basis-full text-xs text-red-900">
diff --git a/config/locales/views/dokumente.de.yml b/config/locales/views/dokumente.de.yml
index fc41f9d..3ea9976 100644
--- a/config/locales/views/dokumente.de.yml
+++ b/config/locales/views/dokumente.de.yml
@@ -189,6 +189,12 @@ de:
runs_heading: Synchronisierungs-Läufe
runs_empty: Noch keine Synchronisierung gelaufen.
run_duration: "%{seconds} s"
+ run_assets:
+ one: 1 Bild
+ other: "%{count} Bilder"
+ run_assets_skipped:
+ one: 1 Bild nicht angezeigt
+ other: "%{count} Bilder nicht angezeigt"
trigger:
manual: Manuell
polling: Automatisch
diff --git a/config/locales/views/dokumente.en.yml b/config/locales/views/dokumente.en.yml
index 29c4bf4..e757da7 100644
--- a/config/locales/views/dokumente.en.yml
+++ b/config/locales/views/dokumente.en.yml
@@ -187,6 +187,12 @@ en:
runs_heading: Sync runs
runs_empty: No sync has run yet.
run_duration: "%{seconds} s"
+ run_assets:
+ one: 1 image
+ other: "%{count} images"
+ run_assets_skipped:
+ one: 1 image not shown
+ other: "%{count} images not shown"
trigger:
manual: Manual
polling: Automatic
diff --git a/db/migrate/20261101120000_create_documentation_assets.rb b/db/migrate/20261101120000_create_documentation_assets.rb
new file mode 100644
index 0000000..aaff59b
--- /dev/null
+++ b/db/migrate/20261101120000_create_documentation_assets.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+# The images of a synced documentation set, copied from the repository at sync time and
+# served by the instance. Until now a page showed them
+# from raw.githubusercontent.com: every reader contacted GitHub, and a private
+# repository's images did not show at all.
+#
+# One row per set and repository path. The file itself is an Active Storage attachment;
+# the row carries what decides whether it has to be uploaded again (git_blob_sha) and
+# what the type is according to its bytes (content_type), not according to its name.
+#
+# The id is what the cached page HTML points at, so the row is upserted, never replaced.
+#
+# The two counters on a sync run say how many images a run kept and how many it turned
+# down (too large, not an image, outside the repository, one too many).
+class CreateDocumentationAssets < ActiveRecord::Migration[8.1]
+ def change
+ create_table :documentation_assets, id: :uuid, default: -> { 'gen_random_uuid()' } do |t|
+ t.references :organisation, type: :uuid, null: false, foreign_key: true
+ t.references :documentation_set, type: :uuid, null: false, index: false, foreign_key: true
+ t.string :path, null: false
+ t.string :git_blob_sha, null: false
+ t.string :content_type, null: false
+ t.bigint :byte_size, null: false
+ t.timestamps
+ end
+
+ add_index :documentation_assets, %i[documentation_set_id path],
+ unique: true, name: 'idx_documentation_assets_set_path'
+
+ change_table :documentation_sync_runs, bulk: true do |t|
+ t.integer :assets_synced, default: 0, null: false
+ t.integer :assets_skipped, default: 0, null: false
+ end
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 25795ff..00440ce 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_11_01_100000) do
+ActiveRecord::Schema[8.1].define(version: 2026_11_01_120000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -517,6 +517,19 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_01_100000) do
t.index ["user_id"], name: "index_document_versions_on_user_id"
end
+ create_table "documentation_assets", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "organisation_id", null: false
+ t.uuid "documentation_set_id", null: false
+ t.string "path", null: false
+ t.string "git_blob_sha", null: false
+ t.string "content_type", null: false
+ t.bigint "byte_size", null: false
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ t.index ["documentation_set_id", "path"], name: "idx_documentation_assets_set_path", unique: true
+ t.index ["organisation_id"], name: "index_documentation_assets_on_organisation_id"
+ end
+
create_table "documentation_commits", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.uuid "organisation_id", null: false
t.uuid "documentation_set_id", null: false
@@ -596,6 +609,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_01_100000) do
t.uuid "triggered_by_user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
+ t.integer "assets_synced", default: 0, null: false
+ t.integer "assets_skipped", default: 0, null: false
t.index ["documentation_set_id", "created_at"], name: "idx_on_documentation_set_id_created_at_714010eb45"
t.index ["documentation_set_id"], name: "index_documentation_sync_runs_on_documentation_set_id"
t.index ["organisation_id"], name: "index_documentation_sync_runs_on_organisation_id"
@@ -2034,6 +2049,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_01_100000) do
add_foreign_key "dashboard_configurations", "projects"
add_foreign_key "dashboard_configurations", "users"
add_foreign_key "document_versions", "users"
+ add_foreign_key "documentation_assets", "documentation_sets"
+ add_foreign_key "documentation_assets", "organisations"
add_foreign_key "documentation_commits", "documentation_sets"
add_foreign_key "documentation_commits", "organisations"
add_foreign_key "documentation_pages", "documentation_sets"
diff --git a/lib/tasks/documentation.rake b/lib/tasks/documentation.rake
new file mode 100644
index 0000000..4edfbcd
--- /dev/null
+++ b/lib/tasks/documentation.rake
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+namespace :documentation do
+ desc 'Sync every documentation set again in full (after a change to how pages are rendered)'
+ task resync_all: :environment do
+ count = Documentation::ResyncAll.call
+ puts "Enqueued a full sync for #{count} documentation #{'set'.pluralize(count)}."
+ end
+end
diff --git a/spec/architecture/no_runtime_cdn_guard_spec.rb b/spec/architecture/no_runtime_cdn_guard_spec.rb
index 8e6ded3..a516da3 100644
--- a/spec/architecture/no_runtime_cdn_guard_spec.rb
+++ b/spec/architecture/no_runtime_cdn_guard_spec.rb
@@ -25,11 +25,10 @@ require 'open3'
#
# What this does NOT see:
# * an address built at run time ("#{HOST}/logo.png", a host in a constant);
-# * CONTENT. A synced documentation page shows its images from the repository host
-# (ProjectRepository#raw_file_url, raw.githubusercontent.com), and a Markdown image
-# with an absolute address stays as its author wrote it. `img-src` allows any https.
-# That is the content's address, not the application's, and it is a decision of its
-# own.
+# * CONTENT. What a user or a repository writes is not read here. Synced documentation
+# pages are held by their own spec (documentation_sync_job_spec, "names no repository
+# host and no address outside the instance"): their images come from the instance
+# since 2026-09-30. `img-src` still allows any https.
#
# A comment that quotes such a tag or address trips the guard as well. Describe it in
# words.
diff --git a/spec/factories/documentation_assets.rb b/spec/factories/documentation_assets.rb
new file mode 100644
index 0000000..8365af8
--- /dev/null
+++ b/spec/factories/documentation_assets.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+# == Schema Information
+#
+# Table name: documentation_assets
+#
+# id :uuid not null, primary key
+# byte_size :bigint not null
+# content_type :string not null
+# git_blob_sha :string not null
+# path :string not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# documentation_set_id :uuid not null
+# organisation_id :uuid not null
+#
+# Indexes
+#
+# idx_documentation_assets_set_path (documentation_set_id,path) UNIQUE
+# index_documentation_assets_on_organisation_id (organisation_id)
+#
+# Foreign Keys
+#
+# fk_rails_... (documentation_set_id => documentation_sets.id)
+# fk_rails_... (organisation_id => organisations.id)
+#
+FactoryBot.define do
+ factory :documentation_asset do
+ documentation_set
+ organisation { documentation_set.organisation }
+ sequence(:path) { |n| "docs/img/picture-#{n}.png" }
+ git_blob_sha { Digest::SHA1.hexdigest(path) }
+ content_type { 'image/png' }
+ byte_size { 70 }
+
+ after(:build) do |asset|
+ next if asset.file.attached?
+
+ asset.file.attach(
+ io: Rails.root.join('spec/fixtures/files/test_avatar.png').open,
+ filename: File.basename(asset.path.presence || 'image.png'),
+ content_type: 'image/png'
+ )
+ end
+ end
+end
diff --git a/spec/factories/documentation_sync_runs.rb b/spec/factories/documentation_sync_runs.rb
index fbd7792..92b0ace 100644
--- a/spec/factories/documentation_sync_runs.rb
+++ b/spec/factories/documentation_sync_runs.rb
@@ -5,6 +5,8 @@
# Table name: documentation_sync_runs
#
# id :uuid not null, primary key
+# assets_skipped :integer default(0), not null
+# assets_synced :integer default(0), not null
# commit_sha :string
# error_class :string
# error_message :text
diff --git a/spec/jobs/documentation_sync_job_spec.rb b/spec/jobs/documentation_sync_job_spec.rb
index 1d857bd..7e94ae6 100644
--- a/spec/jobs/documentation_sync_job_spec.rb
+++ b/spec/jobs/documentation_sync_job_spec.rb
@@ -13,6 +13,8 @@ RSpec.describe DocumentationSyncJob, type: :job do
let(:project) { create(:project, organisation: organisation) }
let(:set) { create(:documentation_set, project: project, path_prefix: 'docs/') }
+ let(:png) { Rails.root.join('spec/fixtures/files/test_avatar.png').binread }
+
before { ActsAsTenant.current_tenant = organisation }
after { @clone_dirs&.each { |d| FileUtils.remove_entry(d, true) } }
@@ -27,7 +29,7 @@ RSpec.describe DocumentationSyncJob, type: :job do
files.each do |rel, content|
full = File.join(dir, rel)
FileUtils.mkdir_p(File.dirname(full))
- File.write(full, content)
+ File.binwrite(full, content)
end
cloner = instance_double(Lalabase::Indexer::GitCloner,
cloned_commit: commit, remote_head_commit: remote_head)
@@ -169,30 +171,155 @@ RSpec.describe DocumentationSyncJob, type: :job do
end
describe 'link and image rewriting' do
- it 'rewrites internal .md links and relative image sources' do
+ it 'rewrites internal .md links and shows a relative image from the instance' do
stub_cloner_with(files: {
'docs/intro.md' => 'See [setup](guide/setup.md) and ![logo](img/logo.png)',
- 'docs/guide/setup.md' => '# Setup'
+ 'docs/guide/setup.md' => '# Setup',
+ 'docs/img/logo.png' => png
})
described_class.perform_now(set.id)
html = set.documentation_pages.find_by(path: 'intro.md').rendered_html
+ asset = set.documentation_assets.find_by!(path: 'docs/img/logo.png')
expect(html).to include('/documentation')
expect(html).to include('page=guide%2Fsetup.md').or include('page=guide/setup.md')
- expect(html).to include('raw.githubusercontent.com')
+ expect(html).to include(%(<img src="/org/#{organisation.id}/files/documentation_asset/#{asset.id}" alt="logo">))
+ end
+ end
+
+ # The images of a page are copied out of the clone and served by the instance.
+ # Until then a page showed them from raw.githubusercontent.com: every reader contacted
+ # GitHub, and the images of a private repository did not show at all.
+ describe 'images' do
+ let(:page_with_image) { "# A\n\n![Aufbau](img/aufbau.png)" }
+
+ def html_of(path)
+ set.documentation_pages.find_by!(path: path).rendered_html
+ end
+
+ def sync_with(files)
+ stub_cloner_with(files: files)
+ described_class.perform_now(set.id)
+ end
+
+ it 'names no repository host and no address outside the instance, whatever the page asks for' do
+ sync_with('docs/a.md' => '![in](img/aufbau.png) ![missing](img/nowhere.png) ![badge](https://img.shields.io/x.svg)',
+ 'docs/img/aufbau.png' => png)
+
+ html = html_of('a.md')
+ expect(html).not_to include('raw.githubusercontent.com')
+ expect(html.scan(/<img[^>]*src="([^"]*)"/).flatten).to all(start_with("/org/#{organisation.id}/files/documentation_asset/"))
+ expect(html).to include('<em>missing</em>', '<a href="https://img.shields.io/x.svg">badge</a>')
+ end
+
+ it 'counts what it kept and what it turned down on the run' do
+ sync_with('docs/a.md' => '![in](img/aufbau.png) ![missing](img/nowhere.png) ![fake](img/fake.png)',
+ 'docs/img/aufbau.png' => png, 'docs/img/fake.png' => '<html></html>')
+
+ expect(set.documentation_sync_runs.recent.first).to have_attributes(status: 'ready', assets_synced: 1, assets_skipped: 2)
+ end
+
+ it 'takes an image that lives beside the documentation folder' do
+ sync_with('docs/a.md' => '![logo](../assets/logo.png)', 'assets/logo.png' => png)
+
+ expect(set.documentation_assets.pluck(:path)).to eq(['assets/logo.png'])
+ expect(html_of('a.md')).to include('<img')
+ end
+
+ # The page did not change, its image appeared. The HTML has to follow, and the
+ # embeddings, which are made from the markdown, have nothing to do.
+ it 'shows an image that arrives later, without the page having changed' do
+ sync_with('docs/a.md' => page_with_image)
+ expect(html_of('a.md')).to include('<em>Aufbau</em>')
+ RSpec::Mocks.space.proxy_for(EmbeddingProcessingJob).reset
+ allow(EmbeddingProcessingJob).to receive(:perform_later)
+
+ sync_with('docs/a.md' => page_with_image, 'docs/img/aufbau.png' => png)
+
+ expect(html_of('a.md')).to include('<img')
+ expect(html_of('a.md')).not_to include('<em>Aufbau</em>')
+ expect(EmbeddingProcessingJob).not_to have_received(:perform_later)
+ end
+
+ it 'takes an image away, file and all, when it leaves the repository' do
+ sync_with('docs/a.md' => page_with_image, 'docs/img/aufbau.png' => png)
+ blob_id = set.documentation_assets.first.file.blob.id
+
+ adapter_was = ActiveJob::Base.queue_adapter
+ ActiveJob::Base.queue_adapter = :test
+ perform_enqueued_jobs { sync_with('docs/a.md' => page_with_image) }
+ ActiveJob::Base.queue_adapter = adapter_was
+
+ expect(set.documentation_assets).to be_empty
+ expect(ActiveStorage::Blob.find_by(id: blob_id)).to be_nil
+ expect(html_of('a.md')).to include('<em>Aufbau</em>')
+ expect(html_of('a.md')).not_to include('<img')
+ end
+
+ it 'takes an image away when no page shows it any more, although the file is still there' do
+ sync_with('docs/a.md' => page_with_image, 'docs/img/aufbau.png' => png)
+
+ sync_with('docs/a.md' => '# A', 'docs/img/aufbau.png' => png)
+
+ expect(set.documentation_assets).to be_empty
+ end
+
+ it 'keeps the address and takes the new bytes when only the image changed' do
+ sync_with('docs/a.md' => page_with_image, 'docs/img/aufbau.png' => png)
+ html = html_of('a.md')
+ # A written page gets a new updated_at; this one is pushed into the past to tell.
+ written_at = 2.days.ago.change(usec: 0)
+ set.documentation_pages.find_by!(path: 'a.md').update_columns(updated_at: written_at)
+ other = Rails.root.join('spec/fixtures/files/avatar_quadrants.png').binread
+
+ sync_with('docs/a.md' => page_with_image, 'docs/img/aufbau.png' => other)
+
+ expect(set.documentation_assets.first.file.download).to eq(other)
+ expect(html_of('a.md')).to eq(html)
+ expect(set.documentation_pages.find_by!(path: 'a.md').updated_at).to eq(written_at)
+ end
+
+ it 'leaves the images of a run that failed where they are' do
+ sync_with('docs/a.md' => page_with_image, 'docs/img/aufbau.png' => png)
+ stub_cloner_raising(Lalabase::Indexer::GitCloner::Error.new('network down'))
+
+ described_class.perform_now(set.id)
+
+ expect(set.reload.sync_status).to eq('failed')
+ expect(set.documentation_assets.count).to eq(1)
end
end
describe 'incremental change detection' do
- it 'does not re-render a page whose content is unchanged' do
+ # Rendered on every run, written only when something differs: the HTML of a page
+ # depends on more than its own markdown (an image arrives, the renderer changes).
+ it 'does not write a page that is unchanged in every respect' do
+ stub_cloner_with(files: { 'docs/a.md' => '# A' })
+ described_class.perform_now(set.id)
+ # A written page gets a new updated_at; this one is pushed into the past to tell.
+ written_at = 2.days.ago.change(usec: 0)
+ set.documentation_pages.find_by!(path: 'a.md').update_columns(updated_at: written_at)
+
stub_cloner_with(files: { 'docs/a.md' => '# A' })
described_class.perform_now(set.id)
- # Second identical sync must skip rendering (the whole point of git_blob_sha).
+ expect(set.documentation_pages.find_by!(path: 'a.md').updated_at).to eq(written_at)
+ end
+
+ # The promise at skip_unchanged_poll?: a manual sync is the repair tool after a code
+ # change. It was not, as long as an unchanged blob SHA skipped the render.
+ it 'renders a page again whose markdown did not change, and heals a stale cache' do
+ stub_cloner_with(files: { 'docs/a.md' => '# A' })
+ described_class.perform_now(set.id)
+ page = set.documentation_pages.find_by!(path: 'a.md')
+ fresh = page.rendered_html
+ page.update_columns(rendered_html: '<p>what an older renderer wrote</p>')
+
stub_cloner_with(files: { 'docs/a.md' => '# A' })
- expect(Documentation::MarkdownRenderer).not_to receive(:new)
described_class.perform_now(set.id)
+
+ expect(page.reload.rendered_html).to eq(fresh)
end
it 're-renders and updates a page whose content changed' do
diff --git a/spec/models/documentation_asset_spec.rb b/spec/models/documentation_asset_spec.rb
new file mode 100644
index 0000000..87298f7
--- /dev/null
+++ b/spec/models/documentation_asset_spec.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+# == Schema Information
+#
+# Table name: documentation_assets
+#
+# id :uuid not null, primary key
+# byte_size :bigint not null
+# content_type :string not null
+# git_blob_sha :string not null
+# path :string not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# documentation_set_id :uuid not null
+# organisation_id :uuid not null
+#
+# Indexes
+#
+# idx_documentation_assets_set_path (documentation_set_id,path) UNIQUE
+# index_documentation_assets_on_organisation_id (organisation_id)
+#
+# Foreign Keys
+#
+# fk_rails_... (documentation_set_id => documentation_sets.id)
+# fk_rails_... (organisation_id => organisations.id)
+#
+require 'rails_helper'
+
+# What: DocumentationAsset, one image of a documentation set, copied from the repository
+# at sync time.
+# Type: Model spec.
+# Why: The row is what the cached page HTML points at, by id. It has to be unique per
+# set and path (or an upsert doubles it), it has to stay inside its tenant, and
+# when it goes its file has to go with it: a documentation set that is
+# disconnected must not leave a private repository's images in the storage.
+RSpec.describe DocumentationAsset, type: :model do
+ let(:organisation) { create(:organisation) }
+ let(:project) { create(:project, organisation: organisation) }
+ let(:set) { create(:documentation_set, project: project) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ # The purge of a file is a job; the test adapter lets a block run it.
+ around do |example|
+ adapter_was = ActiveJob::Base.queue_adapter
+ ActiveJob::Base.queue_adapter = :test
+ example.run
+ ActiveJob::Base.queue_adapter = adapter_was
+ end
+
+ it 'is valid from its factory, with a file' do
+ asset = create(:documentation_asset, documentation_set: set)
+
+ expect(asset).to be_persisted
+ expect(asset.file).to be_attached
+ expect(asset.organisation).to eq(organisation)
+ end
+
+ it 'exists once per set and path' do
+ create(:documentation_asset, documentation_set: set, path: 'docs/img/a.png')
+ twin = build(:documentation_asset, documentation_set: set, path: 'docs/img/a.png')
+ elsewhere = build(:documentation_asset, documentation_set: create(:documentation_set, project: project), path: 'docs/img/a.png')
+
+ expect(twin).not_to be_valid
+ expect(elsewhere).to be_valid
+ end
+
+ it 'needs a path, a blob SHA and a content type' do
+ asset = build(:documentation_asset, documentation_set: set, path: nil, git_blob_sha: nil, content_type: nil)
+
+ expect(asset).not_to be_valid
+ expect(asset.errors.attribute_names).to include(:path, :git_blob_sha, :content_type)
+ end
+
+ it 'is invisible from another organisation' do
+ asset = create(:documentation_asset, documentation_set: set)
+
+ ActsAsTenant.with_tenant(create(:organisation)) do
+ expect(described_class.find_by(id: asset.id)).to be_nil
+ end
+ end
+
+ it 'takes its file along when it is destroyed' do
+ asset = create(:documentation_asset, documentation_set: set)
+ blob_id = asset.file.blob.id
+
+ perform_enqueued_jobs { asset.destroy! }
+
+ expect(ActiveStorage::Blob.find_by(id: blob_id)).to be_nil
+ end
+
+ it 'goes, file and all, when its set is destroyed' do
+ asset = create(:documentation_asset, documentation_set: set)
+ blob_id = asset.file.blob.id
+
+ perform_enqueued_jobs { set.destroy! }
+
+ expect(described_class.find_by(id: asset.id)).to be_nil
+ expect(ActiveStorage::Blob.find_by(id: blob_id)).to be_nil
+ end
+
+ # The images of a customer's repository are the customer's data. Their deletion belongs
+ # in the deletion register like that of any other file (AttachmentDeletionRecorder
+ # works with a list of exclusions, so a new carrier is recorded unless it says otherwise).
+ it 'leaves an entry in the deletion register' do
+ asset = create(:documentation_asset, documentation_set: set, path: 'docs/img/aufbau.png')
+
+ expect { perform_enqueued_jobs { asset.destroy! } }.to change(AttachmentDeletionRecord, :count).by(1)
+ expect(AttachmentDeletionRecord.order(:created_at).last).to have_attributes(organisation_id: organisation.id, filename: 'aufbau.png')
+ end
+end
diff --git a/spec/models/documentation_sync_run_spec.rb b/spec/models/documentation_sync_run_spec.rb
index 2e954f9..51bb18d 100644
--- a/spec/models/documentation_sync_run_spec.rb
+++ b/spec/models/documentation_sync_run_spec.rb
@@ -5,6 +5,8 @@
# Table name: documentation_sync_runs
#
# id :uuid not null, primary key
+# assets_skipped :integer default(0), not null
+# assets_synced :integer default(0), not null
# commit_sha :string
# error_class :string
# error_message :text
diff --git a/spec/models/project_repository_spec.rb b/spec/models/project_repository_spec.rb
index 1c455bc..d7fd753 100644
--- a/spec/models/project_repository_spec.rb
+++ b/spec/models/project_repository_spec.rb
@@ -416,19 +416,4 @@ RSpec.describe ProjectRepository, type: :model do
expect(repo.reload.access_token).to eq(token)
end
end
-
- describe '#raw_file_url' do
- it 'builds the raw content URL from full_name, default_branch and the given path' do
- repo = build(:project_repository, full_name: 'acme/docs', default_branch: 'develop')
-
- expect(repo.raw_file_url('docs/img/logo.png'))
- .to eq('https://raw.githubusercontent.com/acme/docs/develop/docs/img/logo.png')
- end
-
- it 'never embeds the access token (raw URLs are shipped to browsers)' do
- repo = build(:project_repository, access_token: 'ghp_secret_token')
-
- expect(repo.raw_file_url('a.png')).not_to include('ghp_secret_token')
- end
- end
end
diff --git a/spec/requests/organisations/documentation_spec.rb b/spec/requests/organisations/documentation_spec.rb
index 1e37ac8..ea22f92 100644
--- a/spec/requests/organisations/documentation_spec.rb
+++ b/spec/requests/organisations/documentation_spec.rb
@@ -316,6 +316,31 @@ RSpec.describe 'Organisations::Documentation', type: :request do
expect(response.body).to include(I18n.t('views.organisations.documentation.history.trigger.polling'))
end
+ # The run says how many images it kept and how many it turned down: an image that is
+ # too large or not an image shows as text on the page, and this is where a reader of
+ # the logbook learns why.
+ it 'says how many images a run kept and how many it did not show' do
+ create(:documentation_sync_run, documentation_set: documentation_set, status: 'ready',
+ trigger: 'manual', assets_synced: 12, assets_skipped: 2)
+ sign_in_with_role(reader_role)
+
+ get history_path
+
+ expect(response.body).to include(I18n.t('views.organisations.documentation.history.run_assets', count: 12))
+ expect(response.body).to include(I18n.t('views.organisations.documentation.history.run_assets_skipped', count: 2))
+ end
+
+ it 'says nothing about images for a run that met none' do
+ create(:documentation_sync_run, documentation_set: documentation_set, status: 'ready', trigger: 'manual')
+ sign_in_with_role(reader_role)
+
+ get history_path
+
+ expect(response).to have_http_status(:ok)
+ expect(response.body).not_to include(I18n.t('views.organisations.documentation.history.run_assets', count: 0))
+ expect(response.body).not_to include(I18n.t('views.organisations.documentation.history.run_assets_skipped', count: 0))
+ end
+
it 'blocks a user without documentation access' do
sign_in_with_role(no_access_role)
diff --git a/spec/requests/organisations/file_downloads_documentation_asset_spec.rb b/spec/requests/organisations/file_downloads_documentation_asset_spec.rb
new file mode 100644
index 0000000..b8b87ba
--- /dev/null
+++ b/spec/requests/organisations/file_downloads_documentation_asset_spec.rb
@@ -0,0 +1,141 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: The images of a synced documentation page come from the authorized file proxy,
+# behind the same right as the page.
+# Type: Request spec, in the CI guard list.
+# Why: Until this change such an image came from raw.githubusercontent.com: every reader
+# contacted GitHub, and a private repository's images did not show at all. Now the
+# instance holds a copy, and a copy of a PRIVATE repository's file must not be more
+# readable than the documentation it belongs to. The address sits in cached page
+# HTML, so it is an id without a signature: everything rests on these checks.
+RSpec.describe 'Organisations::FileDownloads documentation assets', :ci_guard, type: :request do
+ let(:organisation) { create(:organisation) }
+ let(:project) { ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) } }
+ let(:set) { ActsAsTenant.with_tenant(organisation) { create(:documentation_set, project: project) } }
+ let(:asset) { ActsAsTenant.with_tenant(organisation) { create(:documentation_asset, documentation_set: set) } }
+
+ let(:standard_role) do
+ create(:role, organisation: organisation, title: "Member #{SecureRandom.hex(4)}", is_default: true)
+ end
+
+ let(:member) do
+ create(:user).tap do |user|
+ ActsAsTenant.with_tenant(organisation) do
+ create(:membership, user: user, organisation: organisation, role: standard_role, active: true)
+ end
+ end
+ end
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ def download(id: asset.id, headers: {})
+ get organisation_file_download_path(organisation_id: organisation.id, kind: 'documentation_asset', id: id), headers: headers
+ end
+
+ def grant(access, on: project)
+ create(:project_permission, user: member, project: on, documentation_access: access)
+ end
+
+ it 'serves the image to a reader of the documentation, as the type it is' do
+ grant('read_only')
+ sign_in member
+
+ download
+
+ expect(response).to have_http_status(:ok)
+ expect(response.media_type).to eq('image/png')
+ expect(response.body.b).to eq(Rails.root.join('spec/fixtures/files/test_avatar.png').binread)
+ end
+
+ it 'answers 404 to a project member without the documentation area' do
+ create(:project_permission, user: member, project: project, tickets_access: 'read_write', documentation_access: 'no_access')
+ sign_in member
+
+ download
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'answers 404 for an asset of another project, to a reader of this one' do
+ grant('read_only')
+ other_project = ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) }
+ other_set = ActsAsTenant.with_tenant(organisation) { create(:documentation_set, project: other_project) }
+ foreign = ActsAsTenant.with_tenant(organisation) { create(:documentation_asset, documentation_set: other_set) }
+ sign_in member
+
+ download(id: foreign.id)
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'answers 404 for an asset of another organisation' do
+ grant('read_only')
+ other_org = create(:organisation)
+ foreign = ActsAsTenant.with_tenant(other_org) do
+ create(:documentation_asset, documentation_set: create(:documentation_set, project: create(:project, organisation: other_org)))
+ end
+ sign_in member
+
+ download(id: foreign.id)
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'sends nobody the bytes without a login' do
+ download
+
+ expect(response).to have_http_status(:redirect)
+ expect(response.body).not_to include('PNG')
+ end
+
+ # One image is one request through Rails, and the general throttle counts every one
+ # (rack_attack, requests/ip). The address never changes, so the browser may keep the
+ # file for a short while and asks with the ETag after that.
+ describe 'caching' do
+ before do
+ grant('read_only')
+ sign_in member
+ end
+
+ it 'lets the browser keep the image privately and names its version' do
+ download
+
+ expect(response.headers['Cache-Control']).to include('private', 'max-age=')
+ expect(response.headers['Cache-Control']).not_to include('public')
+ expect(response.headers['ETag']).to be_present
+ end
+
+ it 'answers 304 without a body to a browser that holds this version' do
+ download
+ etag = response.headers['ETag']
+
+ download(headers: { 'If-None-Match' => etag })
+
+ expect(response).to have_http_status(:not_modified)
+ expect(response.body).to be_empty
+ end
+
+ it 'sends the file again once it has changed' do
+ download
+ etag = response.headers['ETag']
+ asset.update!(git_blob_sha: Digest::SHA1.hexdigest('another version'))
+
+ download(headers: { 'If-None-Match' => etag })
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'checks the right before it checks the version' do
+ download
+ etag = response.headers['ETag']
+ ProjectPermission.where(user: member, project: project).update_all(documentation_access: 0)
+
+ download(headers: { 'If-None-Match' => etag })
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/spec/services/documentation/asset_collector_spec.rb b/spec/services/documentation/asset_collector_spec.rb
new file mode 100644
index 0000000..c1d6eb0
--- /dev/null
+++ b/spec/services/documentation/asset_collector_spec.rb
@@ -0,0 +1,244 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: Documentation::AssetCollector, which copies the images a documentation set's
+# pages refer to out of the cloned repository.
+# Type: Service spec, on a real directory.
+# Why: The repository is not ours. A page may name any path, a file may be a symlink to
+# anywhere on the worker's disk, and a file's name says nothing about its content.
+# What the collector accepts is served from OUR origin to everybody who may read
+# the documentation, so every refusal here is a security boundary, and each one is
+# pinned with the file that would cross it.
+RSpec.describe Documentation::AssetCollector do
+ let(:organisation) { create(:organisation) }
+ let(:project) { create(:project, organisation: organisation) }
+ let(:set) { create(:documentation_set, project: project, path_prefix: 'docs/') }
+ let(:repo) { Pathname.new(Dir.mktmpdir('asset-collector-spec-')) }
+ let(:outside) { Pathname.new(Dir.mktmpdir('asset-collector-outside-')) }
+ let(:png) { Rails.root.join('spec/fixtures/files/test_avatar.png').binread }
+ let(:collector) { described_class.new(documentation_set: set, repo_path: repo) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+
+ after do
+ ActsAsTenant.current_tenant = nil
+ FileUtils.remove_entry(repo, true)
+ FileUtils.remove_entry(outside, true)
+ end
+
+ def write_file(relative, bytes, root: repo)
+ full = root.join(relative)
+ FileUtils.mkdir_p(full.dirname)
+ File.binwrite(full, bytes)
+ full
+ end
+
+ def asset_for(path)
+ set.documentation_assets.find_by(path: path)
+ end
+
+ describe 'an image of the repository' do
+ before { write_file('docs/img/logo.png', png) }
+
+ it 'is stored once, with the type of its bytes, and answered with the address of the file proxy' do
+ address = collector.address_for('docs/img/logo.png')
+ asset = asset_for('docs/img/logo.png')
+
+ expect(asset).to have_attributes(content_type: 'image/png', byte_size: png.bytesize, organisation: organisation)
+ expect(asset.file.download).to eq(png)
+ expect(address).to eq("/org/#{organisation.id}/files/documentation_asset/#{asset.id}")
+ expect(collector).to have_attributes(synced: 1, skipped: 0)
+ end
+
+ it 'carries the blob SHA git itself would give the file' do
+ collector.address_for('docs/img/logo.png')
+
+ expected = Digest::SHA1.hexdigest("blob #{png.bytesize}\0".b + png)
+ expect(asset_for('docs/img/logo.png').git_blob_sha).to eq(expected)
+ end
+
+ it 'is one row for two pages that show it' do
+ first = collector.address_for('docs/img/logo.png')
+ second = collector.address_for('docs/img/logo.png')
+
+ expect(second).to eq(first)
+ expect(set.documentation_assets.count).to eq(1)
+ expect(collector.synced).to eq(1)
+ end
+
+ it 'keeps its row, its address and its upload on the next run when it did not change' do
+ address = collector.address_for('docs/img/logo.png')
+ blob_id = asset_for('docs/img/logo.png').file.blob.id
+
+ again = described_class.new(documentation_set: set, repo_path: repo)
+
+ expect(again.address_for('docs/img/logo.png')).to eq(address)
+ expect(asset_for('docs/img/logo.png').file.blob.id).to eq(blob_id)
+ end
+
+ it 'keeps its row and its address and takes the new bytes when it changed' do
+ address = collector.address_for('docs/img/logo.png')
+ other = Rails.root.join('spec/fixtures/files/avatar_quadrants.png').binread
+ write_file('docs/img/logo.png', other)
+
+ again = described_class.new(documentation_set: set, repo_path: repo)
+
+ expect(again.address_for('docs/img/logo.png')).to eq(address)
+ expect(asset_for('docs/img/logo.png').file.download).to eq(other)
+ expect(asset_for('docs/img/logo.png').byte_size).to eq(other.bytesize)
+ end
+
+ it 'may lie outside the documentation folder, as long as it is inside the repository' do
+ write_file('assets/shared.png', png)
+
+ expect(collector.address_for('assets/shared.png')).to be_present
+ end
+ end
+
+ describe 'what is refused' do
+ def refused(path)
+ expect(collector.address_for(path)).to be_nil
+ expect(set.documentation_assets.where(path: path)).to be_empty
+ end
+
+ it 'a file that is not there' do
+ refused('docs/img/missing.png')
+ expect(collector).to have_attributes(synced: 0, skipped: 1)
+ end
+
+ it 'a directory' do
+ FileUtils.mkdir_p(repo.join('docs/img.png'))
+
+ refused('docs/img.png')
+ end
+
+ it 'a page of HTML that calls itself .png' do
+ write_file('docs/img/fake.png', '<html><script>alert(1)</script></html>')
+
+ refused('docs/img/fake.png')
+ end
+
+ # Bytes that say nothing about their type: a guess from the NAME would call them a PNG.
+ it 'bytes of no known type that call themselves .png' do
+ write_file('docs/img/words.png', 'just some words, and not a single pixel')
+
+ refused('docs/img/words.png')
+ end
+
+ it 'an SVG, whatever it is called' do
+ svg = Rails.root.join('spec/fixtures/files/avatar_bomb.svg').binread
+ write_file('docs/img/diagram.svg', svg)
+ write_file('docs/img/diagram.png', svg)
+
+ refused('docs/img/diagram.svg')
+ refused('docs/img/diagram.png')
+ end
+
+ it 'a file one byte over the limit, and not one at the limit' do
+ stub_const("#{described_class}::MAX_BYTES", png.bytesize)
+ write_file('docs/img/exact.png', png)
+ write_file('docs/img/over.png', "#{png}\0")
+
+ expect(collector.address_for('docs/img/exact.png')).to be_present
+ refused('docs/img/over.png')
+ end
+
+ it 'an empty file' do
+ write_file('docs/img/empty.png', '')
+
+ refused('docs/img/empty.png')
+ end
+
+ it 'the image after the last one the set may hold' do
+ stub_const("#{described_class}::MAX_ASSETS", 2)
+ %w[a b c].each { |name| write_file("docs/img/#{name}.png", png) }
+
+ expect(collector.address_for('docs/img/a.png')).to be_present
+ expect(collector.address_for('docs/img/b.png')).to be_present
+ refused('docs/img/c.png')
+ # An image already counted is not refused for being asked about again.
+ expect(collector.address_for('docs/img/a.png')).to be_present
+ expect(collector).to have_attributes(synced: 2, skipped: 1)
+ end
+
+ it 'a path that climbs out of the repository' do
+ write_file('secret.png', png, root: outside)
+ relative = outside.join('secret.png').relative_path_from(repo).to_s
+
+ expect(relative).to start_with('..')
+ refused(relative)
+ end
+
+ it 'an absolute path' do
+ write_file('secret.png', png, root: outside)
+
+ refused(outside.join('secret.png').to_s)
+ end
+
+ it 'a symlink to a file outside the repository, although it looks like an image inside it' do
+ write_file('secret.png', png, root: outside)
+ FileUtils.mkdir_p(repo.join('docs/img'))
+ File.symlink(outside.join('secret.png'), repo.join('docs/img/innocent.png'))
+
+ refused('docs/img/innocent.png')
+ end
+
+ it 'a file reached through a symlinked directory that leaves the repository' do
+ write_file('pictures/secret.png', png, root: outside)
+ FileUtils.mkdir_p(repo.join('docs'))
+ File.symlink(outside.join('pictures'), repo.join('docs/img'))
+
+ refused('docs/img/secret.png')
+ end
+
+ it 'nothing at all through a symlink that stays inside the repository' do
+ write_file('assets/real.png', png)
+ FileUtils.mkdir_p(repo.join('docs/img'))
+ File.symlink(repo.join('assets/real.png'), repo.join('docs/img/alias.png'))
+
+ expect(collector.address_for('docs/img/alias.png')).to be_present
+ end
+ end
+
+ describe 'a failing storage' do
+ it 'costs the image, not the run' do
+ write_file('docs/img/logo.png', png)
+ allow_any_instance_of(DocumentationAsset).to receive(:save!).and_raise(ActiveStorage::IntegrityError)
+
+ expect(collector.address_for('docs/img/logo.png')).to be_nil
+ expect(collector).to have_attributes(synced: 0, skipped: 1)
+ end
+ end
+
+ describe '#finish' do
+ it 'destroys the images of the set that no page asked about in this run, file and all' do
+ write_file('docs/img/kept.png', png)
+ write_file('docs/img/dropped.png', png)
+ first = described_class.new(documentation_set: set, repo_path: repo)
+ first.address_for('docs/img/kept.png')
+ first.address_for('docs/img/dropped.png')
+ first.finish
+ dropped_blob = asset_for('docs/img/dropped.png').file.blob.id
+
+ second = described_class.new(documentation_set: set, repo_path: repo)
+ second.address_for('docs/img/kept.png')
+ adapter_was = ActiveJob::Base.queue_adapter
+ ActiveJob::Base.queue_adapter = :test
+ perform_enqueued_jobs { second.finish }
+ ActiveJob::Base.queue_adapter = adapter_was
+
+ expect(set.documentation_assets.pluck(:path)).to eq(['docs/img/kept.png'])
+ expect(ActiveStorage::Blob.find_by(id: dropped_blob)).to be_nil
+ end
+
+ it 'leaves the images of another set alone' do
+ other_set = create(:documentation_set, project: project)
+ other = create(:documentation_asset, documentation_set: other_set)
+
+ collector.finish
+
+ expect(DocumentationAsset.find_by(id: other.id)).to be_present
+ end
+ end
+end
diff --git a/spec/services/documentation/markdown_renderer_spec.rb b/spec/services/documentation/markdown_renderer_spec.rb
index c2768ee..b1821c7 100644
--- a/spec/services/documentation/markdown_renderer_spec.rb
+++ b/spec/services/documentation/markdown_renderer_spec.rb
@@ -88,21 +88,95 @@ RSpec.describe Documentation::MarkdownRenderer do
end
end
- describe 'relative images' do
- it 'rewrites a relative image source to the raw repo URL' do
- html = render('![logo](img/logo.png)')
- expect(html).to include('src="https://raw.githubusercontent.com/acme/handbook/main/.lalabase/doku/guide/img/logo.png"')
+ # The images of a page come from the instance. The
+ # renderer asks a resolver for the address of every relative image; the sync hands it
+ # the AssetCollector. What is not served shows as text, never as an address elsewhere.
+ describe 'images' do
+ let(:resolver) do
+ Class.new do
+ attr_reader :asked
+
+ def initialize(answers) = (@answers = answers) && (@asked = [])
+
+ def address_for(path)
+ @asked << path
+ @answers[path]
+ end
+ end
+ end
+
+ def render_with(answers, markdown, page_path: 'guide/intro.md')
+ asked = resolver.new(answers)
+ html = described_class.new(documentation_set: set, page_path: page_path, asset_resolver: asked).render(markdown)
+ [html, asked.asked]
+ end
+
+ it 'shows a relative image from the address the resolver gives, asked by its path in the repository' do
+ html, asked = render_with({ '.lalabase/doku/guide/img/logo.png' => '/org/1/files/documentation_asset/7' }, '![Logo](img/logo.png)')
+
+ expect(asked).to eq(['.lalabase/doku/guide/img/logo.png'])
+ expect(html).to include('<img src="/org/1/files/documentation_asset/7" alt="Logo">')
+ end
+
+ it 'reaches an image outside the documentation folder, as long as it is inside the repository' do
+ _, asked = render_with({}, '![x](../../../assets/shared.png)')
+
+ expect(asked).to eq(['assets/shared.png'])
+ end
+
+ it 'reads a path that starts with a slash from the root of the repository, as the repository host does' do
+ _, asked = render_with({}, '![x](/assets/shared.png)')
+
+ expect(asked).to eq(['assets/shared.png'])
+ end
+
+ it 'asks for the file, not for its query string, its fragment or its escapes' do
+ _, asked = render_with({}, '![x](img/my%20logo.png?raw=true#top)')
+
+ expect(asked).to eq(['.lalabase/doku/guide/img/my logo.png'])
+ end
+
+ it 'does not ask about a path that climbs out of the repository' do
+ html, asked = render_with({}, '![leak](../../../../secret.png)')
+
+ expect(asked).to be_empty
+ expect(html).to include('<em>leak</em>')
+ expect(html).not_to include('<img')
+ end
+
+ it 'shows the alt text for an image that is not served, and the file name when there is none' do
+ html, = render_with({}, "![Aufbau](img/aufbau.png)
+
+![](img/ohne-text.svg)")
+
+ expect(html).to include('<em>Aufbau</em>', '<em>ohne-text.svg</em>')
+ expect(html).not_to include('<img')
end
- it 'leaves absolute image sources untouched' do
- html = render('![x](https://cdn.example.com/x.png)')
- expect(html).to include('src="https://cdn.example.com/x.png"')
+ it 'shows the alt text without a resolver, and names no repository host' do
+ html = render('![Logo](img/logo.png)')
+
+ expect(html).to include('<em>Logo</em>')
+ expect(html).not_to include('<img', 'raw.githubusercontent.com', repository.access_token)
end
- it 'never embeds the repository access token in the raw URL' do
- html = render('![logo](img/logo.png)')
- expect(html).to include('raw.githubusercontent.com') # sanity: it did rewrite
- expect(html).not_to include(repository.access_token)
+ # An image with an address of its own would make the reader's browser fetch it from
+ # there on every visit. It becomes a link: no request without a click.
+ it 'turns an image with a foreign address into a link with its alt text' do
+ html = render("![Build](https://img.shields.io/badge/build-passing.svg)
+
+![](//cdn.example.com/x.png)")
+
+ expect(html).to include('<a href="https://img.shields.io/badge/build-passing.svg">Build</a>')
+ expect(html).to include('<a href="//cdn.example.com/x.png">//cdn.example.com/x.png</a>')
+ expect(html).not_to include('<img')
+ end
+
+ it 'keeps an image inside a link as a link, without nesting one in the other' do
+ html = render('[![Build](https://img.shields.io/badge.svg)](https://ci.example.com/run/1)')
+
+ expect(html).to include('<a href="https://ci.example.com/run/1">Build</a>')
+ expect(html).not_to include('<img', 'img.shields.io')
end
end
@@ -163,8 +237,8 @@ RSpec.describe Documentation::MarkdownRenderer do
expect(result.html).to include("/notes/#{note.id}")
expect(result.html).to include("/documents/#{document.id}")
# The other rewrite branches still fire (knowledge branch does not shadow them).
- expect(result.html).to include('/documentation') # internal .md link
- expect(result.html).to include('raw.githubusercontent.com') # relative image
+ expect(result.html).to include('/documentation') # internal .md link
+ expect(result.html).to include('<em>pic</em>') # relative image: no resolver here, so its alt text
end
it 'does NOT resolve a note from another project (no cross-project link), no reference' do
@@ -232,9 +306,10 @@ RSpec.describe Documentation::MarkdownRenderer do
expect(html).not_to include('/documentation')
end
- it 'does not turn an image escaping the set into a repo URL' do
- html = render('![leak](../../../secret.png)')
- expect(html).not_to include('raw.githubusercontent.com')
+ it 'does not turn an image escaping the repository into an image at all' do
+ html = render('![leak](../../../../secret.png)')
+ expect(html).not_to include('<img', 'secret.png')
+ expect(html).to include('<em>leak</em>')
end
end
end
diff --git a/spec/services/documentation/resync_all_spec.rb b/spec/services/documentation/resync_all_spec.rb
new file mode 100644
index 0000000..afe3e8d
--- /dev/null
+++ b/spec/services/documentation/resync_all_spec.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: Documentation::ResyncAll, behind `bin/rails documentation:resync_all`.
+# Type: Service spec.
+# Why: A change to the renderer reaches a page only when its set is synced again, and a
+# poll skips every set whose repository did not move (DocumentationSyncJob
+# #skip_unchanged_poll?). After the deploy that moved the images of a page from the
+# repository host to the instance, every page cached before it still named the old
+# address. This is the one step that reaches them all: a MANUAL sync, which always
+# runs in full, for every set of every organisation.
+RSpec.describe Documentation::ResyncAll do
+ around do |example|
+ adapter_was = ActiveJob::Base.queue_adapter
+ ActiveJob::Base.queue_adapter = :test
+ example.run
+ ActiveJob::Base.queue_adapter = adapter_was
+ end
+
+ def set_in(organisation)
+ ActsAsTenant.with_tenant(organisation) do
+ create(:documentation_set, project: create(:project, organisation: organisation))
+ end
+ end
+
+ it 'enqueues a manual sync for every set of every organisation, and says how many' do
+ first = set_in(create(:organisation))
+ second = set_in(create(:organisation))
+
+ count = nil
+ expect { count = described_class.call }
+ .to have_enqueued_job(DocumentationSyncJob).with(first.id, trigger: 'manual')
+ .and have_enqueued_job(DocumentationSyncJob).with(second.id, trigger: 'manual')
+
+ expect(count).to eq(2)
+ end
+
+ it 'does nothing, and says so, where there is no set' do
+ expect { expect(described_class.call).to eq(0) }.not_to have_enqueued_job(DocumentationSyncJob)
+ end
+end