gosec G101 flags apiTokenCtxKey, apiTokenLastUsedCtxKey, and the
ScopeNotificationGroupWrite identifier as hardcoded credentials. They are
context-key names and a scope string, not secrets. Annotate them with
#nosec G101 (matching the existing JWTSecretEnvKey precedent) so the
gosec CI step passes without disabling the rule globally.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
- ServeRPC now applies real-IP + WAF interceptors to streaming RPCs
(RequestTask, IOStream), not just unary calls; without them
authHandler.check saw an empty real IP so brute-force BlockIP counters
never keyed on a source and the WAF block table was bypassed at the
stream entrypoint. Factored real-IP resolution into ctxWithRealIP shared
by unary and stream paths.
- handleFsRead rejects negative offset/length; handleFsWrite validates
if_match_sha256 is 64 hex chars before dispatch.
- createAPIToken always verifies each server_id exists (even for admins),
so an admin cannot bind a PAT to a not-yet-created server id that a
future server would auto-inherit.
- Add relay zero-length-chunk rejection regression test.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
- consumeTransferToken now recomputes and constant-time compares the
entry's HMAC-SHA256; previously the signature was minted but never
checked, so the documented "防篡改" guarantee was hollow and security
rested solely on the sync.Map key's randomness.
- CSRF switches from a raw-random double-submit cookie to a signed token
(nonce.HMAC-SHA256 keyed by JWTSecretKey). The middleware now also
validates the signature, defeating sibling-subdomain cookie tossing
where a naive header==cookie pair would otherwise pass.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
GHSA-x6fg-52vr-hj4w: NAT is a commonHandler any authenticated member can
create, and newHTTPandGRPCMux matches r.Host against NAT before dispatching
the dashboard/gRPC handlers, so a member could register the dashboard's own
host as a NAT Domain and hijack global routing. Add IsReservedDashboardHost
(InstallHost/ListenHost plus an operator-declared ReservedHosts list for
reverse-proxy deployments), reject reserved hosts on create/update, and drop
pre-planted records when building the startup cache.
GHSA-39g2-8x68-pmx8: bind-time CheckPermission let a member pre-bind a DDNS
profile ID that the victim would only create later. GetDDNSProvidersFromProfiles
now re-validates ownership by server owner UID and skips foreign-owned
profiles (UserID==0 is treated as a migration artifact, not an admin grant).
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
Introduce Personal Access Tokens (nzp_*) as a stateless auth path alongside
JWT, gated per-endpoint by a scope middleware (nezha:{resource}:{verb}) with
fail-closed empty-scope defaults and a server-id whitelist. Self-management
endpoints (profile, api-tokens, oauth2 bind, refresh-token) explicitly reject
PATs to block privilege-escalation chains. A revoke registry tears down active
long-lived connections (terminal, fm, ws, transfer, mcp) the moment a PAT is
deleted, with a tombstone closing the revoke->register race.
Add an MCP endpoint that proxies tool calls (exec, fs read/write/delete,
transfer) to agents over gRPC, guarded by origin/DNS-rebinding checks, a
per-token rate limiter, audit logging, and a kill switch. Serialize all
sends through the IOStream wrapper to honour grpc-go's concurrency contract.
Add CSRF double-submit protection on unsafe cookie-authenticated methods,
exempting authenticated PAT requests by context identity (not a forgeable
Authorization header). Apply visibility/whitelist filtering consistently
across list, get-by-id, and mutate paths to enforce tenant isolation.
Migrate legacy mcp:* scopes: rewrite read/exec to nezha:* equivalents and
drop dangerous write/delete/wildcard grants.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
listServerGroup returned every group, including ones whose only
servers are HideForGuest=true (or that have zero members), to
unauthenticated callers. The group name itself is then leaked to
guests even though every server it references is hidden from them.
Guest visitors now only see groups that contain at least one guest-
visible server. Authenticated members and admins keep full visibility
(including their own empty groups) so management UI still works.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
GET /api/v1/file?id=<server> created an FM stream on the agent stream
and committed real state change (TaskTypeFM dispatched). With JWT
cookie SameSite=Lax a victim's browser would still send the cookie on
a top-level cross-site GET, so an attacker could trick a logged-in
user into opening an FM session on any of their own servers, consuming
resources and triggering the agent's FM machinery without consent.
Mirror the GHSA-8qhj-4f8c-j8qg fix: move the route to POST. SameSite=
Lax cookies are not sent on cross-site POST. Frontend (admin-frontend)
adjusted in a follow-up commit.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
GHSA-vrmh-5mmx-hjwx: GET /api/v1/server/:id/service and
GET /api/v1/service/:id/history both iterate the raw service list and
emit ServiceName / timing for any service that happens to monitor the
queried server, ignoring the owner's EnableShowInService=false flag.
Both routes are on optionalAuth, so unauthenticated visitors could
enumerate hidden services by name and timing.
Introduce userCanViewService(c, service):
- EnableShowInService=true -> always visible
- admin -> always visible
- authenticated owner -> visible (HasPermission)
- everyone else -> hidden
getServiceHistory rejects unknown-or-invisible service with the same
'service not found' message so the endpoint cannot be used as an
oracle. listServerServices pre-filters the sorted service list.
Owners and admins keep their existing visibility into their own hidden
services.
Tests:
- TestUserCanViewServiceVisibleServiceIsPublic
- TestUserCanViewServiceHiddenServiceRejectsGuest
- TestUserCanViewServiceHiddenServiceRejectsForeignMember
- TestUserCanViewServiceHiddenServiceAllowsOwner
- TestUserCanViewServiceHiddenServiceAllowsAdmin
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
GHSA-8qhj-4f8c-j8qg: GET /api/v1/cron/:id/manual changed shared state
on the agent stream, and the JWT cookie is SameSite=Lax so a victim's
browser would send the cookie on a top-level cross-site GET. An
attacker could trick a logged-in user into firing any of their own
cron commands.
Switch the route to POST: SameSite=Lax cookies are not sent on cross-
site POST, closing the CSRF window without introducing a new token.
Tests:
- TestCronManualTriggerRejectsCrossSiteGET locks in that GET no longer
resolves.
- TestCronManualTriggerAcceptsSameSitePOST locks in the legitimate POST
still works.
Frontend (admin-frontend) updated in a follow-up commit.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
Replace the {user_id, ip} claim pair with {keyId, uid}:
- keyId is a 32-byte random id that points to a row in the new
jwt_sessions table holding the real user id, bound IP, UA hash,
TokenVersion and expiry.
- uid is the user id encoded through pkg/idcodec; mismatch between
claim uid and session.UserID trips WAF block on the caller IP.
- identityHandler now rejects unknown/revoked/expired sessions, IP
drift and stale TokenVersion. Refresh updates session.ExpiresAt.
User.TokenVersion bumps on password change and revokes outstanding
sessions, so a leaked JWT secret alone is no longer enough to forge
a token. JWTSession rows are GC'd every 10 minutes (expired + grace
or revoked >24h). OAuth2 callback shares the same issue path.
Includes regression tests for happy path, mismatched claim uid,
revoked session, TokenVersion bump, IP drift and unknown keyId.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
- Set GinJWTMiddleware.SigningAlgorithm to "HS256" explicitly so a future
library default change (or an alg:none confusion attempt) cannot weaken
token validation. This matches the current gin-jwt default, so behaviour
is unchanged.
- Set CookieSameSite to Lax: same as the modern-browser default, but
pinned so server-side intent is clear and CSRF on cross-site POST is
blocked while top-level GET (OAuth callback) still works.
- Move the nz-o2s OAuth2 state cookie into writeOauth2StateCookie and
set HttpOnly=true. The frontend does not read this cookie, so HttpOnly
is strictly an XSS-hardening win with no behaviour change.
JWT Cookie HttpOnly/Secure are intentionally left default for now: the
frontend reads \`!!document.cookie\` to display login state and many
deployments terminate TLS at an upstream proxy — flipping those would
require a coordinated frontend change.
Co-authored-by: naiba/CloudCode <hi+cloudcode@nai.ba>
The previous loop only checked ownership inside the
\`server != nil && server.TaskStream != nil\` branch. A foreign online
server returned permission denied for the whole batch while foreign
offline / unknown IDs silently went into the Offline bucket — the
response-shape delta let a RoleMember enumerate other users' online
server IDs by submitting them in batches.
Drop both foreign and unknown IDs silently into the Offline bucket
(without dispatching the upgrade task) so the response is indistinguishable
across those three states.
Co-authored-by: naiba/CloudCode <hi+cloudcode@nai.ba>
createTerminal and createFM correctly check server ownership before
issuing a stream UUID, but terminalStream and fmStream only verified
that the UUID existed. Any authenticated user holding a valid stream
UUID could attach to it, gaining the original creator's live shell or
file-manager session — and the UUID is exposed via URL path (referer
leaks, access logs, browser history, frontend error reporters).
Bind the creator user ID into ioStreamContext at CreateStream time,
expose StreamOwnership and IsStreamAuthorizedForUser, and check
ownership in terminalStream/fmStream before the WebSocket upgrade so a
rejected attempt does not tear down the legitimate stream via defer.
NAT streams are also routed through CreateStream(_, 0); they are not
reachable from /ws/terminal or /ws/file so a sentinel user ID is fine.
Co-authored-by: naiba/CloudCode <hi+cloudcode@nai.ba>
* feat: tsdb
* fix(ci): remove --parseGoList=false from swag init to fix dependency resolution
* fix(ci): fix swag init directory and temporary remove s390x support due to cgo issues
* fix(ci): fix swag init output directory to cmd/dashboard/docs
* fix(ci): set GOTOOLCHAIN=auto for gosec
* feat: add system storage maintenance for SQLite and TSDB
* shit
* feat: add s390x support and improve service monitoring
* ci: upgrade goreleaser-cross image to v1.25
* ci: add libzstd-dev:s390x for cross-compilation
* ci: build libzstd for s390x from source
* ci: add libzstd_linux_s390x.go for gozstd linking
* ci: use vendor mode for s390x gozstd build
* ci: clone zstd source for s390x build
* refactor(tsdb): rename MaxDiskUsageGB to MinFreeDiskSpaceGB and optimize queries
- Rename config to accurately reflect VictoriaMetrics behavior: minimum free disk space threshold
- Add QueryServiceHistoryByServerID for batch query optimization
- Fix hasStatus to avoid false status counting when only delay data exists
- Fix service aggregation boundary: use successCount*2 >= count
- Fix serviceID parsing with strconv.ParseUint error handling
- Add TagFiltersCacheSize for better query performance
* feat(api): add server metrics endpoint and simplify service history response
- Add /server/:id/metrics API for querying TSDB server metrics
- Simplify getServiceHistory by removing redundant data conversion
- Change AvgDelay type from float32 to float64
- Remove generated swagger docs (to be regenerated)
- Update TSDB query, writer and tests
* chore: 临时禁用不支持前端
* ci: cache zstd build for s390x to speed up CI
* fix(tsdb): fix race conditions, data correctness and optimize performance
- Fix TOCTOU race between IsClosed() and write/query by holding RLock
- Fix delay=0 excluded from stats by using hasDelay flag instead of value > 0
- Fix fmt.Sscanf -> strconv.ParseUint for server_id parsing with error logging
- Fix buffer unbounded growth by flushing inside lock when over maxSize
- Split makeMetricRow into makeServerMetricRow/makeServiceMetricRow
- Extract InitGlobalSettings() from Open() for VictoriaMetrics globals
- Remove redundant instance/GetInstance/SetInstance singleton
- Add error logging for silently skipped block decode errors
- Optimize WriteBatch* to build all rows in single write call
- Optimize downsample to use linear scan instead of map for sorted data
- Optimize query slice reuse across block iterations
* 服务添加DisplayIndex (#1166)
* 服务添加DisplayIndex
* 根据ai建议修改
---------
Co-authored-by: huYang <306061454@qq.com>
* fix(tsdb): restore SQLite fallback and monthly status reload on restart
- Restore ServiceHistory model and SQLite write fallback when TSDB is disabled
- Reload monthlyStatus (30-day) and serviceStatusToday from TSDB/SQLite on startup
- Add SQLite fallback query for /service/:id/history and /server/:id/service
- Remove breaking GET /service/:id endpoint, keep /service/:id/history only
- Add QueryServiceDailyStats to TSDB for per-day aggregation
- Add tests for monthly status and today stats loading from both TSDB and SQLite
- Migrate ServiceHistory table only when TSDB is disabled
* ci: exclude false-positive gosec rules G117, G703, G704
* feat(api): expose tsdb_enabled in setting response
* ci: restore G115 exclusion accidentally dropped in previous commit
* fix: update version numbers for OfficialAdmin and Official templates
* chore: upgrade frontend
* chore: upgrade frontend
---------
Co-authored-by: 胡说丷刂 <34758853+laosan-xx@users.noreply.github.com>
Co-authored-by: huYang <306061454@qq.com>
* test(deps): use self admin-frontend
* feat: separate real ip header of frontend/agent
* test(ci): test
* Revert "test(ci): test"
This reverts commit 1634c7e7d7bca2873c13955abb582ea88645844f.
* test(ci): test
* test(ci): test
* test(ci): test
* Revert "test(ci): test"
This reverts commit 8fce20a07e5a9503f665937337050d4373ca7e78.
* Revert "test(ci): test"
This reverts commit 3267cccbfb81776a711e8cb34e676536f0852d1c.
* Revert "test(ci): test"
This reverts commit 566660c0c6a9875864aa46537bcc6788769337eb.
* Revert "test(deps): use self admin-frontend"
This reverts commit 16a838b374ff040800b2c1c5f8e5ede577645669.
* feat: support listening https
* refactor
* modernize
* support snake case in config
* more precise control of config fields
* update goreleaser config
* remove kubeyaml
* fix: expose agent_secret
* chore