Skip to content

fix(api): refuse CORS * without a token and check Host on the loopback API - #50

Merged
mattmattox merged 28 commits into
mainfrom
claude/api-hardening
Nov 10, 2026
Merged

mattmattox merged 28 commits into
mainfrom
claude/api-hardening

Conversation

@mattmattox

@mattmattox mattmattox commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Follow-ups from the shepherd's review of #48, kept out of #48 so #48 stayed as reviewed. #48 has merged, and this PR now targets main. The branch merges main (head ec51891); the diff is these 13 files.

  • Without a token, mount refuses -api-cors '*'. With a token, * goes out as a literal *, responses carry Vary: Origin, and Allow-Methods is GET, HEAD, OPTIONS.
  • A token-less loopback API answers 403 unless the Host header is localhost, 127.x or [::1], which blocks DNS rebinding. With a token or a non-loopback bind, it skips this check.
  • Auth skips only the exact /health and /metrics paths, not their subpaths.
  • Mount validates the API flags before it opens the device, so a bad -api-cors or a missing port stops it with a clear message.
  • doc.go fixes, goclusterfs.BlockSize, and tests for -version, the broadcast warning and the early errors.

Not done: reading the token from a file or env var (it still shows in ps), and caching the bitmap scan behind /api/v1/status.

#49 will need this merged in: both change the middleware chain in NewServer.

Results (.68, head 2174722, before main was merged in):
build, vet, gofmt, go mod tidy -diff, golangci-lint (0 issues), parity and go test -race ./internal/... ./cmd/... all pass. Integration -short: 97 pass, 17 skip, 0 fail, including the 3 new mount tests.

🤖 Generated with Claude Code

mattmattox and others added 26 commits November 10, 2026 12:35
Set up the foundation package structure for the HTTP API server that will
serve the management CLI and web dashboard.

Files created:
- doc.go: Package documentation with endpoint overview
- config.go: Config struct with DefaultConfig(), Validate(), and builder methods
- errors.go: Package-specific error definitions
- types.go: JSON request/response type definitions
- routes.go: Route registration with /health endpoint
- server.go: Server struct with Start/Stop lifecycle
- server_test.go: Comprehensive unit tests (11 tests)

The API server follows existing GoClusterFS patterns:
- Config pattern from internal/cache
- Manager lifecycle pattern from internal/journal
- Dependency injection (no global singletons)

All tests pass (11/11).

Task: #5588
- Add /api/v1/ catch-all handler for versioned endpoints
- Add /metrics endpoint for Prometheus scraping
- Add /api/v1/status endpoint returning server status
- Add /api/v1/stats/* placeholder for component stats
- Add method validation (405 Method Not Allowed)
- Add route tests for all endpoint groups

Task: #5591
- Add LoggingMiddleware that logs method, path, status, duration
- Add AuthMiddleware with Bearer token validation and skip paths
- Add CORSMiddleware with configurable origins and preflight support
- Integrate middleware chain into server (logging -> CORS -> auth)
- Add comprehensive middleware tests (11 new tests)

Task: #5592
- Add HealthStatus constants (ok, degraded, unhealthy)
- Add ComponentHealth for individual health checks
- Enhance StatusResponse with capacity, cluster, mount state
- Add CacheStatsResponse matching internal/cache.Stats
- Add JournalStatsResponse matching internal/journal.JournalStats
- Add IOStatsResponse and StatsOverviewResponse
- Add comprehensive type marshaling tests

Task: #5593
- Add HealthChecker interface for component health reporting
- Add AggregateHealth to combine multiple health check results
- Implement priority: unhealthy > degraded > ok
- Return 503 for unhealthy status, 200 for ok/degraded
- Add RegisterHealthChecker to Server for dependency injection
- Add comprehensive health endpoint tests

Task: #5594
…y info

- Add version.go with build-time ldflags support (Version, GitCommit, BuildTime)
- Add StatusProvider interface for filesystem status injection
- Enhance handleStatus with build info and optional capacity
- Add status endpoint tests with mock provider

Task: #5595
- Add fsStatusProvider to expose filesystem status via API
- Start API server on :8080 after FUSE mount succeeds
- Register health checker and status provider
- Add graceful shutdown in signal handler and exit cleanup

Task: #5596
- Add -api flag to enable/disable API server (default: enabled)
- Add -api-addr for listen address (default: :8080)
- Add -api-token for Bearer token authentication
- Add -api-cors for comma-separated CORS allowed origins
- Wire flags to API server configuration via fluent API

Task: #5597
Add thread-safe accessor method to expose snapshot registry for API
endpoints. Uses RLock since we're only reading the pointer and the
Registry itself manages its own concurrent access with internal mutex.

Task: #5598
Add unified statistics collection and aggregation package:

- stats.go: Core types (Snapshot, CacheStats, JournalStats, etc.)
  and provider interfaces for component decoupling
- collector.go: Collector with TTL-based caching to aggregate
  statistics from multiple providers
- cache.go: Cache state utilities (CacheInfo, CachedSnapshot)
- errors.go: Package-specific error definitions
- doc.go: Package documentation
- stats_test.go: Comprehensive unit tests (16 tests)

The collector uses a pull model where providers are queried on
demand, with configurable cache TTL to avoid expensive repeated
queries. Preset configs available for different use cases:
DefaultConfig (1s TTL), HighFrequencyConfig (100ms), LowOverheadConfig (10s).

Task: #5599
Add comprehensive statistics types for TRIM operations, Sparse File
Bitmap allocation, and cluster node information:

- TrimStats: TRIM/discard operation metrics
- SFBStats: block allocation and fragmentation stats
- ClusterInfo: node role, state, and peer information
- PeerInfo: individual peer node details

Also add provider interfaces and Collector support for all new types.

Task: #5600
…sfb, cluster

- Add StatsProvider interface for statistics collection
- Implement /api/v1/stats endpoints:
  - /stats (overview with cache and journal)
  - /stats/cache (inode, extent, negative cache hit rates)
  - /stats/journal (transactions, space, checkpoints)
  - /stats/trim (TRIM operations and bytes)
  - /stats/lock (lock hint cache statistics)
  - /stats/sfb (block allocation statistics)
  - /stats/cluster (node membership and peers)
  - /stats/all (combined snapshot of all stats)
- Add response types for all stats endpoints
- Add comprehensive tests for stats handlers

Task: #5602, #5603, #5604, #5605, #5606, #5607
CI fails on unformatted files. Whitespace and import order only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t a token

The API listened on :8080 on every interface with no auth, so any host
that could reach the node could read cluster state. -api-addr now
defaults to 127.0.0.1:8080. Mount exits before touching the device when
-api-addr can be reached from other hosts and -api-token is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Broadcast is on by default and its secret is empty by default, so most
clusters accept unauthenticated invalidation and peer messages without
knowing it. Mount now logs a WARNING line before it opens the device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/api kept its own Version, GitCommit and BuildTime, which
scripts/dist.sh never set, so /api/v1/status always said "dev".
GetBuildInfo now reads internal/version, and goclusterfs-mount -version
prints the same string as goclusterfs-fsck -version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
golangci-lint flagged mockFilesystemProvider as unused. Use it in a test
of SetFilesystemProvider instead of deleting it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
allocateImage opens an existing file, so the refusal test failed before
it ran the mount.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the API port is taken, mount logged a second warning at unmount
("api: server not started"). Every mount after the first on a host
hits this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #48 found three ways around the loopback default:
- CORS "*" echoed any Origin, so with no token any web page open on the
  node could read the API. CheckExposure now refuses "*" without a token,
  "*" is sent as a literal, responses carry Vary: Origin, and only GET,
  HEAD and OPTIONS are allowed.
- A token-less loopback server accepted any Host header, so a
  DNS-rebinding page could reach it. It now answers 403 unless Host is
  localhost, 127.x or [::1].
- Auth skipped /health/... and /metrics/... too. Only the exact paths
  skip it now.

doc.go no longer says /health always returns 200 or that only /health
skips auth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Validate ran only after the mount, so a bad -api-cors became a warning
and -api-addr without a port got the misleading "other hosts can reach"
error. Mount now validates first and names the right fix for each
refusal. Adds tests for -version, the broadcast-secret warning and these
early errors. Also uses goclusterfs.BlockSize for status capacity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main's tree equals #48's last head, already merged in the parent commit.
@mattmattox
mattmattox changed the base branch from claude/land-api-work-c8b883 to main November 10, 2026 19:53
mattmattox and others added 2 commits November 10, 2026 13:55
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MountedFS.Format sends fusermount -u without waiting and then kills the
mount, which can leave a dead FUSE mount behind. On a loaded .68 the
next mount then failed with "failed to access mountpoint: Permission
denied". Passing -format to Mount avoids the second process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mattmattox
mattmattox merged commit 1c60b28 into main Nov 10, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant