Add PG creds + policy/tags UI; fix lint and build

- internal/ui/ui.go: add PGCred, Tags to AccountDetailData; register
  PUT /accounts/{id}/pgcreds and PUT /accounts/{id}/tags routes; add
  pgcreds_form.html and tags_editor.html to shared template set; remove
  unused AccountTagsData; fix fieldalignment on PolicyRuleView, PoliciesData
- internal/ui/handlers_accounts.go: add handleSetPGCreds — encrypts
  password via crypto.SealAESGCM, writes audit EventPGCredUpdated, renders
  pgcreds_form fragment; password never echoed; load PG creds and tags in
  handleAccountDetail
- internal/ui/handlers_policy.go: fix handleSetAccountTags to render with
  AccountDetailData instead of removed AccountTagsData
- internal/ui/ui_test.go: add 5 PG credential UI tests
- web/templates/fragments/pgcreds_form.html: new fragment — metadata display
  + set/replace form; system accounts only; password write-only
- web/templates/fragments/tags_editor.html: new fragment — textarea editor
  with HTMX PUT for atomic tag replacement
- web/templates/fragments/policy_form.html: rewrite to use structured fields
  matching handleCreatePolicyRule (roles/account_types/actions multi-select,
  resource_type, subject_uuid, service_names, required_tags, checkbox)
- web/templates/policies.html: new policies management page
- web/templates/fragments/policy_row.html: new HTMX table row with toggle
  and delete
- web/templates/account_detail.html: add Tags card and PG Credentials card
- web/templates/base.html: add Policies nav link
- internal/server/server.go: remove ~220 lines of duplicate tag/policy
  handler code (real implementations are in handlers_policy.go)
- internal/policy/engine_wrapper.go: fix corrupted source; use errors.New
- internal/db/policy_test.go: use model.AccountTypeHuman constant
- cmd/mciasctl/main.go: add nolint:gosec to int(os.Stdin.Fd()) calls
- gofmt/goimports: db/policy_test.go, policy/defaults.go,
  policy/engine_test.go, ui/ui.go, cmd/mciasctl/main.go
- fieldalignment: model.PolicyRuleRecord, policy.Engine, policy.Rule,
  policy.RuleBody, ui.PolicyRuleView
Security: PG password encrypted AES-256-GCM with fresh random nonce before
storage; plaintext never logged or returned in any response; audit event
written on every credential write.
This commit is contained in:
2026-03-11 23:24:03 -07:00
parent 5a8698e199
commit 052d3ed1b8
27 changed files with 3609 additions and 10 deletions

191
internal/db/policy.go Normal file
View File

@@ -0,0 +1,191 @@
package db
import (
"database/sql"
"errors"
"fmt"
"git.wntrmute.dev/kyle/mcias/internal/model"
)
// CreatePolicyRule inserts a new policy rule record. The returned record
// includes the database-assigned ID and timestamps.
func (db *DB) CreatePolicyRule(description string, priority int, ruleJSON string, createdBy *int64) (*model.PolicyRuleRecord, error) {
n := now()
result, err := db.sql.Exec(`
INSERT INTO policy_rules (priority, description, rule_json, enabled, created_by, created_at, updated_at)
VALUES (?, ?, ?, 1, ?, ?, ?)
`, priority, description, ruleJSON, createdBy, n, n)
if err != nil {
return nil, fmt.Errorf("db: create policy rule: %w", err)
}
id, err := result.LastInsertId()
if err != nil {
return nil, fmt.Errorf("db: create policy rule last insert id: %w", err)
}
createdAt, err := parseTime(n)
if err != nil {
return nil, err
}
return &model.PolicyRuleRecord{
ID: id,
Priority: priority,
Description: description,
RuleJSON: ruleJSON,
Enabled: true,
CreatedBy: createdBy,
CreatedAt: createdAt,
UpdatedAt: createdAt,
}, nil
}
// GetPolicyRule retrieves a single policy rule by its database ID.
// Returns ErrNotFound if no such rule exists.
func (db *DB) GetPolicyRule(id int64) (*model.PolicyRuleRecord, error) {
return db.scanPolicyRule(db.sql.QueryRow(`
SELECT id, priority, description, rule_json, enabled, created_by, created_at, updated_at
FROM policy_rules WHERE id = ?
`, id))
}
// ListPolicyRules returns all policy rules ordered by priority then ID.
// When enabledOnly is true, only rules with enabled=1 are returned.
func (db *DB) ListPolicyRules(enabledOnly bool) ([]*model.PolicyRuleRecord, error) {
query := `
SELECT id, priority, description, rule_json, enabled, created_by, created_at, updated_at
FROM policy_rules`
if enabledOnly {
query += ` WHERE enabled = 1`
}
query += ` ORDER BY priority ASC, id ASC`
rows, err := db.sql.Query(query)
if err != nil {
return nil, fmt.Errorf("db: list policy rules: %w", err)
}
defer func() { _ = rows.Close() }()
var rules []*model.PolicyRuleRecord
for rows.Next() {
r, err := db.scanPolicyRuleRow(rows)
if err != nil {
return nil, err
}
rules = append(rules, r)
}
return rules, rows.Err()
}
// UpdatePolicyRule updates the mutable fields of a policy rule.
// Only the fields in the update map are changed; other fields are untouched.
func (db *DB) UpdatePolicyRule(id int64, description *string, priority *int, ruleJSON *string) error {
n := now()
// Build SET clause dynamically to only update provided fields.
// Security: field names are not user-supplied strings — they are selected
// from a fixed set of known column names only.
setClauses := "updated_at = ?"
args := []interface{}{n}
if description != nil {
setClauses += ", description = ?"
args = append(args, *description)
}
if priority != nil {
setClauses += ", priority = ?"
args = append(args, *priority)
}
if ruleJSON != nil {
setClauses += ", rule_json = ?"
args = append(args, *ruleJSON)
}
args = append(args, id)
_, err := db.sql.Exec(`UPDATE policy_rules SET `+setClauses+` WHERE id = ?`, args...)
if err != nil {
return fmt.Errorf("db: update policy rule %d: %w", id, err)
}
return nil
}
// SetPolicyRuleEnabled enables or disables a policy rule by ID.
func (db *DB) SetPolicyRuleEnabled(id int64, enabled bool) error {
enabledInt := 0
if enabled {
enabledInt = 1
}
_, err := db.sql.Exec(`
UPDATE policy_rules SET enabled = ?, updated_at = ? WHERE id = ?
`, enabledInt, now(), id)
if err != nil {
return fmt.Errorf("db: set policy rule %d enabled=%v: %w", id, enabled, err)
}
return nil
}
// DeletePolicyRule removes a policy rule by ID.
func (db *DB) DeletePolicyRule(id int64) error {
_, err := db.sql.Exec(`DELETE FROM policy_rules WHERE id = ?`, id)
if err != nil {
return fmt.Errorf("db: delete policy rule %d: %w", id, err)
}
return nil
}
// scanPolicyRule scans a single policy rule from a *sql.Row.
func (db *DB) scanPolicyRule(row *sql.Row) (*model.PolicyRuleRecord, error) {
var r model.PolicyRuleRecord
var enabledInt int
var createdAtStr, updatedAtStr string
var createdBy *int64
err := row.Scan(
&r.ID, &r.Priority, &r.Description, &r.RuleJSON,
&enabledInt, &createdBy, &createdAtStr, &updatedAtStr,
)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("db: scan policy rule: %w", err)
}
return finishPolicyRuleScan(&r, enabledInt, createdBy, createdAtStr, updatedAtStr)
}
// scanPolicyRuleRow scans a single policy rule from *sql.Rows.
func (db *DB) scanPolicyRuleRow(rows *sql.Rows) (*model.PolicyRuleRecord, error) {
var r model.PolicyRuleRecord
var enabledInt int
var createdAtStr, updatedAtStr string
var createdBy *int64
err := rows.Scan(
&r.ID, &r.Priority, &r.Description, &r.RuleJSON,
&enabledInt, &createdBy, &createdAtStr, &updatedAtStr,
)
if err != nil {
return nil, fmt.Errorf("db: scan policy rule row: %w", err)
}
return finishPolicyRuleScan(&r, enabledInt, createdBy, createdAtStr, updatedAtStr)
}
func finishPolicyRuleScan(r *model.PolicyRuleRecord, enabledInt int, createdBy *int64, createdAtStr, updatedAtStr string) (*model.PolicyRuleRecord, error) {
r.Enabled = enabledInt == 1
r.CreatedBy = createdBy
var err error
r.CreatedAt, err = parseTime(createdAtStr)
if err != nil {
return nil, err
}
r.UpdatedAt, err = parseTime(updatedAtStr)
if err != nil {
return nil, err
}
return r, nil
}