mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
Fixes all 109 golangci-lint findings (106 contextcheck, 1 gocritic,
2 gosec) that accumulated after D2 wired dbgen (whose queries take ctx)
under ctx-less db.DB wrappers while CI lint was quota-dead. No nolint
comments added; every finding fixed by genuinely threading context.
- db: all 138 hand-written db.DB methods take ctx first; the dbCtx()
Background shim is deleted; raw Query/QueryRow/Exec/Begin use their
Context variants; the four redundant ctx-less passthroughs removed.
db.Auditor/WriteAudit gain ctx.
- Seams: permissions.Checker (DB iface, HasChannelPerm,
RequireChannelAccess) and the service.Store interface mirror the new
signatures (ws.EventStore and plugin.PluginStore already did).
- Callers: api/admin handlers use r.Context(); ws per-message paths use
the connection ctx via DispatchV2; hub loops and startup wiring use
context.Background(); service methods thread ctx where they have one
and Background where no ctx exists. Public service surface reached by
ctx-holding chains (PermissionService.HasChannelPerm/GetRoleForUser/
RequireChannelAccess, message/dm/block/invite/profile methods) is now
ctx-first.
- Detached (context.WithoutCancel) where cancellation would break an
invariant, found by a 3-lens adversarial review of the diff:
* voice-leave background retries (a dead webhook/connection ctx killed
retry 2 before it ran, leaving ghost capacity-holding voice rows)
* rollbackVoiceJoin's compensating delete (its trigger IS the cancel)
* post-2FA-change DeleteOtherSessions and logout DeleteSession (the
security tail of a committed change must not die with the request)
* all api/ws audit writes (a banned user could suppress their own
login_blocked_banned row by aborting the request mid-bcrypt)
* admin backup VACUUM INTO (an interrupt left a truncated .db that
the backup list presented as restorable)
* post-commit message/edit refetches (a committed message must still
fan out when the sender disconnects)
* hub settings-cache refresh (one dead connection could pin stale
values for the 30s TTL)
- gocritic rangeValCopy fixed (index iteration); gosec G306 excluded in
config with justification (generated source must stay world-readable)
instead of flipping genprotocol output to 0o600.
Verified: gofmt/vet, all four build-tag variants, full suite, deadlock
pass, full -race pass, golangci-lint 0 issues uncapped.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
131 lines
3.6 KiB
Go
131 lines
3.6 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/owncord/server/db"
|
|
"github.com/owncord/server/permissions"
|
|
"github.com/owncord/server/service"
|
|
)
|
|
|
|
// createInviteRequest is the JSON body for POST /api/v1/invites.
|
|
type createInviteRequest struct {
|
|
MaxUses int `json:"max_uses"`
|
|
ExpiresInHours int `json:"expires_in_hours"`
|
|
}
|
|
|
|
// inviteResponse is the API shape for an invite.
|
|
type inviteResponse struct {
|
|
ID int64 `json:"id"`
|
|
Code string `json:"code"`
|
|
MaxUses *int `json:"max_uses"`
|
|
Uses int `json:"uses"`
|
|
ExpiresAt *string `json:"expires_at"`
|
|
Revoked bool `json:"revoked"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
// MountInviteRoutes registers invite endpoints on the given router.
|
|
// All routes require authentication and MANAGE_INVITES permission.
|
|
func MountInviteRoutes(r chi.Router, database *db.DB, svc *service.Services) {
|
|
r.Route("/api/v1/invites", func(r chi.Router) {
|
|
r.Use(AuthMiddleware(database))
|
|
r.Use(RequirePermission(permissions.ManageInvites))
|
|
|
|
r.Post("/", handleCreateInvite(svc))
|
|
r.Get("/", handleListInvites(svc))
|
|
r.Delete("/{code}", handleRevokeInvite(svc))
|
|
})
|
|
}
|
|
|
|
// handleCreateInvite processes POST /api/v1/invites.
|
|
func handleCreateInvite(svc *service.Services) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req createInviteRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
if err != io.EOF {
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
|
Error: "BAD_REQUEST", Message: "malformed JSON body",
|
|
})
|
|
return
|
|
}
|
|
req = createInviteRequest{}
|
|
}
|
|
|
|
user, ok := r.Context().Value(UserKey).(*db.User)
|
|
if !ok || user == nil {
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
Error: "UNAUTHORIZED", Message: "not authenticated",
|
|
})
|
|
return
|
|
}
|
|
|
|
// H-4: Cap invite expiration to 30 days.
|
|
if req.ExpiresInHours > service.MaxInviteExpiryHours() {
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
|
Error: "BAD_REQUEST",
|
|
Message: fmt.Sprintf("expires_in_hours cannot exceed %d (30 days)", service.MaxInviteExpiryHours()),
|
|
})
|
|
return
|
|
}
|
|
|
|
inv, err := svc.Invites.CreateInvite(r.Context(), user.ID, req.MaxUses, req.ExpiresInHours)
|
|
if err != nil {
|
|
writeServiceError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, toInviteResponse(inv))
|
|
}
|
|
}
|
|
|
|
// handleListInvites processes GET /api/v1/invites.
|
|
func handleListInvites(svc *service.Services) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
invites, err := svc.Invites.ListInvites(r.Context())
|
|
if err != nil {
|
|
writeServiceError(w, err)
|
|
return
|
|
}
|
|
|
|
resp := make([]inviteResponse, 0, len(invites))
|
|
for _, inv := range invites {
|
|
resp = append(resp, toInviteResponse(inv))
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
}
|
|
|
|
// handleRevokeInvite processes DELETE /api/v1/invites/:code.
|
|
func handleRevokeInvite(svc *service.Services) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
code := chi.URLParam(r, "code")
|
|
if err := svc.Invites.RevokeInvite(r.Context(), code); err != nil {
|
|
writeServiceError(w, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
// toInviteResponse converts a db.Invite to the API response shape.
|
|
func toInviteResponse(inv *db.Invite) inviteResponse {
|
|
var maxUses *int
|
|
if inv.MaxUses != nil {
|
|
v := *inv.MaxUses
|
|
maxUses = &v
|
|
}
|
|
return inviteResponse{
|
|
ID: inv.ID,
|
|
Code: inv.Code,
|
|
MaxUses: maxUses,
|
|
Uses: inv.Uses,
|
|
ExpiresAt: inv.ExpiresAt,
|
|
Revoked: inv.Revoked,
|
|
CreatedAt: inv.CreatedAt,
|
|
}
|
|
}
|