mirror of
https://github.com/runbear-io/beardrive.git
synced 2026-08-25 08:08:08 +02:00
* fix(security): close 12 authorization holes found by adversarial round 1
Four offensive agents attacked the hub's trust boundaries in isolated
worktrees; every finding is a Go test that failed on the tree before the
fix and passes after. 43 TestSec_* regression tests land with the fixes.
The two that matter most:
- A grant outlived org membership: projectPerm consulted p.Perms before
checking the org role, so removing someone from the org through the API
left their explicit project grant working. Offboarding did not offboard.
- Any device could PUT any other device's journal key — the hub never
compared the key to X-Bdrive-Device. That is the "each device writes
only its own journal" invariant, enforced nowhere.
Also: uploads accepted .bdrive/ and .git/ paths (and materialize applied
only filter.Skip, never neverSync, so a hostile peer journal could too);
the org share audit handed every member public /s/ URLs for projects they
were denied; password reset left old sessions and device tokens valid;
blobs were not verified against their content address; quota was bypassed
by chunked encoding and by a client-declared size; X-Forwarded-For
defeated both rate limiters, login brute-force included; the /s/* sandbox
CSP was missing on error paths; expired shares were revocable by anyone;
and projectPerm failed open to admin for org-less and unknown projects.
Known open, recorded in .claude/security-goal.md: the device header is
self-asserted (the fix buys an audit trail, not identity), and the
Dir==nil/Auth==nil admin escape needs a design decision first.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 17 more holes found by adversarial round 2
Round 2 attacked the five boundaries round 1 never reached (read heat,
path handling, secret leakage, the agent hook guard, the metadata store)
plus the places round 1's coverage was overstated. 43 more regression
tests; 86 TestSec_* now green.
The critical one was not on the original board. A journal op's Blob field
is a raw storage key that nothing validates: handleStorePut checks blob
keys and their content hash, but a journal is arbitrary JSONL that never
passes through that validator. One PUT of your own journal with
"blob":"../../<other-project>/blobs/<sha>" — or "../../../etc/passwd" —
then reads back through the ordinary /file, /download and /render routes.
Any member read any file on the hub host, across orgs and outside the
storage root. Guarded where content resolves, and localBackend now
refuses a key that escapes root at all.
Also: /blob served HTML and SVG inline on the hub origin with no sandbox
CSP (stored XSS via History); bdrive init deleted the hooks it had just
written whenever $HOME is a git repo, silently disabling sync hooks
machine-wide; any account could rewrite another org's device registry row
and forge History attribution; a planted device id became a heat "reader",
putting an identity in an API response that must never carry one; storage
errors relayed the hub's absolute paths (and on S3 the bucket and key);
/auth/login?next= was an open redirect via backslash and TAB; the org and
project registries handed out their live maps (self-promotion to owner,
plus a hub-killing concurrent map iteration); revoked invites came back
after a restart and refused writes applied in memory anyway; a share
minted by someone since removed from the org kept serving publicly;
a newline in a folder name made the hook guard spawn bdrive outside any
mount; single-volume upload escaped through a symlink; the seat check was
check-then-act; and the hub data dir holding auth.json ended up 0755.
Known open and recorded in .claude/security-goal.md: nothing expires (no
TTL on tokens or sessions), the Dir==nil/Auth==nil admin escape, and
client-asserted Op.User. Postgres was never exercised — row 14's
SQL-injection result covers file and sqlite only.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 17 more holes found by adversarial round 3
Round 3 attacked the journal fields nobody had audited, the fixes rounds
1 and 2 had just landed, the real `bdrive serve -c` config path, and the
read ledger on a live Postgres. 133 TestSec_* now green.
The two worst are in the syncer, and both are arbitrary file write on
every teammate's machine. materialize guarded Path with neverSync, which
splits on "/" and looks segments up in ReservedDirs — ".." is not a
member and no ignore rule mentions it, so one JSONL line pushed to your
own journal key reached ~/.ssh/authorized_keys on every device that
synced. And the reserved-directory guard was case-sensitive, so
.GIT/hooks/pre-commit sailed past it and APFS resolved it into the real
.git/hooks. Op.Mode was applied verbatim, setuid bit included.
Attacking our own round-2 fixes paid for the slot twice over: ownsDevice
turned out to be a one-request speed bump (the refused report is what
registered the forged id, so the second identical request passed) and
its first-caller-wins rule made device registration a claim-staking
primitive an outsider could use to forge History attribution and
silently kill the real owner's read heat forever. Both dissolve by
keying the registry on (account, id) instead of treating the client's
device header as a hub-wide namespace. trust_proxy, added in round 2,
took the first X-Forwarded-For hop — but XFF grows left-to-right, so
turning it on disabled the login brute-force limiter instead of fixing
it.
Also: a peer's Lamport: MaxInt64 wrapped a victim's clock and silently
reverted its own edits on its own disk; History leaked other orgs'
device names and was a hub-wide device-existence oracle; anonymous
/api/config named the storage bucket; /auth/reset enumerated accounts by
timing and was not rate limited; the signed-in hub UI was frameable and
sniffable; an asset miss returned the app shell marked immutable for a
year; Op.Size forged Content-Length; a share on an org-less project
survived its creator's offboarding; a refused upload still created
directories outside the served folder; and one NUL in a read report
wedged the entire hub's read telemetry permanently on Postgres.
Verified against a real Postgres 16 this round. Known open and recorded
in .claude/security-goal.md: NUL round-trip on Postgres text columns
(refusal vs encoding is a design call), nothing expires, the
Dir==nil/Auth==nil escape, client-asserted Op.User, and store/sign on a
backend that can actually presign — never reached in three rounds.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 32 more holes found by adversarial round 4
Round 4 opened five packages no previous round had touched — store,
journal, config, remote and cmd/bdrive — and attacked the fixes rounds
1-3 had landed. It broke five of them. 166 TestSec_* now green.
The four criticals:
- ownJournal bound the journal key to the X-Bdrive-Device header of the
same request, and nothing bound that header to an account. Round 1's
test varied the key while holding the header fixed — the one
combination that was refused. Move both together and any member wrote
and replaced any peer's journal: her ops vanish, every device replays
the attacker's deletes, History credits them to her.
- store.BlobPath joined Op.Blob straight onto the blob dir with no check
that it was a sha256, and HasBlob answering true made syncer.pull skip
hash verification — so a peer's journal op read any file on every
teammate's machine into their working folder.
- A folder's .bdrive/config.json chose where this device's hub token was
sent. The file travels with the folder, so a zip or a colleague's copy
redirected the credential to any host, http:// included.
- sync --prune read .bdriveignore before the cycle and pruned against the
version the cycle had just pulled, so it deleted for the whole team
under exactly the ! rules it refuses to run with. A teammate running
bdrive scope was enough; no attacker needed.
Also: two symlink escapes in materialize (unsafeRel judges spelling, not
disk); three ways one peer op killed sync permanently on every device
that pulled it, including a panic on a short blob string; the ignore-file
reload dropped the nested-mount boundary; round 3's Lamport ceiling was
inclusive and so still reachable; the (account, id) device rekey held
neither on the read path nor on disk, so a restart handed the device to
the squatter; presigned uploads bypassed the content-address guard
entirely — that whole branch had never executed under a test, since every
fixture used file:// which cannot sign; remote.Prefixed, the single
containment primitive for multi-tenancy, did not contain; and a mount id
from the untrusted folder config escaped $BDRIVE_HOME.
Plus: bdrive export wrote hub-named keys as tar members unvalidated; the
device token followed cross-origin redirects; a symlink in the file://
storage root read and wrote anywhere on the host; GCS presigned PUTs
bound no size; presigned device uploads were never billed; trust_proxy
was wrong for the third round running; one bad line voided an entire
journal; Op.Path was not byte-exact through JSON; Less was not a total
order, so Replay's determinism rested on a caller's accident; and client
journals were 0644.
Three new scoreboard rows: client local state, the project archive, and
the device as client of a hostile hub. Still zero tests after four
rounds: internal/daemon and internal/autostart.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 29 more holes found by adversarial round 5
Round 5 opened internal/daemon and internal/autostart (zero tests after
four rounds), drove the browser presign flow, and attacked round 4's
fixes. It broke seven of them, including the one round 4's commit message
called "the critical". 247 TestSec_* now green.
ownJournal failed four separate ways. The write doors called
observeDevice BEFORE ownJournal, so for an unclaimed id the request
manufactured the fact that authorized it — and device ids are not secret,
History publishes them. The claim was then permanent and unrecoverable:
no Delete on DeviceRepo, no release, no admin route, no CLI re-mint, and
a 403 naming no remedy, so any member could deny any colleague's laptop
the ability to sync forever. Rows were global but visibility per project,
so offboarding a teammate released her journal to whoever was left.
And because an ownerless row ranked as the earliest claim, every hub
upgraded from before rows had owners had the binding switched off for
precisely its established devices. Ownership is now hub-wide, an
ownerless row authorizes nobody, observation happens after the decision,
and project admin is the documented recovery path.
The other critical is a divergence primitive: pull resumed at an op
COUNT, and round 4 had just taught Parse to skip bad lines silently. One
undecodable line inserted among lines a device already counted shifts
every appended op down by one, so two devices replaying one journal hold
different states permanently — and the peer picks the split. Now resumed
at a byte offset.
Also: a mid-run edit to .bdrive/config.json moved a whole project to a
remote of the writer's choosing, with no restart and no credential, and
the daemon then pulled from it; verify-on-read was defeated by uploading
honest bytes first, since a presigned URL is replayable for its TTL;
appendOp's lamport wrapped int64 and silently broke last-writer-wins for
every later upload in the project; peer journal strings reached bdrive
log's terminal unescaped, so the audited party could rewrite the audit
(OSC 52 to the clipboard, \r to repaint a delete as a put); path_raw let
one journal line name two different files to two reader versions; Stop
signalled whatever pid a 0644 file named; locked() failed open, so status
lied and stop stopped nothing; and a macOS path containing "&" made the
autostart plist unparseable while Install reported success.
Two four-round deferrals are now answered rather than carried.
Dir==nil/Auth==nil is not reachable — nine real configurations, both
arms, real project ids — and is a guarded invariant. The Postgres NUL
question was swept across seven stored-record surfaces on a live
Postgres: no silent-loss path, and cleanUploadPath now refuses control
characters so it is unreachable through the API.
Quota became a reservation with reconciliation: reserved at the grant so
concurrent grants cannot oversubscribe, charged on arrival, released free
on expiry, and charged once.
Recorded, not hidden: permHub builds a hub with Devices == nil, so round
4's ownership binding was inert in that fixture and earlier "clean"
results measured through it proved less than they looked.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 30 more holes found by adversarial round 6
Round 6 attacked round 5's fixes, the completeness floor (templates, CLI
commands, the untested exported API), and — new this round — the test
suite itself. 290 TestSec_* now green.
One hacker reverted 33 of the accumulated fixes one at a time to see
which the suite actually caught. 28 held. Five did not, and those five
are the most valuable result of the round: permHub built its hub with
Devices == nil, so a dozen journal-pushing tests had been proving
permission and never ownership; the ownerless-legacy-row test passed
because its helper never set Op.Device, so the r5 hole it guards would
have gone undetected; nothing asserted that an outstanding presigned
grant counts against the quota cap, which is half of reserve.go's
contract; row 6 claimed cleanUploadPath refuses control characters and
named no test, and that guard is what keeps the Postgres NUL divergence
unreachable; and unsafeRel — round 3's headline client fix — could be
deleted with the suite green, surviving on round 4's UnderRoot. It also
accepted ".", contained only because hashFile happens to fail on a
directory first.
The criticals: round 5's byte-offset pull resume was the same divergence
primitive it replaced, twice. A peer that publishes in two stages and
cuts the first mid-line makes one chosen device permanently skip the op
that straddles the cut while every other device applies it. And round 5
deleted the shrink guard, so a peer withdraws an op every device already
applied — the file vanishes from teammates' folders with no delete op,
nothing in the journal, nothing in History. Separately, Deny removed an
account but every authorization decision downstream keys on email, so
grants and org roles stayed attached to the address: re-registering it
walked back in as project admin, and its public share links kept
serving.
Also: reset and verification mail took its link host from the request, so
an unauthenticated stranger could have the hub mail a victim a genuine
reset link pointing at the attacker's server; a refused password reset
reported "Password updated"; share revocation, approval, policy and
account removal all took effect in memory after the store refused them,
each failing in the widening direction; one journal push with a year-2300
timestamp overflowed the History cursor and hid the whole audit feed past
page one; account ids were 32 bits with no uniqueness check, and the
birthday bound is ~9,300 accounts for a 1% chance of silently
transferring one account's credentials onto another; the new reservation
ledger had a data race on the billing path, a check-then-act that let 5
of 16 concurrent grants through a cap fitting one, and released arrived
bytes unbilled on expiry; safeField stripped C0 but not the 8-bit C1
controls that are CSI/OSC/DCS/NEL in any xterm-lineage terminal, nor
bidi overrides; and internal/templates — first contact — bypassed
cleanUploadPath entirely and wrote through symlinks using the shipped
template with no hostile input at all.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 29 more holes found by adversarial round 7
Round 7 drove `bdrive init` end to end for the first time — named the
largest gap by two consecutive CISOs — and tripled the sabotage sweep to
53 reversions. 326 TestSec_* functions green.
init held two criticals the moment it was actually run. `init --server`
took the no-auth branch when a server answered {"auth":{"enabled":false}}
and rewrote settings.Server without touching settings.Token — and
settings.Server is the entirety of round 4's token binding, so a 30-line
HTTP server collects the real hub's bearer token. And `init $BDRIVE_HOME`
was accepted, because the .bdrive reserved-directory rule only applies to
segments below the mount root: from there settings.json is an ordinary
top-level file, so the first cycle pushed this device's token to the hub
as project content, for every member and every teammate's disk.
Two more criticals were old fixes on doors they never covered. Round 4
bound the device token to settings.Server's origin in remote.deviceToken
— the sync backend's door — while share.go reads its destination from the
folder's .bdrive/config.json and hands the token straight to it, and the
CLI's own http.Client had no CheckRedirect at all. And round 6's offboard
only log.Printf'd RemoveMember's "cannot remove the last owner", so
anyone signing up on a removed sole-owner's address inherited org
ownership and admin on every project in it.
The sabotage sweep found 8 more guards deletable with the whole suite
green, including MayActAs (every existing test planted an id that
validDeviceID rejects first, so the ownership loop was never consulted),
both framing headers (round 3's test held the disjunction, not the code),
and sqlAccountRepo's id guard — where the untested backend is the one
managed and Postgres deployments run. For the first time the sweep also
covered the three choke points themselves: reverting requirePerm turns 30
tests red, projectPerm 21, authGate 9.
Also: two more journal-undo primitives past round 6's count guard, now
keyed on identity; reset-mail poisoning survived because the pin was
first-request-wins and round 6's own reproducer sent the honest request
first; the /store/* journal door accepted paths /upload/commit refuses,
so the three spellings of one path rule became one exported predicate;
bdrive forget injected .bdriveignore rules outside any managed block;
bdrive resume built a volume path from an unvalidated registry key; round
5's $HOME-is-a-git-repo fix broke again on a string compare of two
spellings of one path, silently disabling every agent hook on the machine
while init reported success; and the CheckWrite call round 6 moved under
the hub-wide ledger mutex stalled every project's sync cycle.
Known open: a peer can still un-publish an applied op by corrupting its
line and appending as many as it removed — the clean close is hub-side
append-only enforcement on /store/*, a behaviour change no failing test
demands yet. The init tests all ran with auth.enabled false, so the login
flow inside init — where the first critical lives — is still untested.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 26 more holes found by adversarial round 8
Round 8 drove the authenticated login flow, the last five CLI commands,
and sabotaged row 15 exhaustively. 621 TestSec assertions green.
Three of round 7's fixes were half-fixes. Its $BDRIVE_HOME guard closed
the child direction only, so `bdrive init` on any ANCESTOR of the home
still pushed this device's bearer token to the hub as project content —
and a relative $BDRIVE_HOME disabled the guard entirely, reopening the
original critical. Its mail fix still seeded the pin from r.Host, so on a
fresh process an anonymous stranger could have the hub mail a VICTIM a
valid reset link on the attacker's server; the mirror image turned
password recovery off hub-wide with one request. And the hole round 7
declined to close got a reproducer that also invalidated its proposed
remedy: a peer publishes its last op unterminated, the next append fuses
onto that line and stops it decoding, so an op every teammate has on disk
vanishes with no delete op — through a byte-level PURE APPEND, which
hub-side append-only cannot stop.
Two more criticals were first contact. The loopback login callback had no
proof of possession: its only binding is a `state` that is printed to
stdout and passed to xdg-open as argv[1], so any local process that can
run `ps` signs the device in as its own account and the user's folders
sync into the attacker's project. And the three /store/* READ doors call
observeDevice as their first statement — round 5 moved it after the
decision on the write door and never touched the read doors — so one GET
with a victim's device id first-claims it hub-wide and locks that device
out of its own journal, from read permission on any single project.
The sabotage sweep is the round's most important result. 48 guards in row
15 reverted one at a time: only 20 were caught. A 57% false-negative
rate, nearly 4x rounds 6 and 7. The materialize DELETE loop's three
guards — one of which ends in os.Remove — were held up by nothing,
masked because scan's delete pass applies the same rule to the same cache
first, so no whole-Cycle fixture can tell which guard refused.
absorbLamport's ceiling and tickLamport's stop mask each other, so the
existing test passes with either removed. Eight of the 26 misses now have
tests; 18 remain open, and row 17 was never reached at all.
Also: a hostile export archive chose which of your existing projects it
landed in (create-or-join-by-name, emptiness checked after the join); a
folder that merely arrived on disk stole an enrolled mount's registry
row, so at next login the real project's daemon ran on the arriving
folder; one device approval minted N tokens and bound them to a device
the human never approved; logout left the credential live with no
revocation route; and two unbounded reads on the device side had the
declared size in scope at the call site.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 5 more holes found by adversarial round 9
Round 9 spent most of its budget on sabotage rather than new attacks, and
the numbers are the point. 705 TestSec assertions green.
Row 17 swept in full: 44 reversions, 9 missed (20.5%). Rows 13 and 18-22:
57 reversions, 12 missed (21% overall — row 13 at 40%, row 20 at 33%,
row 18 at 0%, the only perfect row swept in any round). And row 15's 18
remaining untested guards got tests, each verified red under its own
reversion — including both of round 8's flagged leads, which turned out
to be correct guards that were merely untested. That agent reported dry.
So roughly 29 previously-deletable guards are now genuinely pinned.
All five live holes are regressions in round 8's own fixes. Its
re-assertion fix re-published a withdrawn op at its original low lamport,
which made it a losing local unpushed op the instant it was written — so
conflictCopies did what it exists to do and the victim created, signed
and pushed a file holding content the peer chose, at a path that never
existed. The same admission rule had no guard for withdrawn deletes and
consulted neither the ignore filter nor neverSync, so a device
republished paths it deliberately refuses to materialize. Re-assertion
now requires that this folder's own cache stands behind the op.
Its sizeBound fix returned on a sha mismatch instead of skipping, so one
understated Op.Size in one line of a peer's journal permanently withheld
every blob queued behind it — before round 8 the read was unbounded, the
sha matched, and the files arrived. The bound was not the defect and is
unchanged; the error is now remembered and returned after the batch.
Also: the org heir was chosen by the smallest email address rather than
the longest-standing member, so the newest member inherited ownership and
project-admin on every project when a hub admin removed a departed
employee; $BDRIVE_HOME was created 0755 by LoadDevice, which runs before
almost everything, so listing alone named every project, every device in
the fleet and every content hash without opening one of the 0600 files;
and round 8's ResolveMount condition stranded a genuinely moved project
behind a leftover config, with init itself blocked on the same check.
Move-vs-copy is now decided by dev+ino, which a rename preserves and a
copy cannot reproduce.
Judgement call recorded: the nested-mount carry reverts green but stays.
Deleting a defence-in-depth guard because the tests did not notice is
exactly the reasoning the sabotage table exists to distrust. It is marked
as not counting toward coverage.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 30 more holes found by adversarial round 10
Round 10 drove three surfaces end to end instead of sweeping, and the
contrast is the round's real result. Round 9 spent itself on sabotage and
found 5 holes; round 10 pointed a device at a hostile hub, executed the
Linux autostart code for the first time in ten rounds, and requested the
three /auth pages nobody had ever fetched — 30 holes. 777 TestSec
assertions green.
Row 19 is the clearest data point the loop has produced. A round-9 sweep
scored it 12.5% missed and annotated it "no reachable impact", so it
wrote zero tests. Driven end to end it held 11 holes, one critical: pull
skips a listed journal only on an exact string compare, so a hub listing
journal/DEVA.jsonl resolves to the same file as deva.jsonl on APFS and
NTFS and overwrites the device's OWN journal — the invariant the whole
concurrency design rests on. A sweep can only find a hole where a guard
exists; it cannot find a class nobody wrote a guard for, and every
critical since round 7 has been that kind.
Also from the hostile hub: one unusable listed key hid every peer
permanently; one listing minted 200k local journal files; the hub sized
the device's own allocation at two layers, and one boolean in a sign
response made a device publish an op for content it never sent, with the
cursor advanced past it so it never retried. putDirect shipped file
bytes to any host the hub named — round 4 dismissed this because "the hub
already holds the data", but at the moment it names the destination it
does not, which is what the upload is for.
Row 5's device binding is closed after four rounds of deferral. A
read-only member's device could never register, so any member with write
anywhere took its id permanently — and the arm that let them through read
a field the attacker writes. The id is now minted hub-side at login,
bound to the authenticated account, at all three mint points. That was
first framed as requiring the supersession of round 7's test; it did not.
Round 7 asserts a read door creates nothing, and that property is
unchanged and strictly stronger, because the read door now has nothing
left to claim with.
Four of round 9's five fixes had live residuals: re-assertion laundering
returned on any device that cannot push (conflictCopies measures unpushed
against a cursor that only advances on success, and read-only is the
documented steady state); the sizeBound fix still let one peer integer
suppress the victim's own push; earliestMember was inert on every
upgraded hub; and the dev+ino discriminator was inert on every row that
existed. ResolveMount turned out to be a write with a read-shaped name,
so bdrive restore and forget enrolled the device in projects it was never
init'ed into.
Recorded as a measurement gap, not a finding: row 14 was scored clean on
every backend for seven rounds, but this is the first round ever run with
a Postgres DSN, and metaBackends silently omits the arm without one. A
skipped arm and a missing guard are indistinguishable in a green suite.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 24 more holes found by adversarial round 11
Two criticals, both first-contact findings on surfaces ten rounds had not
reached.
An `.xml` file got script on the hub's own origin with the reader's session:
`sandboxInline` walled off a LIST of content types where the thing it protects
is a PROPERTY ("the browser parses this as a document"), and the whole XML
family sat outside the list while having the property — an XML document carries
its own `<?xml-stylesheet type="text/xsl"?>` and the XSLT output is HTML in the
origin that served it. `inlineMarkup` is now the property, `inlineType` serves
the XML family inline as text/plain so nothing parses it as a document, and
`nosniff` goes on every stored-bytes door.
A plain member replaced another account's journal by spelling her device id in
a different case: every hub ownership decision was a byte compare while APFS
and NTFS fold, so one login and one PUT broke the one-writer invariant the
whole concurrency design rests on. `canonDeviceID` folds at the trust boundary,
the registry folds on load and at every entry point, and `ownJournal` requires
the canonical journal key.
Also: org ownership was drawn by Go map iteration (`sort.Slice` on an all-zero
`Created` column) and now needs real evidence of age or produces no heir; a
revoked grant was restored by any unrelated write from a second hub process
(grant writes are row-scoped now, on all three backends); `/history` named
whoever the pushing device typed; the admin recovery arm locked the real owner
out of `bdrive login` forever, across the org wall; `bdrive scope` was the
unescaped door `forget` used to be and could wipe the team's synced rules;
`journal.SafePath` let every bidi control and every C1 through.
Two tests were touched, both disclosed in .claude/security-goal.md:
TestSec_DB_NULBytesDoNotTruncateRecords is retired (its assertion is one
Postgres cannot implement), and TestSec_Scope_AddCannotCreateADirectoryOutside-
TheProject is rewritten against the guard it was meant to test — it called
os.MkdirAll itself, so no production code sat between its setup and its
assertion. The rewrite was verified to go red with the guard removed.
918 TestSec assertions green, whole suite green including Postgres and -race,
108/108 Playwright, Linux container clean.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): the run-mode note only printed when the suite was already red
Round 10 moved the "postgres UNTESTED in this run" note from t.Log to
os.Stderr because t.Log is invisible without -v. That was not enough: `go
test` buffers a package's output and discards it on success without -v,
stderr included. So the note that exists to make a silent coverage gap loud
was itself audible only during a failure — the same shape as the hole it
guards against, and the reason it went unnoticed is that every round that
read it had a red suite in front of it.
secrunNotify now also writes to /dev/tty, which survives that buffering.
Verified under a pty on a fully passing run with no -v.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 24 more holes found by adversarial round 12
The critical one is the fifth instance of "something survives offboarding":
an org invite outlived the membership, the ownership AND the account that
minted it. OrgDB.Redeem/ValidInvite now resolve the minter's ownership at
read time — the rule shareCreatorStillBelongs already applied to a share
link — and retire the invite when it fails, so EvictMember's heir promotion
cannot revive it.
Round 11's row-scoped write landed on ProjectRepo only. OrgRepo, ShareRepo
and DeviceRepo had the same whole-record shape, so a second hub process's
unrelated write resurrected a revoked org membership, a revoked /s/ link,
or erased a device binding. And the authorization READ path never got it at
all: ProjectDB answered from a copy taken at boot, so a revocation took
effect on one process and no other.
Also: a push could credit another account through Op.Author; journalOps
checked the Note and not Author/UserName; a display name skipped trimText;
a password reset left outstanding reset and verification mail grants alive;
nosniff missed two stored-bytes doors; SafeText admitted the zero-width
formats; a project name could break out of the ConnectGuide paste prompt;
inviteTokenFromNext matched "/join/" anywhere in `next`; file content chose
what read-log reported as a read, and the hub recorded reads for paths that
do not exist.
Frontend: decodePath threw URIError on a link in a teammate's document and
unmounted the whole SPA persistently (fixed at the decode, plus a real
ErrorBoundary), and the router kept the Object.prototype lookup bug round 11
fixed in ProjectIcon.
Decision, not a patch: agent HOOK config (.claude/settings.json and
friends) is now reserved in both directions. Skills, commands and CLAUDE.md
deliberately are not — sharing what an agent reads is the product. The trust
boundary that follows from that is now written down in INSTALL_FOR_AGENTS.md,
the docs' Start-here path, and README.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 17 more holes found by adversarial round 13
Round 12 gave ProjectDB a read-path refresh() because a revocation only took
effect on the process that served it. Four sibling registries with the
identical defect went unexamined for a round.
The refresh family (one fix, three service structs + two file repos):
- OrgDB.refresh — the wall IN FRONT of project permissions. A removed org
member kept reading every project in the org; a revoked invite still
redeemed and, on the default invite-only posture, bootstrapped the account.
At the top of the MUTATORS too: the last-owner guard is a cross-process
TOCTOU the write-side re-read cannot close.
- BuiltinAuth.refresh — the CREDENTIAL, not a grant on top of one. A revoked
device token still authenticated; a deleted account signed in again with its
old password.
- ShareDB.refresh — a revoked /s/<token> was still served to anonymous
strangers. fileShareRepo.reload's own r12 comment named this row.
- fileAccountRepo.reload, fileReadRepo.reload — the last two file repos with
no write-side re-read.
It lives in the service structs, not db_file.go: the staleness reproduces on
sqlite and Postgres too, and a file-only fix would have left the
two-replicas-one-database deployment fully broken.
Also:
- offboard now releases the device binding (DeviceRepo.Delete +
DeviceRegistry.Release). A deleted account kept a hub-wide claim on its
device id, which silently and permanently locked out the next hire.
- SafeText and trimText refuse unicode.Cf and the tag block AS A CLASS. The
tag block encodes all printable ASCII with no glyph, so a project name
rendering as "wiki" smuggled a shell command into the agent paste prompt.
- .mcp.json is reserved; the agent-config list is now derived from what each
platform LOADS, not from what BearDrive writes.
- pageDevice and X-Bdrive-Device-Name go through trimText: an unauthenticated
stranger chose the text AND the length of the hub's only consent surface.
- SetPolicy runs the startup validator, so POST /api/admin/policy cannot reach
a posture the binary refuses to boot in.
- Insights uses Object.create(null): a folder named __proto__ erased an agent
device from the Dashboard.
go build / go vet / go test ./... clean with and without BDRIVE_TEST_POSTGRES;
-race clean; Playwright 127/127. Linux container run not completed — see
.claude/security-goal.md.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close the agent-onboarding holes found by round 13's fourth hacker
Four findings, all against the already-hardened tree. Its fifth (.mcp.json)
was already closed and its test passes — an independent confirmation of that
fix from a second angle.
1. A peer's `!.env` in the shared .bdriveignore uploaded another member's local
.env on their next cycle. Round 4 made .bdriveignore team-wide on purpose
and made `sync --prune` refuse on `!` rules for exactly that reason — but
that reasoning covered DELETION, and nobody asked what a pulled negation
does to SCAN. The runbook's own `bdrive init . --only docs,notes` is what
creates the exposure: the whole repo goes under the mount with only this
synced, teammate-writable file holding the rest back.
Fixed asymmetrically at the upload door (Filter.SkipUp, consulted by
walkFolder): pulled rules that NARROW apply immediately in both directions;
pulled rules that WIDEN apply to materialize but not to scan, until this
device authors the rules itself (init --only, bdrive scope, an editor). A
joining device has authored nothing, so team-wide scope still works on day
one — which a blanket "ignore pulled negations" would have broken.
`bdrive scope --explain` reads the same floor so it cannot drift.
2. A FAILED `init --server <url>` signed the device out of its real hub and
left it defaulting to the new one — after a run that ended in "Error:".
ensureLogin now returns a rollback; initCmd commits the session only once
the hub has answered with a project this device can open.
3. `init --server http://…` minted and stored a device token with no plaintext
warning while `bdrive login` on the same URL warned — and step 2 of the
runbook is titled "Do not run a login command". The warning moved from
loginCmd's RunE into the shared runLogin: one sign-in door, one warning.
4. The hub chose the device-login link and the CLI printed it verbatim under
its own "open this link in any browser". sameOriginLink falls back to the
hub's own /auth/device when scheme+host differ.
Also: safeField gets the same unicode.Cf + tag-block class rule SafeText and
trimText got — third door, same class. Scoping guide documents the widening
rule. Two findings that are not tests (the runbook URL pinned to a mutable
branch; nothing authenticates the hub during device sign-in) are recorded in
known-open.
go build / go vet / go test ./... clean with and without BDRIVE_TEST_POSTGRES;
-race clean on webapp, syncer, store, cmd/bdrive; Playwright 127/127. Linux
container run still not completed — the Docker daemon on this machine will not
create containers at all; see .claude/security-goal.md.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(security): close 22 more holes found by adversarial round 14
The last round of the loop. Four hackers landed; 21 of their tests go green
here, the 22nd names a hole that IS fixed but cannot pass as written (see
below). `.claude/security-goal.md` gains a handover section for a human in
place of the "next round's targets" framing.
Sync / scope (internal/syncer)
- A peer DELETING the shared `.bdriveignore` walked straight past round 13's
upload floor: the `IgnorePulled` bookkeeping sat behind `if want, ok :=
target[IgnoreFile]; ok`, so a delete never updated it while materialize
unlinked the local copy anyway — and the next cycle read the absent file as
locally authored, dropped the floor AND the live rules, and pushed the whole
repo. Recorded as pulled now.
- Both SyncState fields are `omitempty`, so on its first post-upgrade cycle
every existing device adopted whatever was on disk as its own — including a
peer's `!.env` that landed one cycle earlier (scan runs before pull, so it
always does). An upgraded device now seeds its floor with `vouchedFloor`:
keep a `!` line when the path it re-includes is already in this mount's
materialization cache, drop it otherwise. That is what keeps a `bdrive
scope` block (`/*` plus nothing but negations) from silently ending uploads
— pinned by TestUpgradedScopedDeviceKeepsUploading.
Second-process staleness (internal/webapp)
- ProjectDB had refresh() on Get and List only. `put`→`PutMeta` is an
unconditional upsert, so a second process's ordinary rename put a DELETED
project back carrying the org the public-link rule reads; the last-ADMIN
guards counted admins out of the boot-time map; GetOrCreate answered
create-or-join differently per replica. refresh() now runs at the top of all
ten mutators.
- DeviceRegistry had no refresh() at all — round 13 cleared it on the
bind-away direction alone. Offboarding released a device claim on one
process and no other: the next hire is locked out, and a re-created address
inherits the departed account's journal write gate elsewhere. Pinned on
file, sqlite and postgres.
Audit trail
- `/store/object` was a plain object PUT with no relation to what is stored,
so any member could rewind their own journal — or, after inheriting a
reassigned device id, a departed member's — out of History. Journal pushes
now must keep every op Seq the hub already holds.
- seedTemplate journaled the hub's own template files under the account that
ran `bdrive init --template`, byte-identical in shape to a hand upload. They
now carry no account and a "seeded from the <name> template" note.
Text and rendering
- journal.SafeText refused every category-Cf rune and missed U+2028/U+2029
(Zl/Zp), which the webapp's own trimText has deleted by number since round
12. A folder row for `line<U+2028>sep.md` paints to exactly the same glyph
run as `line sep.md`.
- A strong-RTL LETTER needs no format character to reorder a rendered row.
Measured in Chromium, `unicode-bidi: isolate`, `plaintext` and `<bdi>` all
leave it intact; `isolate-override` fixes it, and peer-written-name
selectors now carry it (SPA + the auth pages' device-approval rows).
- `)` closes the paste prompt's clause exactly as `"` did; project names now
drop both parens (org/device/account names are unaffected). PATCH
/api/projects/{id} called trimText where create called trimName, so rename
stored `/` and `\` — one rule for both doors now.
CLI
- `p.Template` was the one hub-chosen field in `bdrive init`'s output that
never reached safeField.
- `--template` reported the hub's own string as proof and never looked at what
arrived; it now always falls through to the idempotent seedLocally.
Docs
- INSTALL_FOR_AGENTS.md no longer raises the hub-seeded AGENTS.md to the
user's authority, and its trust boundary names the hub as an author of
folder content. Documentation defects, not demonstrated exploits: three live
headless runs did not flip behaviour.
Known red, deliberately not worked around:
- TestSec_ProjectName_RenameBypassesTheCreateNameRule — the hole is fixed and
separately verified; the test's own control creates a project with the
normalized name in the same org before renaming into it, so correct
behaviour collides with the unique-name-per-org rule.
- Two e2e/sec14fe specs upload a U+2028 path to demonstrate a rendering
collision that this commit's ingest fix now refuses at the door.
go build / go vet clean. go test ./... green with and without
BDRIVE_TEST_POSTGRES and under -race, except the test named above. Playwright
serial: 131 passed, 2 failed (the two named above).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* test(security): the rename test collided with its own control
TestSec_ProjectName_RenameBypassesTheCreateNameRule created a project
from the same payload it then renamed a second project to. Both
normalize to "notes....etc", names are unique per org, so the rename
400'd on the collision and the test failed at its control check without
ever reaching the assertion it exists to make.
It failed that way against the FIXED code, which is the worst way for a
test to be wrong: it reads as an open hole and is really a broken
instrument. The control now uses a payload that normalizes to a
different name.
Verified load-bearing rather than merely green: reverting Update's
projectLabel call turns it red with "rename stored a path separator in
a project name: notes/../../etc".
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* docs(architecture): draw the security hardening's new types and seams
The branch added shared rules and gates that the diagrams did not have
boxes for, so the pictures no longer described the code.
cli-sync: the three drifting path/text checks collapse into one
journal.SafePath/SafeText box, plus store.UnderRoot and
config.ReservedPath as their own single-rule boxes; Filter gains SkipUp
and AcceptRules and the scan/materialize rules stop being symmetric;
SyncState is drawn for the IgnoreAccepted/IgnorePulled floor; the
registry records Dev/Ino and splits ResolveMount (read, self-heal) from
EnrollMount (the only writer); the daemon's signalled pid moved inside
the flock.
webapp-server: DeviceRegistry is keyed (account, id) with
Bind/Release/OwnerOf/MayActAs; new boxes for the /store journal door,
the quota reservation ledger, sandboxInline and offboard; refresh() on
every service; the row-scoped repo interfaces, the storable validation
gate and the schema-version guard in the MetaStore block; HasBlob became
BlobSize.
webapp-frontend: ErrorBoundary, the app's floor. Also fixes escaped
quotes in a note that have been rendering this whole diagram as an error
box on GitHub since it was written.
overview: unchanged — no package appeared or disappeared and no
cross-piece flow moved.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* test(security): re-aim two specs their own fix made unbuildable
Round 14 refused U+2028/U+2029 at ingest. Two e2e specs proved a
*rendering* collision by uploading exactly those code points, so the fix
made their fixture impossible and left them red — a broken instrument
reading as an open hole, the same shape as the rename test.
The listing spec now asserts the ingest guard instead, and keeps the
measurement that says why the guard matters: the two names painted to
70.9844 x 16, one line box, byte-different and pixel-identical, measured
in Chromium with Range.getClientRects() over live text nodes. Relax
SafeText and it goes red before the collision returns.
The shares-audit spec is skipped with its numbers preserved. Its
reachable sibling — a strong-RTL letter, which cannot be refused without
refusing Hebrew filenames — is covered by the neighbouring spec and
fixed in style.css.
Playwright: 133 passed, 1 skipped.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* test(security): a comment in a spec leaked a CSS rule into the bundle
Tailwind's content scanner reads the e2e specs. A bare `isolate` token in
prose explaining the bidi fix emitted `.isolate{isolation:isolate}` into
the shipped bundle — a rule nothing uses, and a stale-assets failure for
check-dist.
Reworded to avoid the token, with a note saying why, since the next
person to explain a utility class in a comment will hit the same thing.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* docs(security): correct three handover entries the landing pass closed
The handover listed one Go test and two browser specs as permanently red.
All three were re-aimed after the loop stopped: the Go test was failing
against the FIXED code because its own control collided with it, and the
two specs were fixture-blocked by round 14's own ingest fix.
Suite is 1052 TestSec assertions green, 0 red; Playwright 133 passed,
1 skipped. The stopping condition itself is still not met and the notice
at the top of the file says so.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(sync): a Persian filename permanently wedged a device's sync
The scan door applied config.ReservedPath; the hub's ingest door applied
journal.SafePath AND config.ReservedPath. A file whose name the scan
accepted and the hub refused was blobbed and journaled locally, and
because push PUTs the whole journal object, every later push from that
device 400'd on the same op forever. Renaming did not help — the delete
op names the same path. The only surface was a line in daemon.log, and
recovery meant deleting the volume store.
walk.go's own comment already stated the rule it was breaking: "the
outbound half has to match the inbound one." It just did not name every
predicate the inbound half applies.
Two changes:
SafePath now permits ZWNJ and ZWJ, which the Cf class rule refused. Both
are orthographically required — U+200C is what makes "میروم" the right
word in Persian and is mandatory in several Indic scripts, and U+200D
builds most multi-person emoji. Refusing them did not harden a hub; it
told those users their filenames were illegal. The confusability they
buy is also already reachable without them: a Cyrillic homoglyph
produces the identical "two rows, one reader" tree and is allowed. So
the clause was paying a hard i18n cost for a partial mitigation of a
class that stays open. A note has no orthography, so SafeText still
refuses all four zero-widths; the two rules now share one implementation
with a flag rather than diverging.
walkFolder applies SafePath, so an unsyncable name is simply not carried
— it shows up in `bdrive scope --explain` like any other exclusion and
never enters a journal.
The regression test asserts a PROPERTY over both predicates rather than a
character list, so adding a rule to one door alone reopens it. Its first
draft was vacuous — it skipped every unsafe name instead of creating it,
so nothing hostile reached the scan and deleting the guard changed
nothing. Caught by sabotaging it; it now creates the names unix permits
and goes red when the guard is removed.
Found by a CTO review of PR #112, not by the security rounds, which
checked this asymmetry on the hub and never on the client.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(hub): a proxied hub throttled all its users as one on day one
Upgrading a hub behind nginx / Caddy / Fly / Cloud Run without editing its
config made every user share ONE 10/min login bucket and capped public share
links hub-wide at 120/min: clientIP fell back to r.RemoteAddr, which is the
proxy. Correct passwords started answering "too many attempts", with no log
line saying why.
X-Forwarded-For is now trusted by PEER rather than by configuration: a proxy
that fronts a hub reaches it over loopback or a private address (sidecar,
container network, Fly/Cloud Run internal hop), so that header is the
operator's own infrastructure. A hub on a public IP still ignores it, and now
logs once instead of failing silently. trust_proxy remains the override for
the one shape the peer check cannot see — a proxy on a public address.
Which hop is taken is unchanged (last element of the last field line), and the
round 13/14 tests that pin it stay green.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* perf(hub): authorization stopped re-reading the whole registry per request
Every authorized request re-read the entire project, org and account registry
under a hub-wide mutex — 14.1 ms per request at 5k projects on the file
backend, nine unfiltered SELECTs on Postgres — so the hub served roughly 60
req/s regardless of cores while ~200 devices polled /store/list every 10s.
None of this existed before the security rounds; registries loaded once at
boot.
The semantics do not change. Registries still re-read the store before every
authorization decision — that is the correctness floor rounds 12-14 built, and
a TTL would put back exactly the staleness window they closed. What changes is
the cost of asking whether there is anything to re-read:
- new optional Versioned repo capability: one os.Stat (file) or one
primary-key lookup on a per-registry meta_version counter bumped inside
every write transaction (SQL). A repo that cannot answer is treated as
changed, so the fallback is the unconditional re-read that was always there.
- proj() resolved the project and then projectPerm resolved it again;
projectPermOf takes the Project the choke point already has. handleProjectList
and the org share audit did one resolution PER PROJECT in a loop; both now
pass the row they are already holding.
Measured on M1, benchtime=200x, one project resolve + permission check:
file 100 projects 331 us -> 6.0 us
file 1000 projects 2.85 ms -> 3.9 us
file 5000 projects 14.14 ms -> 3.9 us
sqlite 100 projects 295 us -> 22.9 us
sqlite 1000 projects 2.57 ms -> 22.5 us
sqlite 5000 projects 10.86 ms -> 21.5 us
and it is now flat in project count rather than linear.
The file backend does NOT become multi-process-safe from this: every write is
still read-modify-write-rename, and the mtime+size token would miss two
processes writing the same byte count within one filesystem timestamp tick.
refresh narrows the stale-read race; it does not close it. SQL is the fix.
TestVersionGateSeesAnotherProcessWrite pins the property that matters — a
second process's create and grant change are both visible through the gate, on
file, sqlite and Postgres. BenchmarkRegistryRead / BenchmarkAuthorizedRequest
go linear again if this regresses.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* perf(hub): every blob read on S3/GCS paid double egress and a full hash first
RemoteSource.verify re-read and re-hashed the whole object before returning a
second read for the actual stream, on any backend that can presign — and
PutSigner survives the Prefixed wrapper, so this was live on every S3 and GCS
hub. Every viewer open, render, download and /s/* share hit paid 2x
object-store egress and a serialized full-object hash before the user's first
byte. On file:// (the OSS default) verify is a no-op, which is why the suite
never felt it.
The check is not weakened. It is cached again, keyed on the one thing that
makes "blobs are immutable" true rather than assumed: BOTH presign doors
refuse to sign a key that already exists, so every presigned URL a blob ever
gets was minted before its first PUT and dies at mint+TTL. Once the stored
object is older than the presign TTL, no live URL for it can exist and none
will ever be minted again — the hub is the only writer left, and the hub hashes
what it relays. Only then is the verification cached. The object's age is read
after the hash, so a replay mid-check reads as seconds old and is not sealed.
Measured, 4 MiB blob, 200 reads (the "unsealed" arm IS the old code path):
before 2.41 ms/op 2.000 storage reads per blob read
after 0.39 ms/op 1.000 storage reads per blob read
On S3/GCS the second read is real egress and real latency, so the win is
larger there than this local stand-in shows.
NOT done: signing the content hash into the presigned URL. GCS cannot bind a
SHA-256 at all — x-goog-hash takes only crc32c and md5, and the md5 would be
declared by the same client that declares the sha, so a chosen-prefix collision
defeats it. On S3 the SDK hoists ChecksumSHA256 into the query string rather
than into SignedHeader; it is inside the signature, but whether S3 enforces a
hoisted checksum (and whether an unsigned request header would override it)
cannot be verified without a real bucket. With the seal in place the checksum
would add no security that verify is not already providing during the only
window it applies to, so it stays out rather than going in untested.
Backends that can sign but cannot bind a content address: GCS certainly, S3
pending a live check.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* docs: record the three PR #112 cost fixes and what they do not fix
architecture/webapp-server.md gains Versioned/versionGate, RemoteSource's
PresignTTL + seal, remote.Object.Modified, and the new clientIP peer rule.
Both mermaid blocks parse-checked with mmdc.
.claude/security-goal.md's "known-open, deliberately deferred" list is updated
with what each fix accepts: the private-peer widening on X-Forwarded-For, the
fact that the file backend does NOT become multi-process-safe from the change
token (read-modify-write-rename is unchanged; mtime+size narrows the race and
does not close it), and why the presigned content hash was left out — GCS
cannot bind a SHA-256 at all, and S3's binding lands as a hoisted query
parameter nothing here can verify S3 enforces.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* fix(hub): the blob seal compared two clocks that need not agree
The verification cache is sound on one argument: once a stored blob is
older than the presign TTL, no live URL for it can exist, so the bytes
cannot change again and the hash need not be recomputed.
That argument is about time, and the two times came from different
machines — o.Modified is the object store's clock, time.Since is the
hub's. A hub running ahead of storage overstates the object's age and
seals it while a minted URL is still live; a replay through that URL is
then served from cache for the rest of the process's life. NTP makes it
unlikely and a container without it, or a VM resumed from suspend, makes
it reachable.
Seal after the TTL plus an hour instead. Sealing early buys nothing —
the blob is immutable either way — so the margin costs a few extra
hashes on a young blob and removes a dependency on two clocks agreeing
that nothing in the process can verify.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* test(hub): age the blob-seal fixtures instead of shrinking the TTL
The clock-skew fix in b1e9d20 is right, and it left TestBlobVerification
StopsOnceTheObjectCannotChange red: the fixture used a 1ns presign TTL as a
stand-in for "old enough to seal", which stops working the moment the margin
is an absolute allowance for clock skew rather than a multiple of the TTL —
correctly so, since an absolute allowance is what skew actually needs.
The fixtures now age what the store holds (os.Chtimes over the backing dir),
so the tests exercise a genuinely old object. That also lets the boundary the
skew fix exists for be asserted directly: a blob PAST the presign TTL but
inside the skew allowance must still be re-verified, because "past the TTL" is
measured on the storage clock and compared on the hub's. Previously nothing
covered that case.
sealAfter's comment now names what the allowance does not buy — it is a bound,
not a proof — with the single-clock alternative as the upgrade path, and the
goal file records the same residual.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* test(hub): a partial Postgres reset was a half-applied migration
metaBackends' postgres reset dropped ten tables and kept four: project_perms
and device_rows leaked rows into the next test, and — the one that bites —
schema_meta survived while projects did not. That combination is precisely
what addColumns refuses: the next open rebuilds projects WITHOUT the guarded
default_level column and then reads a recorded schema version saying it should
already be there, so the store fails to open with the rollback error.
Nothing tripped it while TestMetaStoreConformance was the only thing opening
Postgres, because it reset and opened back to back. Adding a second Postgres
consumer (TestVersionGateSeesAnotherProcessWrite) made the residue reachable.
Reset now drops every table migrate() creates, which is what reset means. And
the version-gate test no longer drops anything at all: it asserts by project
id and GetOrCreate is create-or-join, so it does not need a clean database and
must not leave a residue the other harness does not expect.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
* docs: a red Postgres result is only evidence when nothing else shares the DSN
The harness DROPs and recreates the schema per test against whatever
BDRIVE_TEST_POSTGRES names, so two concurrent runs produce moving failures
that read as regressions. Record how to tell the two apart, since the
scoreboard leans on Postgres results.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgF8JsoeNPVShGYWdooE72
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1244 lines
46 KiB
Go
1244 lines
46 KiB
Go
// Package webapp serves the bdrive web server: a browsable web view of
|
|
// synced files (file tree reconstructed from the journals, rendered
|
|
// markdown, downloads), browser uploads, and — in hub mode — the sync API
|
|
// that lets storage-blind client devices sync whole projects through this
|
|
// server.
|
|
//
|
|
// Two modes:
|
|
//
|
|
// - single-volume: Source is set (a DirSource for a plain folder, or a
|
|
// RemoteSource in tests); the classic viewer.
|
|
// - hub: Root + Projects are set; the server hosts many projects, each a
|
|
// volume stored under <root>/<project-id>/ in the object store, managed
|
|
// by a file-backed project registry.
|
|
//
|
|
// The client — browser or syncing device — is deliberately told nothing
|
|
// about the storage: no remote URL, bucket, or credentials ever appear in an
|
|
// API response.
|
|
package webapp
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"embed"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"log"
|
|
"maps"
|
|
"mime"
|
|
"net/http"
|
|
"path"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/runbear-io/beardrive/internal/journal"
|
|
"github.com/runbear-io/beardrive/internal/remote"
|
|
"github.com/runbear-io/beardrive/internal/templates"
|
|
)
|
|
|
|
//go:embed static
|
|
var staticFiles embed.FS
|
|
|
|
// Source supplies the file set and content of one volume. Implementations:
|
|
// RemoteSource (a beardrive remote) and DirSource (a plain local folder).
|
|
type Source interface {
|
|
Files(ctx context.Context) (map[string]FileInfo, error)
|
|
Open(ctx context.Context, path string, fi FileInfo) (io.ReadCloser, error)
|
|
}
|
|
|
|
// Server renders volumes as a website and, in hub mode, brokers sync for
|
|
// client devices.
|
|
type Server struct {
|
|
// Single-volume mode: serve exactly this source.
|
|
Source Source
|
|
Volume string // display only
|
|
|
|
// Hub mode (when Root is set): many projects on one storage root.
|
|
Root remote.Backend
|
|
Projects *ProjectDB
|
|
|
|
// Device identifies this server in ops it journals for browser uploads.
|
|
Device Identity
|
|
Refresh time.Duration
|
|
Upload UploadConfig
|
|
// Auth, when set, gates the whole API behind sign-in. Nil means the
|
|
// historical trusted-network behavior: no accounts, everyone welcome.
|
|
Auth AuthProvider
|
|
// Devices, when set, records what the server observes about syncing
|
|
// devices (name, OS, public IP, last activity) for history.
|
|
Devices *DeviceRegistry
|
|
// Shares, when set, enables public share links (/s/<token>).
|
|
Shares *ShareDB
|
|
// Reads, when set, aggregates read telemetry (viewer, share, and agent
|
|
// reads) for the heat API. Nil means read tracking is off.
|
|
Reads *ReadLedger
|
|
// Dir, when set, walls projects off by organization membership and owns
|
|
// every org read and write the hub performs. LocalDirectory is the
|
|
// built-in implementation; a managed deployment supplies its own so that
|
|
// orgs come from the same place identities do. Nil means single-volume
|
|
// mode: no orgs, every authenticated request passes.
|
|
Dir Directory
|
|
// Quota, when set, enforces plan limits (managed deployments). Nil
|
|
// means UnlimitedQuota: the open-source server never says no.
|
|
Quota QuotaProvider
|
|
// Billing, when set, surfaces a billing entry in the frontend's account
|
|
// menu: the billing page URL plus the signed-in user's current plan name
|
|
// (/api/config `billing`). The OSS hub has no billing; managed
|
|
// deployments plug this in. Nil — or ok=false for a user with no org —
|
|
// hides the entry. The mirror of the Quota seam: Quota enforces the
|
|
// plan, Billing displays it.
|
|
Billing func(email string) (plan, url string, ok bool)
|
|
// Analytics, when its Key is set, tells the frontend to load PostHog
|
|
// (/api/config `analytics`). The third managed-deployment seam beside
|
|
// Quota and Billing, and deliberately server-supplied rather than
|
|
// bundled: with no key the OSS frontend ships no analytics code and
|
|
// makes no third-party request, so a self-hosted hub cannot phone home
|
|
// even by accident.
|
|
Analytics AnalyticsConfig
|
|
// ShareRPM is the per-IP request rate on public share links (/s/*);
|
|
// 0 means DefaultShareRPM.
|
|
ShareRPM int
|
|
// TrustProxy honors X-Forwarded-For from ANY peer. Only needed for a
|
|
// proxy on a public address: a proxy on loopback or a private network is
|
|
// already trusted without it (see clientIP). Setting it on a directly-
|
|
// reachable hub lets any client pick its own rate-limit bucket.
|
|
TrustProxy bool
|
|
|
|
xffWarnOnce sync.Once
|
|
shareLimOnce sync.Once
|
|
shareLim *rateLimiter
|
|
authLimOnce sync.Once
|
|
authLim *rateLimiter
|
|
|
|
volOnce sync.Once
|
|
vol *volume
|
|
|
|
volsMu sync.Mutex
|
|
vols map[string]*volume // hub mode: per-project, keyed by project id
|
|
|
|
resMu sync.Mutex
|
|
grants []grant // outstanding presigned upload reservations (reserve.go)
|
|
|
|
// joinMu serializes invite redemption: the seat check reads the member
|
|
// count and the join adds to it, and two clicks on the same link at the
|
|
// same moment would otherwise both see the last seat free.
|
|
// ponytail: one hub-wide lock; redemption is a rare, human-paced request —
|
|
// make it per-org if that ever stops being true.
|
|
joinMu sync.Mutex
|
|
}
|
|
|
|
// UploadConfig controls whether and how clients may write.
|
|
type UploadConfig struct {
|
|
Enabled bool
|
|
// TTL bounds the lifetime of presigned direct-upload URLs.
|
|
TTL time.Duration
|
|
}
|
|
|
|
// AnalyticsConfig points the frontend at a PostHog project. The key is a
|
|
// public write-only project token, not a credential — it is served to signed-
|
|
// out visitors too, because the app shell loads before login.
|
|
type AnalyticsConfig struct {
|
|
Key string // PostHog project key; empty disables analytics entirely
|
|
Host string // PostHog API host; empty means DefaultAnalyticsHost
|
|
}
|
|
|
|
// DefaultAnalyticsHost is PostHog's US cloud ingestion host.
|
|
const DefaultAnalyticsHost = "https://us.i.posthog.com"
|
|
|
|
// Endpoint is Host with the default applied. Exported because the same
|
|
// config drives more than the app shell in a managed deployment (the cloud
|
|
// module's marketing pages render their own loader from it).
|
|
func (a AnalyticsConfig) Endpoint() string {
|
|
if a.Host != "" {
|
|
return a.Host
|
|
}
|
|
return DefaultAnalyticsHost
|
|
}
|
|
|
|
// DefaultUploadTTL is used when UploadConfig.TTL is unset: long enough for a
|
|
// slow upload, short enough that a leaked URL goes stale quickly.
|
|
const DefaultUploadTTL = 15 * time.Minute
|
|
|
|
func (c UploadConfig) ttl() time.Duration {
|
|
if c.TTL > 0 {
|
|
return c.TTL
|
|
}
|
|
return DefaultUploadTTL
|
|
}
|
|
|
|
// FileInfo is the resolved state of one path: content identity (Blob doubles
|
|
// as the ETag), plus provenance where the source knows it.
|
|
type FileInfo struct {
|
|
Blob string
|
|
Size int64
|
|
Time time.Time
|
|
// User/UserName are the signed-in account behind the change; Author is
|
|
// the git/OS identity an offline device falls back to. History renders
|
|
// the account and falls back to Author, so the viewer needs all three
|
|
// to give the same answer — see whoChanged() in the frontend.
|
|
User string
|
|
UserName string
|
|
Author string
|
|
Device string
|
|
}
|
|
|
|
// volume is one browsable/syncable file set: a source plus its snapshot
|
|
// cache. File listings are cached for refresh between fetches; if the source
|
|
// becomes unreachable, the last good snapshot keeps being served.
|
|
type volume struct {
|
|
source Source
|
|
refresh time.Duration
|
|
|
|
mu sync.Mutex
|
|
snap *snapshot
|
|
at time.Time
|
|
}
|
|
|
|
type snapshot struct {
|
|
files map[string]FileInfo
|
|
}
|
|
|
|
func (v *volume) snapshot(ctx context.Context) (*snapshot, error) {
|
|
v.mu.Lock()
|
|
defer v.mu.Unlock()
|
|
if v.snap != nil && time.Since(v.at) < v.refresh {
|
|
return v.snap, nil
|
|
}
|
|
files, err := v.source.Files(ctx)
|
|
if err != nil {
|
|
if v.snap != nil {
|
|
return v.snap, nil // serve stale rather than fail
|
|
}
|
|
return nil, err
|
|
}
|
|
v.snap, v.at = &snapshot{files: files}, time.Now()
|
|
return v.snap, nil
|
|
}
|
|
|
|
// invalidate forces the next snapshot to refetch, so an upload shows up in
|
|
// the tree immediately instead of after refresh.
|
|
func (v *volume) invalidate() {
|
|
v.mu.Lock()
|
|
v.at = time.Time{}
|
|
v.mu.Unlock()
|
|
}
|
|
|
|
func (v *volume) uploader() Uploader {
|
|
u, _ := v.source.(Uploader)
|
|
return u
|
|
}
|
|
|
|
// single returns the single-volume mode volume.
|
|
func (s *Server) single() *volume {
|
|
s.volOnce.Do(func() {
|
|
s.vol = &volume{source: s.Source, refresh: s.Refresh}
|
|
})
|
|
return s.vol
|
|
}
|
|
|
|
// projectVolume resolves a project id to its record and its volume, creating
|
|
// the (cached) source over the project's storage prefix on first use. It
|
|
// returns the Project so the permission check does not have to resolve the id
|
|
// a second time — see projectPermOf.
|
|
func (s *Server) projectVolume(id string) (Project, *volume, error) {
|
|
if s.Root == nil || s.Projects == nil {
|
|
return Project{}, nil, fmt.Errorf("this server does not host projects")
|
|
}
|
|
if !projectIDRe.MatchString(id) {
|
|
return Project{}, nil, fmt.Errorf("invalid project id %q", id)
|
|
}
|
|
p, ok := s.Projects.Get(id)
|
|
if !ok {
|
|
return Project{}, nil, fmt.Errorf("no such project %q", id)
|
|
}
|
|
s.volsMu.Lock()
|
|
defer s.volsMu.Unlock()
|
|
if s.vols == nil {
|
|
s.vols = make(map[string]*volume)
|
|
}
|
|
v, ok := s.vols[id]
|
|
if !ok {
|
|
v = &volume{
|
|
source: &RemoteSource{
|
|
Backend: remote.Prefixed(s.Root, id), Device: s.Device,
|
|
// The real TTL the presign doors hand out, so verify seals a
|
|
// blob no earlier than the last URL for it can expire.
|
|
PresignTTL: s.Upload.ttl(),
|
|
},
|
|
refresh: s.Refresh,
|
|
}
|
|
s.vols[id] = v
|
|
}
|
|
return p, v, nil
|
|
}
|
|
|
|
// RemoteSource reads a beardrive remote: it fetches every journal and folds the
|
|
// ops into the current volume state (same total order as journal.Replay,
|
|
// but keeping author/device/time of the winning op per path). With Device set
|
|
// it also accepts uploads, journaled under that identity.
|
|
type RemoteSource struct {
|
|
Backend remote.Backend
|
|
// Device identifies this server in ops it journals for uploads. Required
|
|
// for uploads; irrelevant for reading.
|
|
Device Identity
|
|
// PresignTTL is the lifetime the hub gives a presigned upload URL. It is
|
|
// how long a blob stays writable by anyone but the hub, and therefore when
|
|
// verify may stop re-hashing it. Zero means DefaultUploadTTL — set it to
|
|
// the server's real UploadConfig.ttl(), or a longer configured TTL would
|
|
// seal an object that can still change.
|
|
PresignTTL time.Duration
|
|
|
|
upmu sync.Mutex // serializes read-modify-write of our own journal
|
|
// sealed holds the blobs this process has verified AND proved immutable.
|
|
// See verify.
|
|
sealed sync.Map // sha (string) → struct{}
|
|
}
|
|
|
|
// OpenBlob is the one way a blob's bytes leave the hub, and on a hub whose
|
|
// storage can presign it is also the only place left that can tell a content
|
|
// address the truth. handleStorePut hashes what it relays — but a presigned
|
|
// PUT writes straight into the object store, so those bytes were never
|
|
// examined by anything: any device with write permission could store arbitrary
|
|
// content under a sha256 it chose, and the viewer, share links, history and
|
|
// every peer would then serve it.
|
|
//
|
|
// Skipped entirely on a backend that cannot presign, where the write path
|
|
// already checked. It used to be once per blob per process, on the premise
|
|
// that blobs are immutable — which is false on the hub that needs the check:
|
|
// SignPut hands out a URL that stays valid for its whole TTL and an object
|
|
// store accepts every PUT to it, not the first. So uploading the honest bytes,
|
|
// letting one reader populate the cache, and then replaying the same URL with
|
|
// hostile bytes served them under the reviewed sha to the viewer, history,
|
|
// share links and every syncing device.
|
|
//
|
|
// Verifying on EVERY read closed that, and cost every S3/GCS hub 2x object-
|
|
// store egress and a serialized full-object hash before the reader's first
|
|
// byte — on every viewer open, render, download and /s/* hit. The cache is
|
|
// back, keyed on the one thing that makes the premise TRUE rather than assumed:
|
|
// see verify.
|
|
func (r *RemoteSource) OpenBlob(ctx context.Context, sha string) (io.ReadCloser, error) {
|
|
if !blobRe.MatchString(sha) {
|
|
return nil, fmt.Errorf("invalid content reference")
|
|
}
|
|
if err := r.verify(ctx, sha); err != nil {
|
|
return nil, err
|
|
}
|
|
return r.Backend.Get(ctx, "blobs/"+sha)
|
|
}
|
|
|
|
// verify re-hashes a stored blob, unless this process has already proved that
|
|
// nobody but the hub can write it any more.
|
|
//
|
|
// The proof is the presign TTL and the fact that BOTH presign doors —
|
|
// handleStoreSign and handleUploadInit — refuse to sign a key that already
|
|
// exists. So every presigned URL a blob ever gets was minted BEFORE its first
|
|
// PUT, and expires at mint+TTL, which is earlier than firstPUT+TTL. Once the
|
|
// stored object is older than the TTL, no live URL for it can exist and none
|
|
// will ever be minted again: the hub is the only writer left, and the hub
|
|
// hashes what it relays. That is when the object really is immutable, and only
|
|
// then is the verification cached — for the life of the process, keyed on the
|
|
// sha, no expiry needed.
|
|
//
|
|
// The age is read AFTER the hash on purpose. A replay lands a NEW object with
|
|
// a new modification time, so an object that was rewritten mid-check reads as
|
|
// seconds old and is not sealed.
|
|
//
|
|
// Two premises this rests on, both true today and both worth breaking loudly:
|
|
// blobs are never deleted (remote.Backend has no delete at all — history keeps
|
|
// every version forever), and PresignTTL is the real TTL the doors use. A
|
|
// backend that does not report Modified never seals, which is the safe answer.
|
|
//
|
|
// ponytail: per-process, so the first read of each blob after a restart still
|
|
// pays the full hash. Persisting it needs somewhere to record "the hub has
|
|
// seen these bytes", which is a metadata-store change for a cost paid once.
|
|
func (r *RemoteSource) verify(ctx context.Context, sha string) error {
|
|
if _, canSign := r.Backend.(remote.PutSigner); !canSign {
|
|
return nil
|
|
}
|
|
if _, ok := r.sealed.Load(sha); ok {
|
|
return nil
|
|
}
|
|
rc, err := r.Backend.Get(ctx, "blobs/"+sha)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
h := sha256.New()
|
|
_, err = io.Copy(h, rc)
|
|
rc.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if hex.EncodeToString(h.Sum(nil)) != sha {
|
|
return fmt.Errorf("stored content does not hash to its key")
|
|
}
|
|
// sealAfter, not presignTTL: o.Modified is the STORAGE service's clock and
|
|
// time.Since is the hub's. A hub whose clock runs ahead of storage would
|
|
// otherwise overstate the object's age and seal it while a minted URL is
|
|
// still live — after which a replay is served from cache for the life of
|
|
// the process.
|
|
if o, ok, err := r.blobStat(ctx, sha); err == nil && ok &&
|
|
!o.Modified.IsZero() && time.Since(o.Modified) > r.sealAfter() {
|
|
r.sealed.Store(sha, struct{}{})
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// sealAfter is how old a stored blob must be before its verification may be
|
|
// cached: the presign TTL plus an allowance for clock skew between the hub and
|
|
// the object store. The allowance is the whole point — the correctness
|
|
// argument is "no live URL can exist any more", and that is a claim about time
|
|
// measured on two machines the hub cannot reconcile.
|
|
//
|
|
// Waiting longer costs only a few extra hashes on a blob younger than this,
|
|
// which is the behavior the check had for every blob anyway.
|
|
//
|
|
// ponytail: a fixed allowance, so it is a bound and not a proof — a hub whose
|
|
// clock runs more than an hour ahead of its object store can still seal early.
|
|
// Closing it properly means measuring the age on ONE clock (record the hub time
|
|
// of the first verification, seal on a later one that finds Modified
|
|
// unchanged), which costs a second map and never seals on a first read.
|
|
func (r *RemoteSource) sealAfter() time.Duration {
|
|
const skewAllowance = time.Hour
|
|
return r.presignTTL() + skewAllowance
|
|
}
|
|
|
|
// Identity is the device identity uploads are journaled under.
|
|
type Identity struct {
|
|
ID, Name, Author string
|
|
}
|
|
|
|
// loadOps fetches and parses every journal on the remote.
|
|
func (r *RemoteSource) loadOps(ctx context.Context) ([]journal.Op, error) {
|
|
sourced, err := r.loadSourcedOps(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
all := make([]journal.Op, len(sourced))
|
|
for i, s := range sourced {
|
|
all[i] = s.Op
|
|
}
|
|
return all, nil
|
|
}
|
|
|
|
// sourcedOp is an op plus the device whose journal it was actually read from.
|
|
// Everything inside an op — including its Device field — is JSON the pusher
|
|
// chose; the journal KEY is the one part the hub binds to the pushing device
|
|
// (store.go's ownJournal), so From is the only trustworthy attribution.
|
|
type sourcedOp struct {
|
|
Op journal.Op
|
|
From string
|
|
}
|
|
|
|
func (r *RemoteSource) loadSourcedOps(ctx context.Context) ([]sourcedOp, error) {
|
|
objs, err := r.Backend.List(ctx, "journal/")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list journals: %w", err)
|
|
}
|
|
var all []sourcedOp
|
|
for _, o := range objs {
|
|
if !strings.HasSuffix(o.Key, ".jsonl") {
|
|
continue
|
|
}
|
|
rc, err := r.Backend.Get(ctx, o.Key)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("fetch %s: %w", o.Key, err)
|
|
}
|
|
data, err := io.ReadAll(rc)
|
|
rc.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ops, err := journal.Parse(data)
|
|
if err != nil {
|
|
continue // corrupt journal; ignore rather than break the view
|
|
}
|
|
from := strings.TrimSuffix(strings.TrimPrefix(o.Key, "journal/"), ".jsonl")
|
|
for _, op := range ops {
|
|
all = append(all, sourcedOp{Op: op, From: from})
|
|
}
|
|
}
|
|
return all, nil
|
|
}
|
|
|
|
func (r *RemoteSource) Files(ctx context.Context) (map[string]FileInfo, error) {
|
|
all, err := r.loadOps(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
journal.Sort(all)
|
|
files := make(map[string]FileInfo)
|
|
for _, op := range all {
|
|
switch op.Kind {
|
|
case journal.KindPut:
|
|
// A journal is arbitrary JSONL a device pushed: Blob is a storage
|
|
// key suffix ("blobs/"+Blob), not a checked field, so anything but
|
|
// a bare sha256 is a path the writer chose — another project's
|
|
// prefix, or out of the storage root entirely. Same rule as every
|
|
// ?sha= route. An op that fails it is ignored (the path keeps its
|
|
// previous version) rather than treated as a delete.
|
|
if !blobRe.MatchString(op.Blob) {
|
|
continue
|
|
}
|
|
files[op.Path] = FileInfo{
|
|
Blob: op.Blob, Size: op.Size, Time: op.Time,
|
|
User: op.User, UserName: op.UserName,
|
|
Author: op.Author, Device: op.DeviceName,
|
|
}
|
|
case journal.KindDelete:
|
|
delete(files, op.Path)
|
|
}
|
|
}
|
|
return files, nil
|
|
}
|
|
|
|
func (r *RemoteSource) Open(ctx context.Context, _ string, fi FileInfo) (io.ReadCloser, error) {
|
|
// Files already drops ops with a bogus Blob; re-checked in OpenBlob because
|
|
// that is where the key is built, and a FileInfo can reach it from anywhere.
|
|
return r.OpenBlob(ctx, fi.Blob)
|
|
}
|
|
|
|
// Handler returns the HTTP handler: /api/* plus the embedded frontend.
|
|
func (s *Server) Handler() http.Handler {
|
|
static, err := fs.Sub(staticFiles, "static")
|
|
if err != nil {
|
|
panic(err) // embedded FS; cannot fail at runtime
|
|
}
|
|
mux := http.NewServeMux()
|
|
|
|
// One account-removal path, one cleanup. Everything downstream of it is
|
|
// keyed by email, so removal has to take the org role, the project grants
|
|
// and (through membership) the share links with it.
|
|
if a, ok := s.Auth.(*BuiltinAuth); ok && a.Offboard == nil {
|
|
a.Offboard = s.offboard
|
|
}
|
|
// A device identity is bound to an account when its token is minted, and
|
|
// nowhere else. Wired here rather than at startup because the fixtures (and
|
|
// a hub rebuilt from its repos) assemble Auth and Devices independently.
|
|
if a, ok := s.Auth.(*BuiltinAuth); ok && a.BindDevice == nil {
|
|
a.BindDevice = s.bindDevice
|
|
}
|
|
|
|
// Volume resolution per route family: fixed single volume, or by
|
|
// project id in hub mode. One handler implementation serves both.
|
|
// Single-volume mode has no per-project permissions, so it ignores the
|
|
// declared level; hub mode enforces it.
|
|
single := func(_ string, h func(*volume, http.ResponseWriter, *http.Request)) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if s.Source == nil {
|
|
http.Error(w, "this server hosts projects; use /api/p/<project-id>/...", http.StatusNotFound)
|
|
return
|
|
}
|
|
h(s.single(), w, r)
|
|
}
|
|
}
|
|
proj := func(level string, h func(*volume, http.ResponseWriter, *http.Request)) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("project")
|
|
p, v, err := s.projectVolume(id)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusNotFound)
|
|
return
|
|
}
|
|
// p, not id: the resolver has already read the registry once for
|
|
// this request and re-reading it is the hub's per-request cost.
|
|
if !s.requirePermOn(w, r, p, level) {
|
|
return
|
|
}
|
|
// Read recording (and anything else downstream) finds the project
|
|
// id in the context; permission has already passed at this point.
|
|
h(v, w, withProjectID(r, id))
|
|
}
|
|
}
|
|
|
|
mux.HandleFunc("GET /api/config", s.handleConfig)
|
|
mux.HandleFunc("GET /api/projects", s.handleProjectList)
|
|
mux.HandleFunc("POST /api/projects", s.handleProjectCreate)
|
|
mux.HandleFunc("GET /api/projects/{project}", s.handleProjectGet)
|
|
|
|
for prefix, resolve := range map[string]func(string, func(*volume, http.ResponseWriter, *http.Request)) http.HandlerFunc{
|
|
"/api/": single,
|
|
"/api/p/{project}/": proj,
|
|
} {
|
|
mux.HandleFunc("GET "+prefix+"tree", resolve(PermRead, s.handleTree))
|
|
mux.HandleFunc("GET "+prefix+"file", resolve(PermRead, s.handleFile))
|
|
mux.HandleFunc("GET "+prefix+"download", resolve(PermRead, s.handleDownload))
|
|
mux.HandleFunc("GET "+prefix+"render", resolve(PermRead, s.handleRender))
|
|
mux.HandleFunc("POST "+prefix+"upload/init", resolve(PermWrite, s.handleUploadInit))
|
|
mux.HandleFunc("PUT "+prefix+"upload/content", resolve(PermWrite, s.handleUploadContent))
|
|
mux.HandleFunc("POST "+prefix+"upload/commit", resolve(PermWrite, s.handleUploadCommit))
|
|
}
|
|
|
|
mux.HandleFunc("GET /api/orgs", s.handleOrgList)
|
|
mux.HandleFunc("PATCH /api/orgs/{org}", s.handleOrgRename)
|
|
mux.HandleFunc("POST /api/orgs/{org}/invites", s.handleInviteCreate)
|
|
mux.HandleFunc("GET /api/orgs/{org}/invites", s.handleInviteList)
|
|
mux.HandleFunc("DELETE /api/orgs/{org}/invites/{token}", s.handleInviteRevoke)
|
|
mux.HandleFunc("PATCH /api/orgs/{org}/members/{email}", s.handleMemberUpdate)
|
|
mux.HandleFunc("DELETE /api/orgs/{org}/members/{email}", s.handleMemberRemove)
|
|
mux.HandleFunc("GET /api/orgs/{org}/shares", s.handleOrgShares)
|
|
mux.HandleFunc("POST /api/invites/{token}", s.handleInviteAccept)
|
|
|
|
mux.HandleFunc("PATCH /api/projects/{project}", s.handleProjectUpdate)
|
|
mux.HandleFunc("DELETE /api/projects/{project}", s.handleProjectDelete)
|
|
|
|
mux.HandleFunc("GET /api/admin/policy", s.handleAdminPolicy)
|
|
mux.HandleFunc("POST /api/admin/policy", s.handleAdminPolicy)
|
|
mux.HandleFunc("GET /api/admin/pending", s.handleAdminPending)
|
|
mux.HandleFunc("POST /api/admin/pending/{id}/approve", s.handleAdminApprove)
|
|
mux.HandleFunc("POST /api/admin/pending/{id}/deny", s.handleAdminDeny)
|
|
|
|
mux.HandleFunc("GET /api/p/{project}/history", proj(PermRead, s.handleHistory))
|
|
mux.HandleFunc("GET /api/p/{project}/blob", proj(PermRead, s.handleBlob))
|
|
// Restore needs a journal to look the version up in, so it exists only
|
|
// per project — never on the single-volume (DirSource) prefix. Remove
|
|
// writes to that same journal, so it lives here too.
|
|
mux.HandleFunc("POST /api/p/{project}/restore", proj(PermWrite, s.handleRestore))
|
|
mux.HandleFunc("POST /api/p/{project}/remove", proj(PermWrite, s.handleRemove))
|
|
mux.HandleFunc("GET /api/p/{project}/heat", proj(PermRead, s.handleHeat))
|
|
mux.HandleFunc("POST /api/p/{project}/reads", proj(PermRead, s.handleReadReport))
|
|
mux.HandleFunc("POST /api/p/{project}/shares", proj(PermWrite, s.handleShareCreate))
|
|
mux.HandleFunc("GET /api/p/{project}/shares", proj(PermRead, s.handleShareList))
|
|
mux.HandleFunc("PATCH /api/shares/{token}", s.handleShareExpiry)
|
|
mux.HandleFunc("DELETE /api/shares/{token}", s.handleShareRevoke)
|
|
mux.HandleFunc("GET /s/{token}", s.handleShared)
|
|
|
|
mux.HandleFunc("GET /api/p/{project}/permissions", s.handleProjectPerms)
|
|
mux.HandleFunc("PUT /api/p/{project}/permissions", s.handleProjectPermDefault)
|
|
mux.HandleFunc("PUT /api/p/{project}/permissions/{email}", s.handleProjectPermSet)
|
|
mux.HandleFunc("DELETE /api/p/{project}/permissions/{email}", s.handleProjectPermClear)
|
|
|
|
// The sync (store) API only exists per project: hub mode is what
|
|
// storage-blind devices sync through. Reading the store is how a
|
|
// pull-only (read) device stays current; writing needs write.
|
|
mux.HandleFunc("GET /api/p/{project}/store/list", proj(PermRead, s.handleStoreList))
|
|
mux.HandleFunc("GET /api/p/{project}/store/object", proj(PermRead, s.handleStoreGet))
|
|
mux.HandleFunc("GET /api/p/{project}/store/exists", proj(PermRead, s.handleStoreExists))
|
|
mux.HandleFunc("POST /api/p/{project}/store/sign", proj(PermWrite, s.handleStoreSign))
|
|
mux.HandleFunc("PUT /api/p/{project}/store/object", proj(PermWrite, s.handleStorePut))
|
|
|
|
mux.Handle("GET /", s.frontend(static))
|
|
if s.Auth != nil {
|
|
s.Auth.Register(mux)
|
|
}
|
|
return s.rateLimitAuth(s.authGate(mux))
|
|
}
|
|
|
|
// frontend serves the embedded single-page app. Real asset files (app.js,
|
|
// style.css) are served directly; every other GET that isn't an API, auth,
|
|
// or share route returns index.html, so client-side routes like
|
|
// /<project-id>/<path> and /join/<token> survive a deep link or refresh.
|
|
func (s *Server) frontend(static fs.FS) http.HandlerFunc {
|
|
files := http.FileServerFS(static)
|
|
index, _ := fs.ReadFile(static, "index.html")
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
upath := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
|
|
// This document carries the session cookie and drives share creation,
|
|
// permission edits and project deletion, so it must not be framed by
|
|
// another origin or MIME-sniffed. /s/* sets its own sandbox CSP and
|
|
// never reaches here.
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("X-Frame-Options", "DENY")
|
|
w.Header().Set("Content-Security-Policy", "frame-ancestors 'none'")
|
|
// Vite emits content-hashed filenames under assets/, safe to cache
|
|
// forever. Everything else (index.html above all) must revalidate:
|
|
// embedded files carry no modtime, so without no-cache browsers
|
|
// cache heuristically and users see a stale frontend after upgrades.
|
|
// Set on the real asset only, below: deciding on the URL prefix meant
|
|
// a MISS under assets/ answered the app shell marked immutable for a
|
|
// year, so a shared cache pinned index.html at an asset URL forever.
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
// Reserved prefixes that fell through to the catch-all are genuine
|
|
// 404s — don't mask a mistyped API/auth/share URL with the app shell.
|
|
if strings.HasPrefix(upath, "api/") || strings.HasPrefix(upath, "auth/") || strings.HasPrefix(upath, "s/") {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
// A hub whose organizations live elsewhere has no org page to show:
|
|
// send the browser where they are actually administered rather than
|
|
// painting a console whose every control would 409. The account menu
|
|
// already links to the same place; this covers bookmarks, history, and
|
|
// hand-typed URLs, which are the paths a link cannot reach.
|
|
if id, ok := strings.CutPrefix(upath, "orgs/"); ok && s.Dir != nil {
|
|
if u := s.Dir.ManageURL(id); !strings.HasPrefix(u, "/") {
|
|
http.Redirect(w, r, u, http.StatusFound)
|
|
return
|
|
}
|
|
}
|
|
if upath != "" && upath != "index.html" {
|
|
if f, err := static.Open(upath); err == nil {
|
|
fi, statErr := f.Stat()
|
|
f.Close()
|
|
if statErr == nil && !fi.IsDir() {
|
|
if strings.HasPrefix(upath, "assets/") {
|
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
|
}
|
|
files.ServeHTTP(w, r) // a real asset
|
|
return
|
|
}
|
|
}
|
|
}
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
w.Write(index)
|
|
}
|
|
}
|
|
|
|
// handleConfig tells the client how this server is configured. Deliberately
|
|
// nothing about the storage backend.
|
|
func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
|
|
mode := "volume"
|
|
if s.Root != nil {
|
|
mode = "hub"
|
|
}
|
|
auth := map[string]any{"enabled": s.Auth != nil}
|
|
if s.Auth != nil {
|
|
auth["cli_login"] = s.Auth.CLILoginPath()
|
|
}
|
|
// Tell the frontend whether self-signup is offered and whether the
|
|
// signed-in user is a hub admin, so it can hide the "Sign up" link and
|
|
// show the admin surfaces. Never leak more than these booleans.
|
|
me := s.requestUser(r)
|
|
brand := ""
|
|
if a, ok := s.Auth.(AccountApprover); ok {
|
|
// Only a hub that owns its accounts can offer self-signup or an admin
|
|
// queue; one whose identities come from elsewhere offers neither.
|
|
auth["allow_signup"] = a.Policy().AllowSignup
|
|
auth["admin"] = me.Admin
|
|
}
|
|
if b, ok := s.Auth.(Brander); ok {
|
|
brand = b.Branding()
|
|
}
|
|
// No fallback: the volume is a storage basename, not a brand. An
|
|
// unconfigured brand stays empty and each app picks its own default
|
|
// (hub: "BearDrive", volume mode: the folder name).
|
|
out := map[string]any{
|
|
"mode": mode,
|
|
"volume": s.Volume,
|
|
"brand": brand,
|
|
"upload": map[string]any{
|
|
"enabled": s.Upload.Enabled,
|
|
},
|
|
"auth": auth,
|
|
"reads": map[string]any{"enabled": s.Reads != nil},
|
|
// The starting structures the create dialog offers. Served rather
|
|
// than hardcoded in the frontend so a hub that ships another one
|
|
// needs no frontend change.
|
|
"templates": templates.List(),
|
|
}
|
|
// Outside a managed deployment this block is absent and the frontend
|
|
// never loads a tracker. Outside the `me` check on purpose: a hub with
|
|
// auth off has no signed-in user and should still be measurable.
|
|
// Note the funnel gap this leaves — /auth/* is server-rendered HTML
|
|
// (authlocal.go authPage) with no analytics, so a visitor is counted on
|
|
// the marketing page and again once the app boots, but the signup page
|
|
// itself reports nothing. Same origin means the anonymous id survives
|
|
// the round trip, so attribution holds; only signup-page drop-off is
|
|
// invisible. Wire authPage up if that becomes the question.
|
|
if s.Analytics.Key != "" {
|
|
out["analytics"] = map[string]string{"key": s.Analytics.Key, "host": s.Analytics.Endpoint()}
|
|
}
|
|
if me.Email != "" {
|
|
out["me"] = map[string]string{"email": me.Email, "name": me.Name}
|
|
if s.Billing != nil {
|
|
if plan, url, ok := s.Billing(me.Email); ok {
|
|
out["billing"] = map[string]string{"plan": plan, "url": url}
|
|
}
|
|
}
|
|
}
|
|
writeJSON(w, out)
|
|
}
|
|
|
|
func (s *Server) handleProjectList(w http.ResponseWriter, r *http.Request) {
|
|
if s.Projects == nil {
|
|
http.Error(w, "this server does not host projects", http.StatusNotFound)
|
|
return
|
|
}
|
|
// Each row carries the caller's own level, so the frontend can hide write
|
|
// affordances without a second fetch per project on every render.
|
|
visible := []projectView{}
|
|
for _, p := range s.Projects.List() {
|
|
perm := s.projectPermOf(r, p)
|
|
if !atLeast(perm, PermRead) {
|
|
continue
|
|
}
|
|
visible = append(visible, projectJSON(p, perm))
|
|
}
|
|
writeJSON(w, map[string]any{"projects": visible})
|
|
}
|
|
|
|
// projectJSON renders a project for the API with the caller's effective level.
|
|
// projectView is a Project plus the caller's own effective level on it.
|
|
// It embeds rather than re-listing fields on purpose: hand-listing them means
|
|
// every new Project field silently fails to reach the client until someone
|
|
// remembers to add it here.
|
|
type projectView struct {
|
|
Project
|
|
Perm string `json:"perm"`
|
|
}
|
|
|
|
func projectJSON(p Project, perm string) projectView {
|
|
// The grant list and the default belong to /api/p/{id}/permissions, which
|
|
// has its own gate; they'd be noise on every row of every project list.
|
|
p.Perms, p.Default = nil, ""
|
|
return projectView{p, perm}
|
|
}
|
|
|
|
func (s *Server) handleProjectGet(w http.ResponseWriter, r *http.Request) {
|
|
if s.Projects == nil {
|
|
http.Error(w, "this server does not host projects", http.StatusNotFound)
|
|
return
|
|
}
|
|
p, ok := s.Projects.Get(r.PathValue("project"))
|
|
perm := s.projectPermOf(r, p)
|
|
if !ok || !atLeast(perm, PermRead) {
|
|
http.Error(w, "no such project", http.StatusNotFound)
|
|
return
|
|
}
|
|
writeJSON(w, projectJSON(p, perm))
|
|
}
|
|
|
|
// handleProjectCreate creates a project by name, or returns the existing one
|
|
// with that name (create-or-join). Creating is a write, so it follows the
|
|
// upload setting.
|
|
func (s *Server) handleProjectCreate(w http.ResponseWriter, r *http.Request) {
|
|
if s.Projects == nil {
|
|
http.Error(w, "this server does not host projects", http.StatusNotFound)
|
|
return
|
|
}
|
|
if !s.Upload.Enabled {
|
|
http.Error(w, "this server is read-only; projects cannot be created", http.StatusForbidden)
|
|
return
|
|
}
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
Org string `json:"org,omitempty"`
|
|
// Template is the starting structure to seed, "" for an empty
|
|
// project (the historical behavior).
|
|
Template string `json:"template,omitempty"`
|
|
}
|
|
if err := json.NewDecoder(io.LimitReader(r.Body, 1<<16)).Decode(&req); err != nil {
|
|
http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
// Resolve the template before anything is created, so an unknown name
|
|
// leaves no project behind.
|
|
var tpl templates.Template
|
|
if req.Template != "" {
|
|
var err error
|
|
if tpl, err = templates.Get(req.Template); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
}
|
|
org, err := s.orgForCreate(r, req.Org)
|
|
if err != nil {
|
|
if errors.Is(err, ErrManagedElsewhere) {
|
|
// A user with no organization on a hub that cannot create one:
|
|
// send them where organizations actually come from, rather than a
|
|
// 403 naming an org that does not exist.
|
|
s.writeDirErr(w, "", err)
|
|
return
|
|
}
|
|
http.Error(w, err.Error(), http.StatusForbidden)
|
|
return
|
|
}
|
|
p, created, err := s.Projects.GetOrCreate(req.Name, org)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
if created {
|
|
// The creator is the project's first admin. Both writes are
|
|
// best-effort in the sense that a failure leaves a usable project
|
|
// governed by org owners — but report it rather than lie.
|
|
me := normEmail(s.requestUser(r).Email)
|
|
if me != "" {
|
|
if err := s.Projects.SetCreator(p.ID, me); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
// An org owner is already implicitly admin; an explicit grant on
|
|
// one is refused elsewhere, so don't write one here either.
|
|
if s.Dir == nil || org == "" || s.Dir.Role(org, me) != RoleOwner {
|
|
if err := s.Projects.SetPerm(p.ID, me, PermAdmin); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
p, _ = s.Projects.Get(p.ID)
|
|
}
|
|
if tpl.Name != "" {
|
|
// Seeding failure leaves a real, usable project holding part of a
|
|
// template. Say so rather than reporting success; there is no
|
|
// rollback, and deleting a project over a storage hiccup is worse
|
|
// than an honest error.
|
|
if err := s.seedTemplate(r.Context(), p.ID, tpl, s.requestUser(r)); err != nil {
|
|
http.Error(w, fmt.Sprintf("project %s was created, but seeding the %s template failed: %v",
|
|
p.Name, tpl.Name, err), http.StatusBadGateway)
|
|
return
|
|
}
|
|
if err := s.Projects.SetTemplate(p.ID, tpl.Name); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
p, _ = s.Projects.Get(p.ID)
|
|
}
|
|
} else if !atLeast(s.projectPermOf(r, p), PermRead) {
|
|
// GetOrCreate is create-or-join by name: without this, POSTing the
|
|
// name of a project you've been cut off from would hand back its id.
|
|
http.Error(w, permDenied(PermRead), http.StatusForbidden)
|
|
return
|
|
}
|
|
writeJSON(w, map[string]any{"project": projectJSON(p, s.projectPermOf(r, p)), "created": created})
|
|
}
|
|
|
|
// orgForCreate resolves which org a new project lands in: the explicitly
|
|
// requested one (must be a membership), else the caller's only org, else —
|
|
// for an account in no org yet — a fresh org named after the account, so
|
|
// nobody is ever blocked from starting to sync. Orgs disabled → "".
|
|
func (s *Server) orgForCreate(r *http.Request, requested string) (string, error) {
|
|
if s.Dir == nil || s.Auth == nil {
|
|
return "", nil
|
|
}
|
|
me := s.requestUser(r)
|
|
if requested != "" {
|
|
if s.Dir.Role(requested, me.Email) == "" {
|
|
return "", fmt.Errorf("you are not a member of organization %q", requested)
|
|
}
|
|
return requested, nil
|
|
}
|
|
mine := s.Dir.OrgsFor(me.Email)
|
|
if len(mine) > 0 {
|
|
return mine[0].ID, nil
|
|
}
|
|
name := me.Name
|
|
if name == "" {
|
|
name = strings.SplitN(me.Email, "@", 2)[0]
|
|
}
|
|
o, err := s.Dir.Create(name, me.Email)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return o.ID, nil
|
|
}
|
|
|
|
// Node is one entry of the file tree returned by the tree endpoint.
|
|
type Node struct {
|
|
Name string `json:"name"`
|
|
Path string `json:"path"`
|
|
Dir bool `json:"dir"`
|
|
Size int64 `json:"size,omitempty"`
|
|
Time time.Time `json:"time,omitzero"`
|
|
// Same three-field "who" shape as HistoryEntry (history.go), so the
|
|
// frontend has one attribution helper for every surface.
|
|
User string `json:"user,omitempty"`
|
|
UserName string `json:"user_name,omitempty"`
|
|
Author string `json:"author,omitempty"`
|
|
Device string `json:"device,omitempty"`
|
|
Children []*Node `json:"children,omitempty"`
|
|
}
|
|
|
|
func (s *Server) handleTree(v *volume, w http.ResponseWriter, r *http.Request) {
|
|
snap, err := v.snapshot(r.Context())
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
return
|
|
}
|
|
writeJSON(w, buildTree(snap.files))
|
|
}
|
|
|
|
func buildTree(files map[string]FileInfo) *Node {
|
|
root := &Node{Name: "/", Dir: true}
|
|
dirs := map[string]*Node{"": root}
|
|
for _, p := range slices.Sorted(maps.Keys(files)) {
|
|
fi := files[p]
|
|
parent := root
|
|
segs := strings.Split(p, "/")
|
|
for i := 0; i < len(segs)-1; i++ {
|
|
dp := strings.Join(segs[:i+1], "/")
|
|
n, ok := dirs[dp]
|
|
if !ok {
|
|
n = &Node{Name: segs[i], Path: dp, Dir: true}
|
|
dirs[dp] = n
|
|
parent.Children = append(parent.Children, n)
|
|
}
|
|
parent = n
|
|
}
|
|
parent.Children = append(parent.Children, &Node{
|
|
Name: segs[len(segs)-1], Path: p,
|
|
Size: fi.Size, Time: fi.Time,
|
|
User: fi.User, UserName: fi.UserName, Author: fi.Author, Device: fi.Device,
|
|
})
|
|
}
|
|
sortTree(root)
|
|
return root
|
|
}
|
|
|
|
func sortTree(n *Node) {
|
|
sort.SliceStable(n.Children, func(i, j int) bool {
|
|
a, b := n.Children[i], n.Children[j]
|
|
if a.Dir != b.Dir {
|
|
return a.Dir // folders first, like Obsidian
|
|
}
|
|
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
|
|
})
|
|
for _, c := range n.Children {
|
|
if c.Dir {
|
|
sortTree(c)
|
|
}
|
|
}
|
|
}
|
|
|
|
// lookup resolves ?path= against the volume's current snapshot.
|
|
func lookup(v *volume, r *http.Request) (string, FileInfo, int, error) {
|
|
p := r.URL.Query().Get("path")
|
|
if p == "" {
|
|
return "", FileInfo{}, http.StatusBadRequest, fmt.Errorf("missing ?path=")
|
|
}
|
|
snap, err := v.snapshot(r.Context())
|
|
if err != nil {
|
|
log.Printf("beardrive: read project snapshot: %v", err)
|
|
return "", FileInfo{}, http.StatusBadGateway, fmt.Errorf("content temporarily unavailable")
|
|
}
|
|
fi, ok := snap.files[p]
|
|
if !ok {
|
|
return "", FileInfo{}, http.StatusNotFound, fmt.Errorf("no such file: %s", p)
|
|
}
|
|
return p, fi, 0, nil
|
|
}
|
|
|
|
func (s *Server) serveBlob(v *volume, w http.ResponseWriter, r *http.Request, attach bool) {
|
|
p, fi, code, err := lookup(v, r)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), code)
|
|
return
|
|
}
|
|
// Count the read before the ETag check: a 304 render is still a person
|
|
// reading the file, and skipping it would undercount the hottest pages.
|
|
s.recordRead(r, p)
|
|
etag := `"` + fi.Blob + `"`
|
|
if r.Header.Get("If-None-Match") == etag {
|
|
w.WriteHeader(http.StatusNotModified)
|
|
return
|
|
}
|
|
rc, err := v.source.Open(r.Context(), p, fi)
|
|
if err != nil {
|
|
storageErr(w, http.StatusBadGateway, "content temporarily unavailable", err)
|
|
return
|
|
}
|
|
defer rc.Close()
|
|
w.Header().Set("ETag", etag)
|
|
ct := contentType(p)
|
|
w.Header().Set("Content-Type", ct)
|
|
setContentLength(w, rc)
|
|
// nosniff on both branches, the sandbox CSP only on the inline one: an
|
|
// attachment is not rendered, and TestInlineHTMLIsSandboxed pins that
|
|
// /download answers with a disposition INSTEAD of a CSP.
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
if attach {
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", path.Base(p)))
|
|
} else {
|
|
w.Header().Set("Content-Type", inlineType(ct))
|
|
sandboxInline(w, ct)
|
|
}
|
|
io.Copy(w, rc)
|
|
}
|
|
|
|
// setContentLength promises a body length only when the thing about to be
|
|
// streamed can be measured. FileInfo.Size comes off a journal op — JSON a
|
|
// client pushed — so echoing it made the hub promise a length it had no way
|
|
// to keep: a padded or truncated response for every download of that file,
|
|
// declared by anyone who can push a journal. When the source cannot measure
|
|
// (an object store's response body), no header goes out and net/http streams
|
|
// chunked, which is a slightly worse progress bar and a true one.
|
|
func setContentLength(w http.ResponseWriter, rc io.Reader) {
|
|
switch v := rc.(type) {
|
|
case interface{ Stat() (fs.FileInfo, error) }: // *os.File: file:// backend, DirSource
|
|
if fi, err := v.Stat(); err == nil && fi.Mode().IsRegular() {
|
|
w.Header().Set("Content-Length", fmt.Sprint(fi.Size()))
|
|
}
|
|
case interface{ Size() int64 }: // GCS *storage.Reader, bytes.Reader
|
|
w.Header().Set("Content-Length", fmt.Sprint(v.Size()))
|
|
}
|
|
}
|
|
|
|
func (s *Server) handleFile(v *volume, w http.ResponseWriter, r *http.Request) {
|
|
s.serveBlob(v, w, r, false)
|
|
}
|
|
|
|
func (s *Server) handleDownload(v *volume, w http.ResponseWriter, r *http.Request) {
|
|
s.serveBlob(v, w, r, true)
|
|
}
|
|
|
|
func (s *Server) handleRender(v *volume, w http.ResponseWriter, r *http.Request) {
|
|
if sha := r.URL.Query().Get("sha"); sha != "" {
|
|
s.renderVersion(v, w, r, sha)
|
|
return
|
|
}
|
|
p, fi, code, err := lookup(v, r)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), code)
|
|
return
|
|
}
|
|
s.recordRead(r, p)
|
|
rc, err := v.source.Open(r.Context(), p, fi)
|
|
if err != nil {
|
|
storageErr(w, http.StatusBadGateway, "content temporarily unavailable", err)
|
|
return
|
|
}
|
|
src, err := io.ReadAll(rc)
|
|
rc.Close()
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
return
|
|
}
|
|
html, err := RenderMarkdown(src)
|
|
if err != nil {
|
|
http.Error(w, fmt.Sprintf("render: %v", err), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
doc := map[string]any{
|
|
"path": p, "html": html,
|
|
"size": fi.Size, "time": fi.Time, "author": fi.Author, "device": fi.Device,
|
|
}
|
|
// Omitted rather than sent empty, so a journal from before accounts
|
|
// existed still renders its Author instead of a blank attribution.
|
|
if fi.User != "" {
|
|
doc["user"] = fi.User
|
|
}
|
|
if fi.UserName != "" {
|
|
doc["user_name"] = fi.UserName
|
|
}
|
|
writeJSON(w, doc)
|
|
}
|
|
|
|
// renderVersion renders one exact past version by content hash — the
|
|
// markdown counterpart of /blob?sha=, so opening an old .md from history
|
|
// shows a rendered page instead of raw source. Provenance is not returned:
|
|
// the caller already has the history entry it clicked. Viewing history is
|
|
// never a read (see the read-heat invariant), so nothing is recorded.
|
|
func (s *Server) renderVersion(v *volume, w http.ResponseWriter, r *http.Request, sha string) {
|
|
if !blobRe.MatchString(sha) {
|
|
http.Error(w, "invalid sha", http.StatusBadRequest)
|
|
return
|
|
}
|
|
rs := storeSource(v, w)
|
|
if rs == nil {
|
|
return
|
|
}
|
|
rc, err := rs.OpenBlob(r.Context(), sha)
|
|
if err != nil {
|
|
http.Error(w, "no such version", http.StatusNotFound)
|
|
return
|
|
}
|
|
src, err := io.ReadAll(rc)
|
|
rc.Close()
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
return
|
|
}
|
|
html, err := RenderMarkdown(src)
|
|
if err != nil {
|
|
http.Error(w, fmt.Sprintf("render: %v", err), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
writeJSON(w, map[string]any{
|
|
"path": r.URL.Query().Get("path"), "html": html, "size": len(src),
|
|
})
|
|
}
|
|
|
|
// inlineMarkup reports whether a Content-Type names something the browser
|
|
// parses as a DOCUMENT in a top-level navigation, which is what makes it a
|
|
// script-execution vehicle on whatever origin served it.
|
|
//
|
|
// It is deliberately a property and not a list of extensions. The list was the
|
|
// bug: it named text/html, image/svg and *xhtml*, and the whole XML family sat
|
|
// outside it while having exactly the property — an XML document carries its
|
|
// own `<?xml-stylesheet type="text/xsl"?>`, the browser applies the XSLT (the
|
|
// stylesheet is same-origin, the attacker uploads it to the same project) and
|
|
// renders the result, which is HTML, in the hub's origin with the reader's
|
|
// session. Anything that parses as markup belongs here; when in doubt, add it.
|
|
func inlineMarkup(ct string) bool {
|
|
ct = strings.ToLower(ct)
|
|
for _, m := range []string{"text/html", "xhtml", "svg", "/xml", "+xml"} {
|
|
if strings.Contains(ct, m) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// inlineType is the Content-Type the hub is willing to have a browser PARSE
|
|
// when it serves stored bytes inline.
|
|
//
|
|
// The XML family is declared inert. The sandbox CSP below already removes its
|
|
// capability — but it removes it by making the document render as nothing at
|
|
// all (the stylesheet an XML document names is sandboxed too, so the XSLT
|
|
// never runs and there is no document), and "you see nothing" is a poor answer
|
|
// for a reader who clicked a .xml. Declaring it text is both the stronger
|
|
// answer — it needs no CSP support in the browser, and nothing parses a
|
|
// document — and the more useful one: the reader sees the source.
|
|
//
|
|
// HTML, XHTML and SVG keep their real type. The app has always served them,
|
|
// and for them the sandbox is a complete wall rather than a blank page.
|
|
func inlineType(ct string) string {
|
|
l := strings.ToLower(ct)
|
|
if inlineMarkup(l) && !strings.Contains(l, "html") && !strings.Contains(l, "svg") {
|
|
return "text/plain; charset=utf-8"
|
|
}
|
|
return ct
|
|
}
|
|
|
|
// sandboxInline walls off markup the hub serves from its own origin: synced
|
|
// HTML (any flavour), scriptable SVG and the XML family run in an opaque
|
|
// sandboxed origin — same posture as /s/* share pages — so they can never
|
|
// touch the API or the reader's session cookie. Every route that streams
|
|
// stored bytes inline calls this: the live file (serveBlob) and any past
|
|
// version (history's handleBlob), which serve identical content and must not
|
|
// differ in their wall.
|
|
// It also stamps nosniff on every response it sees. The wall above keys off
|
|
// the Content-Type the hub declared; without nosniff a browser is free to
|
|
// sniff attacker-written bytes into a document type the hub never named, which
|
|
// is the same capability arriving through a door the CSP never opened.
|
|
func sandboxInline(w http.ResponseWriter, ct string) {
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
if inlineMarkup(ct) {
|
|
w.Header().Set("Content-Security-Policy", "sandbox allow-scripts")
|
|
}
|
|
}
|
|
|
|
func contentType(p string) string {
|
|
switch strings.ToLower(path.Ext(p)) {
|
|
case ".md", ".markdown":
|
|
return "text/markdown; charset=utf-8"
|
|
case ".txt", ".log", ".go", ".py", ".js", ".ts", ".sh", ".yaml", ".yml", ".toml", ".csv":
|
|
return "text/plain; charset=utf-8"
|
|
case ".json":
|
|
return "application/json"
|
|
}
|
|
if t := mime.TypeByExtension(path.Ext(p)); t != "" {
|
|
return t
|
|
}
|
|
return "application/octet-stream"
|
|
}
|
|
|
|
// storageErr answers a failed storage operation. The detail goes to the log,
|
|
// never to the client: an object-store error names the hub's absolute path
|
|
// (or, on S3, its bucket and key), which no project member has any business
|
|
// learning from a missing file.
|
|
func storageErr(w http.ResponseWriter, code int, msg string, err error) {
|
|
log.Printf("beardrive: %s: %v", msg, err)
|
|
http.Error(w, msg, code)
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(v)
|
|
}
|