feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders
- feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders - feat(cli): add check and audit commands - feat(api): add api framework, login, page routes and account, user, delegation and audit handlers - test(auth): cover passwords, sessions, rate limiter, authorization and audit builders - test(api): cover the api framework, sessions, client origin, headers and cross-origin refusal - test(api): cover account, user, delegation and audit handlers and the authorization matrix - test(ui): cover login, logout, page routes and the page authorization matrix
This commit is contained in:
1 parent
23bec143e3
commit
99fa5de747
28 files changed
+6591
-243
No files matched your search
+723
@@ -11,12 +11,735 @@ import (
|
||||
"errors"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
msgOwnAccount = "use the account page to change your own account"
|
||||
msgLastActiveAdmin = "the last active admin cannot be demoted or deleted"
|
||||
msgUsernameTaken = "username already used"
|
||||
msgDelegationAbsent = "delegation not found"
|
||||
msgWrongPassword = "current password is wrong"
|
||||
msgConfirmMismatch = "confirmation does not match"
|
||||
)
|
||||
|
||||
func frameworkAPIHandlers(s *WebServer) map[string]apiHandler {
|
||||
return map[string]apiHandler{
|
||||
opAccountRead: handleAccountRead,
|
||||
opPasswordChange: handlePasswordChange,
|
||||
opDelegationList: handleDelegationList,
|
||||
opDelegationGrant: handleDelegationGrant,
|
||||
opDelegationRevoke: handleDelegationRevoke,
|
||||
opUserList: handleUserList,
|
||||
opUserCreate: handleUserCreate,
|
||||
opUserRead: handleUserRead,
|
||||
opUserRole: handleUserRole,
|
||||
opUserPassword: handleUserPassword,
|
||||
opUserDelete: handleUserDelete,
|
||||
opAuditRead: handleAuditRead,
|
||||
}
|
||||
}
|
||||
|
||||
func apiTime(t time.Time) string {
|
||||
return t.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
func apiNullTime(t sql.NullTime) *string {
|
||||
if !t.Valid {
|
||||
return nil
|
||||
}
|
||||
s := apiTime(t.Time)
|
||||
return &s
|
||||
}
|
||||
|
||||
func noContent() apiResponse {
|
||||
return apiResponse{Status: http.StatusNoContent}
|
||||
}
|
||||
|
||||
func okJSON(body any) apiResponse {
|
||||
return apiResponse{Status: http.StatusOK, Body: body}
|
||||
}
|
||||
|
||||
func badParameter(name string) *apiError {
|
||||
return &apiError{Status: http.StatusBadRequest, Message: "invalid parameter " + name}
|
||||
}
|
||||
|
||||
func ownAccountError() *apiError {
|
||||
return &apiError{Status: http.StatusForbidden, Message: msgOwnAccount}
|
||||
}
|
||||
|
||||
func lastAdminError() *apiError {
|
||||
return &apiError{Status: http.StatusConflict, Message: msgLastActiveAdmin}
|
||||
}
|
||||
|
||||
func passwordFieldError(field string, err error) *apiError {
|
||||
return fieldError(field, err.Error())
|
||||
}
|
||||
|
||||
func (c *apiContext) setTargetUser(u userRow) {
|
||||
c.Entry.TargetUserID = sql.NullInt64{Int64: u.ID, Valid: true}
|
||||
}
|
||||
|
||||
func (c *apiContext) pathUsername() (string, error) {
|
||||
username := c.Vars["username"]
|
||||
if !validUsernameSyntax(username) {
|
||||
return "", errUserNotFound()
|
||||
}
|
||||
return username, nil
|
||||
}
|
||||
|
||||
func (c *apiContext) lookupUser(ctx context.Context) (userRow, error) {
|
||||
username, err := c.pathUsername()
|
||||
if err != nil {
|
||||
return userRow{}, err
|
||||
}
|
||||
u, err := c.Server.store.UserByUsername(ctx, username)
|
||||
if errors.Is(err, errRowNotFound) {
|
||||
return userRow{}, errUserNotFound()
|
||||
}
|
||||
if err != nil {
|
||||
return userRow{}, err
|
||||
}
|
||||
c.setTargetUser(u)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func activeTargetForUpdate(ctx context.Context, c *apiContext, tx webTx, username string) (userRow, error) {
|
||||
u, err := tx.UserByUsernameForUpdate(ctx, username)
|
||||
if errors.Is(err, errRowNotFound) {
|
||||
return userRow{}, errUserNotFound()
|
||||
}
|
||||
if err != nil {
|
||||
return userRow{}, err
|
||||
}
|
||||
c.setTargetUser(u)
|
||||
if u.DeletedAt.Valid {
|
||||
return userRow{}, errUserNotFound()
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (c *apiContext) recordChange(before, after []byte) {
|
||||
c.Entry.Before, c.Entry.After = before, after
|
||||
}
|
||||
|
||||
func (c *apiContext) commitChange(ctx context.Context, tx webTx, status int) error {
|
||||
return c.writeChangeAuditWith(ctx, tx, status)
|
||||
}
|
||||
|
||||
type accountResponse struct {
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
Zones []string `json:"zones"`
|
||||
}
|
||||
|
||||
func handleAccountRead(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
u := c.Principal.User
|
||||
resp := accountResponse{Username: u.Username, Role: u.Role, Zones: []string{}}
|
||||
if !c.Principal.isAdmin() {
|
||||
zones, err := c.Server.store.UserZones(ctx, u.ID)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
for _, z := range zones {
|
||||
if z.ZoneExists {
|
||||
resp.Zones = append(resp.Zones, z.Zone)
|
||||
}
|
||||
}
|
||||
}
|
||||
return okJSON(resp), nil
|
||||
}
|
||||
|
||||
type passwordChangeRequest struct {
|
||||
Current string `json:"current"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func handlePasswordChange(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
var req passwordChangeRequest
|
||||
if err := c.decodeJSON(&req); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
s := c.Server
|
||||
fields := map[string]string{}
|
||||
if !s.verifyPassword(req.Current, c.Principal.User.PasswordHash) {
|
||||
fields["current"] = msgWrongPassword
|
||||
}
|
||||
if err := checkPasswordRules(req.Password); err != nil {
|
||||
fields["password"] = err.Error()
|
||||
}
|
||||
if len(fields) > 0 {
|
||||
return apiResponse{}, &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid password change", Fields: fields}
|
||||
}
|
||||
hash, err := s.hashPassword(req.Password)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
c.setTargetUser(c.Principal.User)
|
||||
err = s.store.InTx(ctx, func(tx webTx) error {
|
||||
u, err := tx.UserByIDForUpdate(ctx, c.Principal.User.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if u.DeletedAt.Valid {
|
||||
return errUserNotFound()
|
||||
}
|
||||
if err := tx.SetPassword(ctx, u.ID, hash, c.Now); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.DeleteUserSessionsExcept(ctx, u.ID, c.Principal.TokenHash); err != nil {
|
||||
return err
|
||||
}
|
||||
snapshot := auditUserJSON(u)
|
||||
c.recordChange(snapshot, snapshot)
|
||||
return c.commitChange(ctx, tx, http.StatusNoContent)
|
||||
})
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return noContent(), nil
|
||||
}
|
||||
|
||||
type delegatedUser struct {
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
func requireZone(ctx context.Context, exists func(context.Context, string) (bool, error), zone string) error {
|
||||
ok, err := exists(ctx, zone)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return errZoneNotFound()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleDelegationList(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
store := c.Server.store
|
||||
if err := requireZone(ctx, store.ZoneExists, c.Zone); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
users, err := store.ZoneUsers(ctx, c.Zone)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
out := make([]delegatedUser, 0, len(users))
|
||||
for _, u := range users {
|
||||
out = append(out, delegatedUser{Username: u.Username, Role: u.Role})
|
||||
}
|
||||
return okJSON(map[string]any{"users": out}), nil
|
||||
}
|
||||
|
||||
func handleDelegationGrant(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
username, err := c.pathUsername()
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
err = c.Server.store.InTx(ctx, func(tx webTx) error {
|
||||
if err := requireZone(ctx, tx.ZoneExists, c.Zone); err != nil {
|
||||
return err
|
||||
}
|
||||
u, err := tx.UserByUsernameForUpdate(ctx, username)
|
||||
if errors.Is(err, errRowNotFound) {
|
||||
return errUserNotFound()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.setTargetUser(u)
|
||||
if aerr := delegationTargetError(u); aerr != nil {
|
||||
return aerr
|
||||
}
|
||||
created, err := tx.GrantDelegation(ctx, c.Zone, u.ID, c.Principal.User.ID, c.Now)
|
||||
if err != nil || !created {
|
||||
return err
|
||||
}
|
||||
c.recordChange(nil, auditDelegationJSON(c.Zone, u.Username))
|
||||
return c.commitChange(ctx, tx, http.StatusNoContent)
|
||||
})
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return noContent(), nil
|
||||
}
|
||||
|
||||
func handleDelegationRevoke(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
username, err := c.pathUsername()
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
err = c.Server.store.InTx(ctx, func(tx webTx) error {
|
||||
u, err := activeTargetForUpdate(ctx, c, tx, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
revoked, err := tx.RevokeDelegation(ctx, c.Zone, u.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !revoked {
|
||||
return &apiError{Status: http.StatusNotFound, Message: msgDelegationAbsent}
|
||||
}
|
||||
c.recordChange(auditDelegationJSON(c.Zone, u.Username), nil)
|
||||
return c.commitChange(ctx, tx, http.StatusNoContent)
|
||||
})
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return noContent(), nil
|
||||
}
|
||||
|
||||
type userListItem struct {
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
ZoneCount int64 `json:"zone_count"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
LastLoginAt *string `json:"last_login_at"`
|
||||
DeletedAt *string `json:"deleted_at"`
|
||||
}
|
||||
|
||||
func userListItemOf(u userRow, zones int64) userListItem {
|
||||
return userListItem{
|
||||
Username: u.Username,
|
||||
Role: u.Role,
|
||||
ZoneCount: zones,
|
||||
CreatedAt: apiTime(u.CreatedAt),
|
||||
LastLoginAt: apiNullTime(u.LastLoginAt),
|
||||
DeletedAt: apiNullTime(u.DeletedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func queryFlag(q url.Values, name string) (bool, error) {
|
||||
if !q.Has(name) {
|
||||
return false, nil
|
||||
}
|
||||
switch q.Get(name) {
|
||||
case "true":
|
||||
return true, nil
|
||||
case "false", "":
|
||||
return false, nil
|
||||
}
|
||||
return false, badParameter(name)
|
||||
}
|
||||
|
||||
func handleUserList(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
deleted, err := queryFlag(c.Request.URL.Query(), "deleted")
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
users, err := c.Server.store.ListUsers(ctx, deleted)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
out := make([]userListItem, 0, len(users))
|
||||
for _, u := range users {
|
||||
out = append(out, userListItemOf(u.userRow, u.Zones))
|
||||
}
|
||||
return okJSON(map[string]any{"users": out}), nil
|
||||
}
|
||||
|
||||
type userCreateRequest struct {
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func roleFieldMessage() string {
|
||||
return "must be admin or user"
|
||||
}
|
||||
|
||||
func handleUserCreate(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
var req userCreateRequest
|
||||
if err := c.decodeJSON(&req); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
fields := map[string]string{}
|
||||
if err := checkUsername(req.Username); err != nil {
|
||||
fields["username"] = err.Error()
|
||||
}
|
||||
if !validRole(req.Role) {
|
||||
fields["role"] = roleFieldMessage()
|
||||
}
|
||||
if err := checkPasswordRules(req.Password); err != nil {
|
||||
fields["password"] = err.Error()
|
||||
}
|
||||
if len(fields) > 0 {
|
||||
return apiResponse{}, &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid user", Fields: fields}
|
||||
}
|
||||
s := c.Server
|
||||
hash, err := s.hashPassword(req.Password)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
var created userRow
|
||||
err = s.store.InTx(ctx, func(tx webTx) error {
|
||||
u, err := tx.CreateUser(ctx, req.Username, req.Role, hash, c.Now)
|
||||
if errors.Is(err, errUsernameTaken) {
|
||||
return &apiError{Status: http.StatusConflict, Message: msgUsernameTaken}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
created = u
|
||||
c.setTargetUser(u)
|
||||
c.recordChange(nil, auditUserJSON(u))
|
||||
return c.commitChange(ctx, tx, http.StatusCreated)
|
||||
})
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return apiResponse{Status: http.StatusCreated, Body: userListItemOf(created, 0)}, nil
|
||||
}
|
||||
|
||||
type userZoneItem struct {
|
||||
Zone string `json:"zone"`
|
||||
Exists bool `json:"exists"`
|
||||
}
|
||||
|
||||
type userDetail struct {
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
LastLoginAt *string `json:"last_login_at"`
|
||||
DeletedAt *string `json:"deleted_at"`
|
||||
Zones []userZoneItem `json:"zones"`
|
||||
}
|
||||
|
||||
func handleUserRead(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
u, err := c.lookupUser(ctx)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
zones, err := c.Server.store.UserZones(ctx, u.ID)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
out := userDetail{
|
||||
Username: u.Username,
|
||||
Role: u.Role,
|
||||
CreatedAt: apiTime(u.CreatedAt),
|
||||
LastLoginAt: apiNullTime(u.LastLoginAt),
|
||||
DeletedAt: apiNullTime(u.DeletedAt),
|
||||
Zones: make([]userZoneItem, 0, len(zones)),
|
||||
}
|
||||
for _, z := range zones {
|
||||
out.Zones = append(out.Zones, userZoneItem{Zone: z.Zone, Exists: z.ZoneExists})
|
||||
}
|
||||
return okJSON(out), nil
|
||||
}
|
||||
|
||||
func (c *apiContext) foreignUsername() (string, error) {
|
||||
username, err := c.pathUsername()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if isOwnAccount(c.Principal, username) {
|
||||
c.setTargetUser(c.Principal.User)
|
||||
return "", ownAccountError()
|
||||
}
|
||||
return username, nil
|
||||
}
|
||||
|
||||
type userRoleRequest struct {
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
func lockAdminsAndTarget(ctx context.Context, c *apiContext, tx webTx, username string) (userRow, []userRow, error) {
|
||||
admins, err := tx.LockActiveAdmins(ctx)
|
||||
if err != nil {
|
||||
return userRow{}, nil, err
|
||||
}
|
||||
u, err := activeTargetForUpdate(ctx, c, tx, username)
|
||||
return u, admins, err
|
||||
}
|
||||
|
||||
func handleUserRole(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
username, err := c.foreignUsername()
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
var req userRoleRequest
|
||||
if err := c.decodeJSON(&req); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if !validRole(req.Role) {
|
||||
return apiResponse{}, fieldError("role", roleFieldMessage())
|
||||
}
|
||||
err = c.Server.store.InTx(ctx, func(tx webTx) error {
|
||||
u, admins, err := lockAdminsAndTarget(ctx, c, tx, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if u.Role == req.Role {
|
||||
return nil
|
||||
}
|
||||
if leavesNoActiveAdmin(u, admins) {
|
||||
return lastAdminError()
|
||||
}
|
||||
if err := tx.SetRole(ctx, u.ID, req.Role, c.Now); err != nil {
|
||||
return err
|
||||
}
|
||||
after := u
|
||||
after.Role = req.Role
|
||||
c.recordChange(auditUserJSON(u), auditUserJSON(after))
|
||||
return c.commitChange(ctx, tx, http.StatusNoContent)
|
||||
})
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return noContent(), nil
|
||||
}
|
||||
|
||||
type userPasswordRequest struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func handleUserPassword(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
username, err := c.foreignUsername()
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
var req userPasswordRequest
|
||||
if err := c.decodeJSON(&req); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if err := checkPasswordRules(req.Password); err != nil {
|
||||
return apiResponse{}, passwordFieldError("password", err)
|
||||
}
|
||||
s := c.Server
|
||||
hash, err := s.hashPassword(req.Password)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
err = s.store.InTx(ctx, func(tx webTx) error {
|
||||
u, err := activeTargetForUpdate(ctx, c, tx, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.SetPassword(ctx, u.ID, hash, c.Now); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
snapshot := auditUserJSON(u)
|
||||
c.recordChange(snapshot, snapshot)
|
||||
return c.commitChange(ctx, tx, http.StatusNoContent)
|
||||
})
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return noContent(), nil
|
||||
}
|
||||
|
||||
type confirmRequest struct {
|
||||
Confirm string `json:"confirm"`
|
||||
}
|
||||
|
||||
func handleUserDelete(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
username, err := c.foreignUsername()
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
var req confirmRequest
|
||||
if err := c.decodeJSON(&req); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if req.Confirm != username {
|
||||
return apiResponse{}, fieldError("confirm", msgConfirmMismatch)
|
||||
}
|
||||
err = c.Server.store.InTx(ctx, func(tx webTx) error {
|
||||
u, admins, err := lockAdminsAndTarget(ctx, c, tx, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if leavesNoActiveAdmin(u, admins) {
|
||||
return lastAdminError()
|
||||
}
|
||||
if err := tx.MarkDeleted(ctx, u.ID, c.Now); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
after := u
|
||||
after.DeletedAt = sql.NullTime{Time: dbTime(c.Now), Valid: true}
|
||||
c.recordChange(auditUserJSON(u), auditUserJSON(after))
|
||||
return c.commitChange(ctx, tx, http.StatusNoContent)
|
||||
})
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return noContent(), nil
|
||||
}
|
||||
|
||||
type auditItem struct {
|
||||
ID int64 `json:"id"`
|
||||
Time string `json:"time"`
|
||||
Actor string `json:"actor"`
|
||||
Origin string `json:"origin"`
|
||||
Operation string `json:"operation"`
|
||||
Status *int64 `json:"status"`
|
||||
Error *string `json:"error"`
|
||||
Zone *string `json:"zone"`
|
||||
RecordID *int64 `json:"record_id"`
|
||||
TargetUser *string `json:"target_user"`
|
||||
Before json.RawMessage `json:"before"`
|
||||
After json.RawMessage `json:"after"`
|
||||
}
|
||||
|
||||
type auditResponse struct {
|
||||
Entries []auditItem `json:"entries"`
|
||||
NextBeforeID *int64 `json:"next_before_id"`
|
||||
}
|
||||
|
||||
func nullInt(v sql.NullInt64) *int64 {
|
||||
if !v.Valid {
|
||||
return nil
|
||||
}
|
||||
return &v.Int64
|
||||
}
|
||||
|
||||
func nullString(v sql.NullString) *string {
|
||||
if !v.Valid {
|
||||
return nil
|
||||
}
|
||||
return &v.String
|
||||
}
|
||||
|
||||
func rawJSON(b []byte) json.RawMessage {
|
||||
if len(b) == 0 || !json.Valid(b) {
|
||||
return json.RawMessage("null")
|
||||
}
|
||||
return json.RawMessage(b)
|
||||
}
|
||||
|
||||
func auditItemOf(r auditRow) auditItem {
|
||||
return auditItem{
|
||||
ID: r.ID,
|
||||
Time: apiTime(r.Time),
|
||||
Actor: r.Actor,
|
||||
Origin: r.Origin,
|
||||
Operation: r.Operation,
|
||||
Status: nullInt(r.Status),
|
||||
Error: nullString(r.Error),
|
||||
Zone: nullString(r.Zone),
|
||||
RecordID: nullInt(r.RecordID),
|
||||
TargetUser: nullString(r.TargetUsername),
|
||||
Before: rawJSON(r.Before),
|
||||
After: rawJSON(r.After),
|
||||
}
|
||||
}
|
||||
|
||||
func parseAuditFilter(q url.Values) (auditFilter, error) {
|
||||
f := auditFilter{Limit: auditDefaultLimit}
|
||||
if v := q.Get("zone"); v != "" {
|
||||
zone, err := normalizeZone(v)
|
||||
if err != nil {
|
||||
return auditFilter{}, badParameter("zone")
|
||||
}
|
||||
f.Zone = zone
|
||||
}
|
||||
if v := q.Get("actor"); v != "" {
|
||||
if len([]rune(v)) > auditMaxActorRunes {
|
||||
return auditFilter{}, badParameter("actor")
|
||||
}
|
||||
f.Actor = v
|
||||
}
|
||||
if v := q.Get("operation"); v != "" {
|
||||
if !knownOperation(v) {
|
||||
return auditFilter{}, badParameter("operation")
|
||||
}
|
||||
f.Operation = v
|
||||
}
|
||||
switch v := q.Get("kind"); v {
|
||||
case "", auditKindRead, auditKindChange:
|
||||
f.Kind = v
|
||||
default:
|
||||
return auditFilter{}, badParameter("kind")
|
||||
}
|
||||
switch v := q.Get("outcome"); v {
|
||||
case "", auditOutcomeSuccess, auditOutcomeError:
|
||||
f.Outcome = v
|
||||
default:
|
||||
return auditFilter{}, badParameter("outcome")
|
||||
}
|
||||
if v := q.Get("before_id"); v != "" {
|
||||
n, err := parsePositive(v, 1<<62)
|
||||
if err != nil {
|
||||
return auditFilter{}, badParameter("before_id")
|
||||
}
|
||||
f.BeforeID = n
|
||||
}
|
||||
if v := q.Get("limit"); v != "" {
|
||||
n, err := parsePositive(v, auditMaxLimit)
|
||||
if err != nil {
|
||||
return auditFilter{}, badParameter("limit")
|
||||
}
|
||||
f.Limit = int(n)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func parsePositive(s string, max int64) (int64, error) {
|
||||
if s == "" || len(s) > 19 {
|
||||
return 0, strconv.ErrSyntax
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return 0, strconv.ErrSyntax
|
||||
}
|
||||
}
|
||||
n, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil || n < 1 || n > max {
|
||||
return 0, strconv.ErrRange
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func handleAuditRead(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
f, err := parseAuditFilter(c.Request.URL.Query())
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if !c.Principal.isAdmin() {
|
||||
f.RestrictToUserID = sql.NullInt64{Int64: c.Principal.User.ID, Valid: true}
|
||||
}
|
||||
delegated := map[string]bool{}
|
||||
if !c.Principal.isAdmin() {
|
||||
zones, err := c.Server.store.UserZones(ctx, c.Principal.User.ID)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
for _, z := range zones {
|
||||
delegated[z.Zone] = true
|
||||
}
|
||||
}
|
||||
limit := f.Limit
|
||||
f.Limit = limit + 1
|
||||
rows, err := c.Server.store.ListAudit(ctx, f)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
rows = slices.DeleteFunc(rows, func(r auditRow) bool { return !auditVisibleTo(c.Principal, r.auditEntry, delegated) })
|
||||
resp := auditResponse{Entries: make([]auditItem, 0, min(len(rows), limit))}
|
||||
for i, r := range rows {
|
||||
if i == limit {
|
||||
next := rows[limit-1].ID
|
||||
resp.NextBeforeID = &next
|
||||
break
|
||||
}
|
||||
resp.Entries = append(resp.Entries, auditItemOf(r))
|
||||
}
|
||||
return okJSON(resp), nil
|
||||
}
|
||||
|
||||
func zoneAPIHandlers(s *WebServer) map[string]apiHandler {
|
||||
h := zoneHandlers{s}
|
||||
return map[string]apiHandler{
|
||||
|
||||
Reference in new issue
Block a user