Files
OwnCord/Server/api/invite_handler.go
T
J3vbandClaude Fable 5 2b2d58abc1 feat(b2-6): safe audit coverage (S-02) (#1441)
* docs(b2-6): enumerate the security-sensitive mutations and their audit coverage

Step 1 of B2-6: the mutation inventory crossed with the 43 non-test
Audit( call sites at 67fdd18d, recorded in the plan's evidence block.
Invite create/revoke (S-02) and plugin install/uninstall have no audit
row; no timeout mutation exists (kick is force_logout / voice_mod_kick).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rg9QQWVN3E5UUgBD2dydtu

* added new doc

* docs(audit): update changelog and security documentation to include admin panel actions in audit log

* feat(b2-6): audit every security-sensitive mutation, invite and plugin rows first (S-02)

Step 2 of B2-6. TestAuditCoverage_* in service, api and admin drive each
mutation from the plan's inventory against a fake db.AuditStore
(Server/db/audittest) and assert the expected action arrives. Red before
this commit on exactly four rows: invite_create, invite_revoke,
plugin_install, plugin_uninstall.

- InviteService writes invite_create / invite_revoke naming the invite by
  id, never by code; RevokeInvite now takes the actor, threaded from the
  handler. A failed revoke writes nothing (test).
- The plugin admin handler takes a db.Auditor and writes plugin_install /
  plugin_uninstall against the RequireAdminAuth principal
  (admin.ActorIDFromContext, exported for that).
- docs/security.md lists the four new actions; CHANGELOG under Unreleased.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rg9QQWVN3E5UUgBD2dydtu

* test(b2-6): denylist over the recorded audit detail corpus

Step 3 of B2-6. Each TestAuditCoverage_* table now ends with a subtest
that runs audittest.AssertSafeDetails over every entry its rows recorded:
a shape denylist (bcrypt/argon2 hashes, password=/token=/secret=/
recovery-code key-value leaks, otpauth URIs, Bearer credentials) plus the
fixture's own secrets (raw tokens, passwords and hashes, TOTP secrets and
codes, invite codes, message bodies). audittest_test.go proves each class
bites and that ordinary details pass. Zero hits on the corpus at HEAD, so
no call site needed changing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rg9QQWVN3E5UUgBD2dydtu

* docs(b2-6): record pre-squash SHAs, red/green and denylist evidence

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rg9QQWVN3E5UUgBD2dydtu

* fix(b2-6): audit committed invites on a canceled request; 404 unknown plugin uninstall

Codex P2s on #1441, both test-first:
- CreateInvite read the invite back on the request context, so a cancel
  after the insert committed returned an error and skipped invite_create.
  The read-back and audit now run on context.WithoutCancel, like the
  password-change tail. TestCreateInvite_AuditSurvivesCanceledLookup.
- Registry.UninstallPlugin is idempotent on an unknown id, so the handler
  wrote plugin_uninstall for plugins that never existed. It now checks the
  row first: 404 and no audit. TestPluginsHandlerUninstallUnknownID.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rg9QQWVN3E5UUgBD2dydtu

* docs(b2-6): record the Codex review outcome on #1441

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rg9QQWVN3E5UUgBD2dydtu

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 11:11:37 +02:00

138 lines
3.8 KiB
Go

package api
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/J3vb/OwnCord/Server/db"
"github.com/J3vb/OwnCord/Server/permissions"
"github.com/J3vb/OwnCord/Server/service"
"github.com/go-chi/chi/v5"
)
// 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(r.Context(), 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(r.Context(), 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) {
user, ok := r.Context().Value(UserKey).(*db.User)
if !ok || user == nil {
writeJSON(w, http.StatusUnauthorized, errorResponse{
Error: "UNAUTHORIZED", Message: "not authenticated",
})
return
}
code := chi.URLParam(r, "code")
if err := svc.Invites.RevokeInvite(r.Context(), user.ID, code); err != nil {
writeServiceError(r.Context(), 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,
}
}