Feature Request: Sharing Sections
Hi @perber, I'd like to help with this one. The issue has no description yet, so I want to check what you have in mind before writing code. I read #1258 and your comments there.
Problem Today there is no way to give someone without an account access to a single page or section. The options are an account (read access to everything), public mode (everything, for everyone), or exporting and attaching files. As you said in #1258, the permalink dialog doesn't help here. It's built for internal links, and #1484 reworded it accordingly.
Two possible readings of "Sharing Sections"
A) Public sections. A root section becomes anonymously readable under its normal URL. This is what you mentioned in #1258. It is permanent and discoverable. It needs the tree, breadcrumbs, listings, search, tags and properties to respect visibility, which is the cost you described in #1258.
B) Share links. An editor creates an unlisted, revocable link (/s/
Rough behavior for B
Creating, listing and revoking links is editor/admin only. Tokens are 256-bit random, with optional expiry. The link follows the page ID, so rename and move don't break it. A shared page shows only title, content and in-scope navigation. It shows no author info, no ancestors above the shared root, and no backlinks, tags or search. Links to pages outside the share render as plain text. Every invalid, expired, revoked or deleted link returns the same 404. It sets Referrer-Policy: no-referrer and noindex, and redacts tokens from access logs. It stays off by default behind an experimental flag, like API keys. Storage is a single share-links.json using the existing settings store, with backup and restore covered in the same PR. I wrote this up as a design doc with the security considerations, alternatives and a split into small PRs. I will share it here, after I understood your idea.
Questions
Do you want A, B, or both? I'd start with B, because it doesn't force visibility changes through the tree and search, and A could build on it later. If B: is a page plus subtree OK for v1, or only a single page? Is it fine for tokens to be stored in plaintext in share-links.json, so the link can be shown again? (Anyone who can read that file can already read root/.) If you prefer A, I'll rework the proposal around that. Happy to wait for your direction before writing any code.
Hi @lboehm,
Thanks for taking this part. I would agree with B, but as you mentioned, the user shouldn't have the possibility to search or do other things. It should be restricted to reading only. Besides that, we should have an easy way to remove shared links, and they should be listed somewhere. Maybe in the settings for now? Later, we could introduce a housekeeping area for this kind of purpose.
What do you think?
Should we use the SQLite for that? What do you think?
Good questions regarding sharing the subtree.
My question is: What would a user expect here? Or what would you personally expect?
At the moment, I don't have a use case for it.
Additionally we should look how it works with the proxy header auth.
I think we should start with the test cases here first, because the search should be restricted and not exposed, and many more things maybe. (Defining the Acceptance Criteria). The API needs to be restricted as well to not allow running a search.
Hi @perber ,
Thanks, that helps. Here's where I landed on each point:
Read-only, no search. Agreed. The share viewer gets its own tiny API (/api/shared/:token/...) with four routes: page, in-scope tree, assets, meta. Search, tags, properties, links, lookup and everything else are simply not reachable with a share token. To prove it, I'd write a route-enumeration test first. It iterates over every route registered in gin, calls it with a valid share token (as Bearer, cookie and query parameter) and asserts that only those four routes answer 2xx and everything else answers 401/404. Routes added later are covered automatically.
Listing and removing links. Settings → "Share links" for admins: page, scope, creator, created/expires, status, last access, views, revoke. Editors also see and revoke the links of a page in its share dialog. A housekeeping area can later be a different view of the same data. Admins also get an instance-wide switch ("Allow share links") in the same Settings area. It can be pinned via env var like public mode. When off, all share routes answer the generic 404 (existing links are kept and work again when re-enabled), and the share dialog offers no creation. I'd use this single setting as the experimental flag for the first release as well, default off.
SQLite. Yes, and I'd go one step further and use it to record access statistics: views per day and last-accessed timestamp, which a housekeeping area could later use ("unused for 90 days"). No IPs or user agents are stored. Counters are kept in memory and flushed in batches, so an anonymous GET doesn't cause a synchronous write. It follows the api_keys.db pattern (suspend/Replace for live restore, included in snapshots).
Subtree. My use case: sharing everything about one customer with that customer, i.e. one link to a section including its subpages. So the share dialog has an explicit "Include subpages" option (off by default). When enabled, the user must confirm a warning: pages created under it or moved into it later become visible automatically. The server enforces that confirmation too. Settings shows how many pages a subtree link currently exposes. If you don't want this in v1, single-page is a clean subset, so it's easy to split.
Proxy header auth. I checked InjectRemoteUser, and it needs explicit handling: it runs globally, so when a trusted proxy asserts a user LeafWiki doesn't know, it returns 401 on every route, which would lock out a recipient who exists at the IdP but has no wiki account. With AutoCreate it would even provision an account just because someone opened a share link. So I'd exempt the share routes from both the proxy-header and API-key middlewares, since a share request never has a user. That's covered by acceptance criteria. The front proxy (oauth2-proxy, nginx auth_request) also has to let /s/, /api/shared/ and the SPA assets through unauthenticated, which I'd document in docs/install.
Acceptance criteria first. Agreed. I wrote them up as Given/When/Then (see below), grouped into isolation, scope, lifecycle, statistics, auth modes (proxy header, API key, public mode, disable-auth), token/log privacy, backup/restore and one e2e path: [link to doc]. If you're fine with the direction, I'd turn them into failing/skipped tests as the first PR, before any implementation, so we agree on the behavior in code.
Open points for you: (1) are the AC complete from your side, especially around what must never be exposed? (2) Is v1 with the subtree option OK for you? (3) Plaintext token storage so the dialog can show the link again, or hash-only and show once? (4) Is a runtime admin switch that can be pinned by env var (same split as public mode) the right shape for the global opt-out, with default off in the first release?
Acceptance criteria
These are written first and become the test specification (the maintainer asked for this in #1252). Notation: Given / When / Then. "Token" means a valid share token; "anonymous" means no session, no API key, no proxy header. Each criterion maps to at least one automated test (unit U, HTTP H, e2e E).
I. Isolation: read-only, nothing else reachable
| ID | Criterion | Test |
|---|---|---|
| AC-I1 | Given the fully wired router, when a test enumerates every registered route (engine.Routes()) and calls each with a valid share token (as Authorization: Bearer, as cookie, as ?token= / ?share=) and no session, then every route outside the four share routes answers 401 or 404, and the four share routes are the only ones that answer 2xx. A newly added route is covered automatically. |
H |
| AC-I2 | When a share token is used against /api/search, /api/search/status, /api/tags*, /api/properties*, /api/pages/:id/links, /api/pages/by-path, /api/pages/by-title, /api/pages/lookup, /api/pages/permalink/:id, /api/tree, /api/pages/:id, /api/pages/:id/assets, static /assets/*, then the result is 401 (no search, no tree, no lookup, no listing). |
H |
| AC-I3 | When a share token is used with any non-GET method on any route, then it is rejected; no share route accepts a body. | H |
| AC-I4 | The shared page response contains only the allow-listed fields (title, rendered/raw content, updatedAt, and in-scope navigation). It contains no creatorId, lastAuthorId, creator, lastAuthor, metadata, no tags, properties, backlinks, revision info, and no path or ancestors above the share root. A reflection/JSON-key test fails if a field is added to the DTO without updating the allow-list. |
H |
| AC-I5 | The shared viewer UI shows no search box, no global navigation, no edit/share/favorite/login controls, and no user menu. | E |
| AC-I6 | When shared content links to a page outside the scope, then it is rendered as plain text and the response does not reveal whether the target exists. | U/E |
II. Scope
| ID | Criterion | Test |
|---|---|---|
| AC-S1 | Given a single-page link for page A, when requesting page B, a child of A, or an asset of B, then 404. |
H |
| AC-S2 | Given a subtree link for A, when requesting A, a child, or a grandchild (and their assets), then 200; requesting a sibling or the parent of A: 404. |
H |
| AC-S3 | Given a subtree link for A, when a page is created under A later or moved into A, then it becomes reachable through the link; when moved out of A, it no longer is. | U/H |
| AC-S4 | Given a link for A, when A is renamed or moved, then the same link still works (keyed on page ID). | H |
| AC-S5 | Given a link for A, when A is deleted, then the link answers the same 404 as an unknown token, and is shown as "dangling" in the admin list until pruned or revoked. |
U/H |
| AC-S6 | Asset requests with .., encoded separators, absolute paths or another page's ID never read outside the in-scope page's asset directory. The scope check happens before any filesystem access. |
H |
| AC-S7 | Asset requests do not count as views; only the document request does. | U |
III. Link lifecycle and management
| ID | Criterion | Test |
|---|---|---|
| AC-L1 | Given an editor or admin, when creating a link, then 201 with a 256-bit random token; a viewer-role user or anonymous caller gets 403 / 401; CSRF is enforced. |
H |
| AC-L2 | When includeChildren: true is sent without confirmSubtree: true, then 400 and no link is created. The UI shows the warning ("pages created under or moved to this page later become visible automatically") and requires confirmation before sending confirmSubtree. |
H/E |
| AC-L3 | When a link is revoked, then the very next request with its token answers 404 (no caching, no grace period). |
H |
| AC-L4 | Given an expiry, when now >= expiresAt, then 404; one second before, 200. |
U |
| AC-L5 | Given unknown, malformed, expired, revoked and dangling tokens, then all answer an identical status and body (no oracle). | H |
| AC-L6 | An admin can see all links in Settings (page title/path, scope, creator, created, expires, status, last accessed, total views, number of currently exposed pages for subtree links) and revoke any of them. An editor sees and revokes links in the share dialog of a page. | E |
| AC-L7 | Failed token attempts are rate limited per client; a valid token from another client is unaffected. | H |
IV. Access statistics
| ID | Criterion | Test |
|---|---|---|
| AC-T1 | When the shared document is loaded, then views for today increases by one and last_accessed_at is updated, after at most one flush interval. |
U |
| AC-T2 | Counters are flushed on graceful shutdown; a failed flush is logged and never fails or slows the request. | U |
| AC-T3 | No IP address, user agent or other visitor data is persisted. | U/review |
| AC-T4 | Revoking a link removes its statistics. | U |
V. Authentication modes
| ID | Criterion | Test |
|---|---|---|
| AC-A1 | Given proxy header auth is on and the trusted proxy sends an identifier unknown to LeafWiki, when opening a share link, then 200 (not 401). |
H |
| AC-A2 | Given proxy header auth with AutoCreate on, when opening a share link with an asserted identifier, then no account is created. |
H |
| AC-A3 | Given a valid API key (Bearer lw_...) is sent on share routes, then it is ignored (a share request never has a user). An invalid API key on a share route does not turn it into a 401. |
H |
| AC-A4 | Share links work with public mode off, with public mode on, and with --disable-auth. |
H |
| AC-A5 | A logged-in user's session cookie on a share route is ignored; the response is identical to the anonymous one. | H |
| AC-A6 | docs/install documents which paths a front proxy must let through unauthenticated (/s/*, /api/shared/*, /static, /branding, /favicon.svg, /custom.css) with an oauth2-proxy and an nginx example. |
review |
VI. Privacy of the token and response hardening
| ID | Criterion | Test |
|---|---|---|
| AC-P1 | The request log line never contains the token (/s/<token>, /api/shared/<token> are redacted). |
H |
| AC-P2 | Prometheus labels never contain the token (route template only). | H |
| AC-P3 | Share responses carry Referrer-Policy: no-referrer, X-Robots-Tag: noindex, nofollow and Cache-Control: private, no-store (JSON). External links in shared content carry rel="noreferrer noopener". |
H/E |
| AC-P4 | Markdown in shared content is sanitized exactly as in the authenticated viewer (script/HTML injection test). | U/E |
VII. Backup, restore, flag
| ID | Criterion | Test |
|---|---|---|
| AC-B1 | A snapshot taken with links and statistics, restored into a fresh instance, yields working links (same tokens) and the same statistics. | H |
| AC-B2 | Restoring a snapshot without share_links.db results in an empty link set, not an error. |
H |
| AC-B3 | During a live restore, share routes answer 503 (store suspended) rather than racing the file swap, mirroring api_keys.db. |
H |
| AC-B4 | With --enable-share-links off, management and share routes are not registered (404) and the UI shows no share options. |
H/E |
VIII. End-to-end happy path
| ID | Criterion | Test |
|---|---|---|
| AC-E1 | An editor creates a subtree link for a customer section (with confirmation), opens it in a logged-out browser context, reads the section and a child, cannot reach a page outside it, cannot search; the admin sees the link and its view count in Settings, revokes it, and the link then shows the generic not-found page. | E |
Thanks, this looks like a solid direction.
Before implementation, I would like to make one architectural aspect explicit. LeafWiki is already large enough that visibility-related concerns such as sharing, public sections and drafts could easily start leaking into TreeService, search, pages, links and other core components.
I would prefer to keep those core services focused on the internal wiki state and introduce a small scoped read boundary for visibility-sensitive views instead.
I drafted the following ADR to make the intended dependency direction, extension points and performance considerations concrete:
ADR: Scoped Read Boundary for Visibility-Sensitive Views
Context
LeafWiki currently keeps features relatively well separated. Core components such as the tree, pages, search, links and assets represent the internal state of the wiki.
Upcoming features introduce a new concern: the same underlying wiki may need to be exposed differently depending on the current view.
Examples include:
- share links
- public sections
- draft / preview views
- potentially other visibility-related features later
A straightforward implementation would add visibility and permission parameters to existing services:
treeService.GetTree(ctx, shareToken, includeDrafts, publicOnly)
or spread checks throughout the code:
if shared { ... }
if public { ... }
if draft { ... }
This would make visibility a cross-cutting concern across TreeService, search, pages, links, assets and other subsystems.
We want to avoid that.
Decision
Introduce a small scoped read boundary for views that expose only part of the internal wiki.
Core services remain unaware of sharing, public visibility and draft/preview semantics.
Conceptually:
share link / public section / preview
|
v
ReadScope / View
|
v
Scoped Readers
|
v
existing core services
/ stores / indexes
The scoped read layer decides what may be observed.
The existing core continues to describe what exists.
Dependency direction
Desired:
ShareHandler
|
v
ScopedTreeReader
|
+----> TreeService
|
+----> NodeStore
Not:
TreeService
├── share permissions
├── public visibility
├── draft visibility
└── user-specific access rules
Core packages must not depend on sharing/public/preview packages.
Consumer-owned interfaces
We do not need to introduce interfaces for all existing LeafWiki services.
The new boundary should define only the small interfaces it needs.
For example:
// package shared
type TreeReader interface {
Tree(
ctx context.Context,
scope ReadScope,
) (*SharedTree, error)
}
The existing TreeService can remain a concrete type.
An implementation of the new reader can adapt existing services:
type scopedTreeReader struct {
treeService *tree.TreeService
nodeStore *tree.NodeStore
}
func NewScopedTreeReader(
treeService *tree.TreeService,
nodeStore *tree.NodeStore,
) *scopedTreeReader {
return &scopedTreeReader{
treeService: treeService,
nodeStore: nodeStore,
}
}
This keeps the refactoring local to the new feature boundary.
Read scope
For section sharing, a minimal scope might look like:
type ReadScope struct {
RootID string
IncludeDescendants bool
}
A resolved share produces a scope:
scope := ReadScope{
RootID: share.RootPageID,
IncludeDescendants: share.IncludeChildren,
}
The share token itself does not need to propagate into tree, page or asset services.
token
|
v
ShareResolver
|
v
ReadScope
|
v
Scoped Readers
This distinction is important: the token is an external capability; the internal read layer works with the already resolved scope.
Example: shared tree
A simple first implementation could use the existing tree:
func (r *scopedTreeReader) Tree(
ctx context.Context,
scope ReadScope,
) (*SharedTree, error) {
tree, err := r.treeService.GetTree(ctx)
if err != nil {
return nil, err
}
subtree, err := projectSubtree(
tree,
scope.RootID,
scope.IncludeDescendants,
)
if err != nil {
return nil, err
}
return toSharedTree(subtree), nil
}
This is intentionally only an example.
The important part is that the filtering semantics live behind TreeReader, not inside TreeService.
The share handler only sees the scoped reader:
type ShareHandler struct {
shares ShareResolver
tree TreeReader
}
func (h *ShareHandler) GetTree(c *gin.Context) {
share, err := h.shares.Resolve(
c.Request.Context(),
c.Param("token"),
)
if err != nil {
c.Status(http.StatusNotFound)
return
}
result, err := h.tree.Tree(
c.Request.Context(),
ReadScope{
RootID: share.RootPageID,
IncludeDescendants: share.IncludeChildren,
},
)
if err != nil {
c.Status(http.StatusNotFound)
return
}
c.JSON(http.StatusOK, result)
}
The normal application remains unchanged:
tree, err := treeService.GetTree(ctx)
Sharing gets a separate read path:
tree, err := scopedTreeReader.Tree(ctx, scope)
Performance
The scoped read abstraction must not require loading the complete wiki and filtering it in memory.
That may be acceptable as an initial implementation, but the abstraction must allow scope restrictions to be pushed down into the storage or index layer.
For example, this:
tree, _ := treeService.GetTree(ctx)
return projectSubtree(tree, scope)
may later become:
nodes, err := nodeStore.GetSubtree(
ctx,
scope.RootID,
)
return projectSharedTree(nodes, scope)
without changing the handler or public scoped-reader API.
The principle is:
Visibility semantics live high.
Execution may happen low.
A scope can therefore be translated into efficient storage/index queries where appropriate.
This becomes particularly important for search.
Filtering global search results after the query would produce incorrect pagination/ranking:
results := search.Search(query)
return filterToScope(results, scope)
A future scoped search implementation should instead be able to push the scope into the index query:
search.Search(ctx, query, compiledScope)
This does not require search support for share links in #1252. It only keeps the extension point open for future public-section functionality.
DTO boundary
Scoped/public APIs must not reuse normal API response DTOs directly.
For example:
type SharedPage struct {
ID string `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
UpdatedAt time.Time `json:"updatedAt"`
}
Projection is explicit:
func toSharedPage(page *page.Page) SharedPage {
return SharedPage{
ID: page.ID,
Title: page.Title,
Content: page.Content,
UpdatedAt: page.UpdatedAt,
}
}
This makes the public representation an allow-list.
Adding fields to an internal page or tree DTO must not automatically expose them through a shared view.
The same rule applies to:
- pages
- trees
- meta responses
- assets/navigation metadata
Assets and links
Scope checks must happen before accessing resources.
Conceptually:
func (r *scopedAssetReader) Asset(
ctx context.Context,
scope ReadScope,
pageID string,
name string,
) ([]byte, error) {
if !r.scope.Contains(ctx, scope, pageID) {
return nil, ErrNotFound
}
return r.assets.Read(ctx, pageID, name)
}
Likewise, link resolution in a shared view must not reveal out-of-scope targets.
An internal link such as:
[[Internal Roadmap]]
should only become a navigable link when the target belongs to the current scope.
Otherwise it is rendered without exposing target ID, path or existence information.
Wiring
The scoped readers are wired only into the relevant feature.
Example composition:
treeService := tree.NewTreeService(...)
nodeStore := tree.NewNodeStore(...)
pageService := page.NewService(...)
assetStore := asset.NewStore(...)
// Existing application paths remain unchanged.
wikiHandler := wiki.NewHandler(
treeService,
pageService,
// ...
)
// New scoped read path.
sharedTreeReader := shared.NewTreeReader(
treeService,
nodeStore,
)
sharedPageReader := shared.NewPageReader(
pageService,
nodeStore,
)
sharedAssetReader := shared.NewAssetReader(
assetStore,
nodeStore,
)
shareHandler := shared.NewHandler(
shareStore,
sharedTreeReader,
sharedPageReader,
sharedAssetReader,
)
No existing service needs a shareToken, isPublic, or includeDrafts parameter.
Extension points
Sharing is the first use case for this boundary, but it should not be designed specifically around share tokens.
A future public section could resolve into the same type of scope:
Share token
|
v
ShareResolver --------\
\
> ReadScope -> Scoped Readers
/
Public route ---------/
|
v
PublicSectionResolver
Draft/preview views may reuse parts of the same mechanism where appropriate.
For example:
authenticated editor
|
v
PreviewView
|
v
visibility policy
|
v
Scoped Readers / Projection
This does not mean that all these features need to be generalized now.
Sharing should define only the minimum abstraction required today.
If later use cases fit naturally, they can reuse and extend it.
Architectural invariants
The following rules should hold:
TreeService, page services, search and other core services do not depend on share/public/preview concepts.- Share tokens are resolved at the feature boundary and are not propagated through the core.
- Scoped/public responses use dedicated allow-listed DTOs.
- Access decisions happen before resources such as assets are read.
- Scoped readers may push restrictions into stores/indexes for performance.
- The scoped layer may depend on core services/stores. Core must not depend on the scoped/view layer.
- Existing normal LeafWiki behavior must not require passing a visibility context everywhere.
These dependency rules should be covered by architecture or integration tests where practical.
Acceptance criteria additions for #1252
In addition to the existing acceptance criteria:
Shared response DTOs
page, tree and meta use dedicated allow-listed response DTOs.
They never expose:
- ancestors above the shared root
- out-of-scope page IDs
- out-of-scope paths
- internal metadata not explicitly part of the share API
A test should fail when fields are added to these DTOs without explicitly updating the allow-list expectation.
Architectural boundary
Share routes must obtain page/tree/asset data through the scoped read boundary.
Normal API DTOs must not be returned directly from /api/shared/....
Where practical, architecture tests should ensure that core packages do not import the sharing/view layer.
Consequences
Positive
TreeServicestays focused on tree/domain behavior.- Sharing does not introduce permission parameters throughout the existing codebase.
- Public sections and preview/draft features have a defined extension point.
- Visibility rules are easier to test centrally.
- Public DTOs have a clear security boundary.
- Performance optimizations can be pushed into stores/indexes without changing HTTP handlers.
- Existing LeafWiki features require minimal changes.
Negative
- There is an additional read/projection layer.
- Some functionality may initially look duplicated between normal and scoped readers.
- Efficient implementations may occasionally need lower-level store access instead of going through an existing service.
- Care is required not to turn
ReadScopeinto a large generic permission framework.
These trade-offs are intentional.
Non-goals
This ADR does not introduce:
- a generic ACL system
- row-level permissions throughout LeafWiki
- a generic policy engine
- share-aware search
- user-specific permissions in
TreeService - interfaces for every existing service
- a requirement to refactor existing normal API paths
The immediate goal is narrower:
Establish a stable boundary for visibility-sensitive read views before sharing/public/draft concerns start spreading through the existing core.
Suggested work packages
To keep the implementation reviewable, I would split this into several small PRs rather than implementing the complete sharing flow at once.
One additional constraint is that the HTTP API is currently being documented and cleaned up as part of #1661.
That work introduces the generated OpenAPI/Swagger surface, shared API error types and route-coverage checks. The sharing implementation should align with those conventions instead of introducing a parallel API style that we would have to refactor again afterwards.
Where possible, the sharing PRs should therefore build on the API primitives established by #1661.
PR 1 — Scoped read boundary
Introduce the architectural extension point only.
Scope:
- add
ReadScope - add the small consumer-side reader interfaces needed by sharing
- add scoped tree/page projection primitives
- add dedicated shared DTOs
- add architecture tests for dependency direction where practical
No public routes yet.
Goal:
Establish the boundary without changing existing LeafWiki behavior.
PR 2 — Share model and token resolution
Introduce share persistence and lifecycle.
Scope:
- share entity/store
- token generation and hashing
- create / revoke / resolve
- backup and restore support
- tests for token privacy and lifecycle
No content exposure yet.
Goal:
A token can safely resolve to a
ReadScope.
PR 3 — Shared page read
Add the smallest useful public read path.
Scope:
/api/shared/:token/page/...- shared page DTO
- scope validation
- out-of-scope access returns not-found semantics
- tests for DTO allow-list and scope isolation
- OpenAPI annotations / generated API documentation according to #1661
- use the shared API error conventions established by #1661
Goal:
Prove the scoped read boundary with one concrete resource.
PR 4 — Shared tree
Add tree/subtree exposure.
Scope:
/api/shared/:token/tree- root-only vs subtree behavior
- no ancestors above the shared root
- dedicated tree DTO
- tests for moved/new descendants and scope changes
- API documentation following the #1661 conventions
Performance can initially use the simplest correct implementation, as long as the reader abstraction allows later query pushdown.
Goal:
Add hierarchical navigation without making
TreeServiceshare-aware.
PR 5 — Assets and link safety
Handle secondary resources and metadata leaks.
Scope:
- scoped asset reads
- scope check before filesystem access
- shared link resolution
- prevent out-of-scope target IDs/paths from leaking
- tests for private link targets and asset access
Goal:
Close the less obvious information-leak paths.
PR 6 — Share API isolation and auth integration
Wire the complete public API boundary.
Scope:
- dedicated
/api/shared/:token/...router - bypass normal authentication/proxy-user provisioning where appropriate
- integrate the share routes into the route-coverage mechanism from #1661
- verify that only explicitly supported share routes are reachable
- meta endpoint if required
- make sure the generated OpenAPI specification reflects the intended public surface
Goal:
Make the externally reachable surface explicit and auditable.
PR 7 — UI and subtree sharing
Add user-facing share management.
Scope:
- create/revoke share UI
- root-only / subtree option
- explicit warning that subtree shares are dynamic
- public share page/navigation
- error/expired/revoked states
Goal:
Deliver the end-user feature after the backend/security boundary is already stable.
Optional follow-up — Performance
Only after profiling real usage:
- subtree query pushdown
- caching by share/scope + content revision
- optimized scoped asset lookup
- future scoped search/index filtering
This should not be required to land the initial architecture unless current measurements show a real problem.
The sequencing would roughly be:
#1661 API foundations
↓
scoped read boundary
↓
token/scope
↓
single resource
↓
tree
↓
secondary leak paths
↓
API isolation
↓
UI
Each PR should leave the repository in a valid state and should ideally be reviewable without needing to understand the entire final feature.
Let me know. What you are thinking and if this way is working for you?
Thanks, this works for me, and I like the direction. Keeping visibility out of the core services is a better answer than my Contains() checks in the handlers, because the scope is applied where the data is read and can't be forgotten in a single endpoint. A few remarks:
1. Boundary and first PR. I'm fine with the ADR as you describe it: consumer-owned interfaces, ReadScope{RootID, IncludeDescendants}, token resolved at the feature boundary, dedicated allow-list DTOs, scope check before any asset access, and an architecture test that core packages don't import sharing. One concern: PR 1 as a standalone, route-less PR has no consumer yet, and an interface without a consumer is easy to cut wrongly. Could PR 1 stay small (ReadScope plus the reader for a single page and its adapter) and be reviewed together with, or directly before, the single-page read in PR 3? The tree and asset readers can then follow the same pattern in PR 4/5. The TreeReader.Tree(ctx, scope) shape stays as you proposed.
2. Token hashing. I saw "token generation and hashing" in PR 2. I had planned plaintext so the dialog could show the link again, but I'm fine with hashing: it follows the API-key pattern and it's one less thing in a leaked backup. The consequence is UX: the link is shown once at creation (copy button, clear hint), and the Settings list can't show it again. If someone loses a link, they revoke it and create a new one. I'll reflect that in the dialog and the acceptance criteria.
3. Things from my acceptance criteria that aren't in the PR plan yet. None of these conflict with it, I just want to make sure they land somewhere:
- the admin switch "Allow share links" (default off, pinnable via env var like public mode, share routes answer the generic 404 when off). It could go into PR 6 or PR 7.
- access statistics (daily views, last accessed, no IPs or user agents, batched flush) in PR 2.
- the admin overview in Settings listing all links, with revoke and, for subtree links, the number of currently exposed pages. It could go into PR 7.
- token redaction in request logs,
Referrer-Policy/noindex/no-storeheaders and per-client rate limiting for failed tokens. It could go into PR 6, or PR 3 if you prefer the first route to be hardened from the start. - the front-proxy documentation (
/s/*,/api/shared/*and the SPA assets must bypass auth in oauth2-proxy and nginxauth_request).
4. Auth bypass earlier. In PR 6 the proxy-header/API-key exemption comes last. I'd suggest doing it with the first shared route (PR 3), because otherwise the first route is tested in a setup that doesn't match how it will run: a proxy asserting a user unknown to LeafWiki gets 401 on a share link, and AutoCreate would create an account just because someone opened a link.
5. Route coverage. My route-enumeration test (calls every registered route with a share token as Bearer, cookie and query parameter, and expects only the shared routes to answer 2xx) overlaps with the route-coverage checks you mention for #1661. I'd rather build on what #1661 introduces than add a second mechanism, so I'd do it after that lands. Is there an ETA, or should I start with PR 1/2, which don't depend on it?
6. Open points from my last comment. I'd still like your view on:
- SQLite for the share store (statistics and a later housekeeping area need queryable data),
- the subtree option with a confirmation in v1 (
IncludeDescendantsin yourReadScopesuggests you're fine with it, but I want to be sure - I personally would prefer to include the subtree feature), - whether the acceptance criteria miss anything that must never be exposed.
7. Who does what. Seven PRs is a lot, so happy to split. I can take PR 1 and 2 first (scope boundary with the single-page reader, share model and store, lifecycle tests, backup/restore) and then continue in order, unless you want to take some of them. I'll update the design document with the ADR structure, the PR sequence and the points above and share it, so the acceptance criteria and the plan are in one place.
Hi @lboehm ,
I will take a look tomorrow evening.
Hi @lboehm,
Thanks for the detailed feedback, and sorry for the delayed response.
I think we're aligned on the overall architecture and direction.
Regarding your points:
-
Scoped read boundary: I agree with your suggestion. Let's keep the first PR small and introduce the abstractions alongside their first concrete use case. There's no need to introduce interfaces before we actually need them.
-
Token hashing: I prefer storing hashed tokens, similar to API keys. Showing the link only once during creation is an acceptable trade-off for better security.
-
Missing acceptance criteria: Agreed. The admin switch, statistics, management UI, token protection, rate limiting, and proxy documentation should remain part of the implementation plan. We can assign them to the appropriate PR or at a later point. I guess implementing sharing alone is already a huge topic.
-
Authentication: Good point. Proxy-header authentication and API-key handling should be addressed with the first public share endpoint rather than later.
-
Route coverage / #1661: I wouldn't block the initial work on #1661. We can start with the scoped read boundary and persistence layer, then integrate the route-coverage mechanisms once the API foundations are available. ETA not clear yet. But should land soon.
-
Open questions:
- SQLite: Yes, I think SQLite is the right choice here.
- Subtree sharing: I'm fine with supporting it in v1, provided it is explicitly enabled and the user understands that newly added or moved pages will also become accessible.
- Acceptance criteria: The current criteria look comprehensive to me. We should pay particular attention to preventing information leaks through assets, internal links, metadata, and authentication middleware.
-
Work distribution: I'm happy for you to start with PR 1 and PR 2 as proposed. Let's review these first before proceeding with the remaining implementation.
Thanks again for taking this on.
Thanks @perber ! I've opened the first PRs:
#1728 -> scoped read boundary (ReadScope + single-page reader, ADR-0015). Small and route-less as discussed; its first production caller will be the shared-page route. #1727 -> a behaviour-preserving refactor that registers state SQLite stores once for snapshots and restore (ADR-0016). Without it share_links.db would have been the fourth copy of the same wiring in restore/snapshot. I split it out so it can be reviewed on its own. #1729 (draft, stacked on the refactor) -> share link store and service: hashed tokens shown once, create/revoke/resolve, backup/restore, behind --enable-share-links.
ADR-0014 is left free because of the open OIDC branch. Listing links and statistics come with their first callers (share dialog / first route). The leak points you mentioned (assets, internal links, auth middleware) are noted for the route PRs.
Hi @perber,
thanks for fixing the Trivy failures and for merging #1727. I've rebased the other two PRs onto main, so both include your fix:
#1728 (scoped read boundary): rebased, all checks green. #1729 (share link store): moved from draft to ready for review. Now that the refactor is merged it only contains its own two commits.
Once you've reviewed those, I'd like to continue with PR 3, the shared page read, as you outlined it:
GET /api/shared/:token/page/...resolves the token to aReadScopeand returns the allow-listed page DTO.- Out-of-scope, unknown and expired all get the same not-found answer.
- Tests cover the DTO allow-list and scope isolation.
- As agreed, it also includes the proxy-header and API-key exemption for share routes, since this is the first public endpoint.
Two questions before I start:
- #1661: PR 3 should use the OpenAPI annotations and the shared error conventions from #1661. I'd prefer to keep going: start with the current conventions now and switch PR 3 over once #1661 lands. I'm happy to do that follow-up myself. If you'd rather I wait for the foundations, that's fine too, it's your call.
- Hardening: should token redaction in logs, the
no-referrer/noindex/no-storeheaders and rate limiting of failed tokens go into PR 3 directly, or into a follow-up PR? I'd lean towards PR 3, so the first public route is never unprotected, but it depends on how small you want PR 3 to be.
Hi @perber,
thank you for merging the PRs! I've implemented the next step and created the PR #1762.
Also please let me know, if there's anything to improve, as these are my first steps in this project.
Best regards, Lukas
Hi @lboehm,
sorry for the long delay. I've merged your PRs.
Best regards, Patrick