mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
chore: fully implement enterprise audit pkg (#3821)
This commit is contained in:
@@ -1,40 +0,0 @@
|
||||
package backends
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/coderd/audit"
|
||||
"github.com/coder/coder/coderd/database"
|
||||
)
|
||||
|
||||
type postgresBackend struct {
|
||||
// internal indicates if the exporter is exporting to the Postgres database
|
||||
// that the rest of Coderd uses. Since this is a generic Postgres exporter,
|
||||
// we make different decisions to store the audit log based on if it's
|
||||
// pointing to the Coderd database.
|
||||
internal bool
|
||||
db database.Store
|
||||
}
|
||||
|
||||
func NewPostgres(db database.Store, internal bool) audit.Backend {
|
||||
return &postgresBackend{db: db, internal: internal}
|
||||
}
|
||||
|
||||
func (b *postgresBackend) Decision() audit.FilterDecision {
|
||||
if b.internal {
|
||||
return audit.FilterDecisionStore
|
||||
}
|
||||
|
||||
return audit.FilterDecisionExport
|
||||
}
|
||||
|
||||
func (b *postgresBackend) Export(ctx context.Context, alog database.AuditLog) error {
|
||||
_, err := b.db.InsertAuditLog(ctx, database.InsertAuditLogParams(alog))
|
||||
if err != nil {
|
||||
return xerrors.Errorf("insert audit log: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package backends_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tabbed/pqtype"
|
||||
|
||||
"github.com/coder/coder/coderd/audit/backends"
|
||||
"github.com/coder/coder/coderd/database"
|
||||
"github.com/coder/coder/coderd/database/databasefake"
|
||||
)
|
||||
|
||||
func TestPostgresBackend(t *testing.T) {
|
||||
t.Parallel()
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var (
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
db = databasefake.New()
|
||||
pgb = backends.NewPostgres(db, true)
|
||||
alog = randomAuditLog()
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
err := pgb.Export(ctx, alog)
|
||||
require.NoError(t, err)
|
||||
|
||||
got, err := db.GetAuditLogsBefore(ctx, database.GetAuditLogsBeforeParams{
|
||||
ID: uuid.Nil,
|
||||
StartTime: time.Now().Add(time.Second),
|
||||
RowLimit: 1,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
require.Equal(t, alog, got[0])
|
||||
})
|
||||
}
|
||||
|
||||
func randomAuditLog() database.AuditLog {
|
||||
_, inet, _ := net.ParseCIDR("127.0.0.1/32")
|
||||
return database.AuditLog{
|
||||
ID: uuid.New(),
|
||||
Time: time.Now(),
|
||||
UserID: uuid.New(),
|
||||
OrganizationID: uuid.New(),
|
||||
Ip: pqtype.Inet{
|
||||
IPNet: *inet,
|
||||
Valid: true,
|
||||
},
|
||||
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
|
||||
ResourceType: database.ResourceTypeOrganization,
|
||||
ResourceID: uuid.New(),
|
||||
ResourceTarget: "colin's organization",
|
||||
Action: database.AuditActionDelete,
|
||||
Diff: []byte{},
|
||||
StatusCode: http.StatusNoContent,
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package backends
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/fatih/structs"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"github.com/coder/coder/coderd/audit"
|
||||
"github.com/coder/coder/coderd/database"
|
||||
)
|
||||
|
||||
type slogBackend struct {
|
||||
log slog.Logger
|
||||
}
|
||||
|
||||
func NewSlog(logger slog.Logger) audit.Backend {
|
||||
return slogBackend{log: logger}
|
||||
}
|
||||
|
||||
func (slogBackend) Decision() audit.FilterDecision {
|
||||
return audit.FilterDecisionExport
|
||||
}
|
||||
|
||||
func (b slogBackend) Export(ctx context.Context, alog database.AuditLog) error {
|
||||
m := structs.Map(alog)
|
||||
fields := make([]slog.Field, 0, len(m))
|
||||
for k, v := range m {
|
||||
fields = append(fields, slog.F(k, v))
|
||||
}
|
||||
|
||||
b.log.Info(ctx, "audit_log", fields...)
|
||||
return nil
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package backends_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/fatih/structs"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"github.com/coder/coder/coderd/audit/backends"
|
||||
)
|
||||
|
||||
func TestSlogBackend(t *testing.T) {
|
||||
t.Parallel()
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var (
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
|
||||
sink = &fakeSink{}
|
||||
logger = slog.Make(sink)
|
||||
backend = backends.NewSlog(logger)
|
||||
|
||||
alog = randomAuditLog()
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
err := backend.Export(ctx, alog)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, sink.entries, 1)
|
||||
require.Equal(t, sink.entries[0].Message, "audit_log")
|
||||
require.Len(t, sink.entries[0].Fields, len(structs.Fields(alog)))
|
||||
})
|
||||
}
|
||||
|
||||
type fakeSink struct {
|
||||
entries []slog.SinkEntry
|
||||
}
|
||||
|
||||
func (s *fakeSink) LogEntry(_ context.Context, e slog.SinkEntry) {
|
||||
s.entries = append(s.entries, e)
|
||||
}
|
||||
|
||||
func (*fakeSink) Sync() {}
|
||||
@@ -1,55 +0,0 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/coderd/database"
|
||||
)
|
||||
|
||||
// Backends can store or send audit logs to arbitrary locations.
|
||||
type Backend interface {
|
||||
// Decision determines the FilterDecisions that the backend tolerates.
|
||||
Decision() FilterDecision
|
||||
// Export sends an audit log to the backend.
|
||||
Export(ctx context.Context, alog database.AuditLog) error
|
||||
}
|
||||
|
||||
// Exporter exports audit logs to an arbitrary list of backends.
|
||||
type Exporter struct {
|
||||
filter Filter
|
||||
backends []Backend
|
||||
}
|
||||
|
||||
// NewExporter creates an exporter from the given filter and backends.
|
||||
func NewExporter(filter Filter, backends ...Backend) *Exporter {
|
||||
return &Exporter{
|
||||
filter: filter,
|
||||
backends: backends,
|
||||
}
|
||||
}
|
||||
|
||||
// Export exports and audit log. Before exporting to a backend, it uses the
|
||||
// filter to determine if the backend tolerates the audit log. If not, it is
|
||||
// dropped.
|
||||
func (e *Exporter) Export(ctx context.Context, alog database.AuditLog) error {
|
||||
decision, err := e.filter.Check(ctx, alog)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("filter check: %w", err)
|
||||
}
|
||||
|
||||
for _, backend := range e.backends {
|
||||
if decision&backend.Decision() != backend.Decision() {
|
||||
continue
|
||||
}
|
||||
|
||||
err = backend.Export(ctx, alog)
|
||||
if err != nil {
|
||||
// naively return the first error. should probably make this smarter
|
||||
// by returning multiple errors.
|
||||
return xerrors.Errorf("export audit log to backend: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
package audit_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tabbed/pqtype"
|
||||
|
||||
"github.com/coder/coder/coderd/audit"
|
||||
"github.com/coder/coder/coderd/database"
|
||||
)
|
||||
|
||||
func TestExporter(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var tests = []struct {
|
||||
name string
|
||||
filterDecision audit.FilterDecision
|
||||
backendDecision audit.FilterDecision
|
||||
shouldExport bool
|
||||
}{
|
||||
{
|
||||
name: "ShouldDrop",
|
||||
filterDecision: audit.FilterDecisionDrop,
|
||||
backendDecision: audit.FilterDecisionStore,
|
||||
shouldExport: false,
|
||||
},
|
||||
{
|
||||
name: "ShouldStore",
|
||||
filterDecision: audit.FilterDecisionStore,
|
||||
backendDecision: audit.FilterDecisionStore,
|
||||
shouldExport: true,
|
||||
},
|
||||
{
|
||||
name: "ShouldNotStore",
|
||||
filterDecision: audit.FilterDecisionExport,
|
||||
backendDecision: audit.FilterDecisionStore,
|
||||
shouldExport: false,
|
||||
},
|
||||
{
|
||||
name: "ShouldExport",
|
||||
filterDecision: audit.FilterDecisionExport,
|
||||
backendDecision: audit.FilterDecisionExport,
|
||||
shouldExport: true,
|
||||
},
|
||||
{
|
||||
name: "ShouldNotExport",
|
||||
filterDecision: audit.FilterDecisionStore,
|
||||
backendDecision: audit.FilterDecisionExport,
|
||||
shouldExport: false,
|
||||
},
|
||||
{
|
||||
name: "ShouldStoreOrExport",
|
||||
filterDecision: audit.FilterDecisionStore | audit.FilterDecisionExport,
|
||||
backendDecision: audit.FilterDecisionExport,
|
||||
shouldExport: true,
|
||||
},
|
||||
// When more filters are written they should have their own tests.
|
||||
{
|
||||
name: "DefaultFilter",
|
||||
filterDecision: func() audit.FilterDecision {
|
||||
decision, _ := audit.DefaultFilter.Check(context.Background(), randomAuditLog())
|
||||
return decision
|
||||
}(),
|
||||
backendDecision: audit.FilterDecisionExport,
|
||||
shouldExport: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var (
|
||||
backend = &testBackend{decision: test.backendDecision}
|
||||
exporter = audit.NewExporter(
|
||||
audit.FilterFunc(func(_ context.Context, _ database.AuditLog) (audit.FilterDecision, error) {
|
||||
return test.filterDecision, nil
|
||||
}),
|
||||
backend,
|
||||
)
|
||||
)
|
||||
|
||||
err := exporter.Export(context.Background(), randomAuditLog())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(backend.alogs) > 0, test.shouldExport)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func randomAuditLog() database.AuditLog {
|
||||
_, inet, _ := net.ParseCIDR("127.0.0.1/32")
|
||||
return database.AuditLog{
|
||||
ID: uuid.New(),
|
||||
Time: time.Now(),
|
||||
UserID: uuid.New(),
|
||||
OrganizationID: uuid.New(),
|
||||
Ip: pqtype.Inet{
|
||||
IPNet: *inet,
|
||||
Valid: true,
|
||||
},
|
||||
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
|
||||
ResourceType: database.ResourceTypeOrganization,
|
||||
ResourceID: uuid.New(),
|
||||
ResourceTarget: "colin's organization",
|
||||
Action: database.AuditActionDelete,
|
||||
Diff: []byte{},
|
||||
StatusCode: http.StatusNoContent,
|
||||
}
|
||||
}
|
||||
|
||||
type testBackend struct {
|
||||
decision audit.FilterDecision
|
||||
|
||||
alogs []database.AuditLog
|
||||
}
|
||||
|
||||
func (t *testBackend) Decision() audit.FilterDecision {
|
||||
return t.decision
|
||||
}
|
||||
|
||||
func (t *testBackend) Export(_ context.Context, alog database.AuditLog) error {
|
||||
t.alogs = append(t.alogs, alog)
|
||||
return nil
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/coder/coder/coderd/database"
|
||||
)
|
||||
|
||||
// FilterDecision is a bitwise flag describing the actions a given filter allows
|
||||
// for a given audit log.
|
||||
type FilterDecision uint8
|
||||
|
||||
const (
|
||||
// FilterDecisionDrop indicates that the audit log should be dropped. It
|
||||
// should not be stored or exported anywhere.
|
||||
FilterDecisionDrop FilterDecision = 0
|
||||
// FilterDecisionStore indicates that the audit log should be allowed to be
|
||||
// stored in the Coder database.
|
||||
FilterDecisionStore FilterDecision = 1 << iota
|
||||
// FilterDecisionExport indicates that the audit log should be exported
|
||||
// externally of Coder.
|
||||
FilterDecisionExport
|
||||
)
|
||||
|
||||
// Filters produce a FilterDecision for a given audit log.
|
||||
type Filter interface {
|
||||
Check(ctx context.Context, alog database.AuditLog) (FilterDecision, error)
|
||||
}
|
||||
|
||||
// DefaultFilter is the default filter used when exporting audit logs. It allows
|
||||
// storage and exporting for all audit logs.
|
||||
var DefaultFilter Filter = FilterFunc(func(ctx context.Context, alog database.AuditLog) (FilterDecision, error) {
|
||||
// Store and export all audit logs for now.
|
||||
return FilterDecisionStore | FilterDecisionExport, nil
|
||||
})
|
||||
|
||||
// FilterFunc constructs a Filter from a simple function.
|
||||
type FilterFunc func(ctx context.Context, alog database.AuditLog) (FilterDecision, error)
|
||||
|
||||
func (f FilterFunc) Check(ctx context.Context, alog database.AuditLog) (FilterDecision, error) {
|
||||
return f(ctx, alog)
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# This script facilitates code generation for auditing types. It outputs code
|
||||
# that can be copied and pasted into the audit.AuditableResources table. By
|
||||
# default, every field is ignored. It is your responsibility to go through each
|
||||
# field and document why each field should or should not be audited.
|
||||
#
|
||||
# Usage:
|
||||
# ./generate.sh <database type> <database type> ...
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}")
|
||||
PROJECT_ROOT=$(cd "$SCRIPT_DIR" && git rev-parse --show-toplevel)
|
||||
|
||||
(
|
||||
cd "$PROJECT_ROOT"
|
||||
go run ./scripts/auditgen ./coderd/database "$@"
|
||||
)
|
||||
+57
-8
@@ -2,22 +2,28 @@ package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
chimw "github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/google/uuid"
|
||||
"github.com/tabbed/pqtype"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"github.com/coder/coder/coderd/database"
|
||||
"github.com/coder/coder/coderd/httpapi"
|
||||
)
|
||||
|
||||
type RequestParams struct {
|
||||
Audit Auditor
|
||||
Log slog.Logger
|
||||
|
||||
Action database.AuditAction
|
||||
ResourceType database.ResourceType
|
||||
Actor uuid.UUID
|
||||
Request *http.Request
|
||||
ResourceID uuid.UUID
|
||||
ResourceTarget string
|
||||
Action database.AuditAction
|
||||
ResourceType database.ResourceType
|
||||
Actor uuid.UUID
|
||||
}
|
||||
|
||||
type Request[T Auditable] struct {
|
||||
@@ -31,9 +37,9 @@ type Request[T Auditable] struct {
|
||||
// that should be deferred, causing the audit log to be committed when the
|
||||
// handler returns.
|
||||
func InitRequest[T Auditable](w http.ResponseWriter, p *RequestParams) (*Request[T], func()) {
|
||||
sw, ok := w.(chimw.WrapResponseWriter)
|
||||
sw, ok := w.(*httpapi.StatusWriter)
|
||||
if !ok {
|
||||
panic("dev error: http.ResponseWriter is not chimw.WrapResponseWriter")
|
||||
panic("dev error: http.ResponseWriter is not *httpapi.StatusWriter")
|
||||
}
|
||||
|
||||
req := &Request[T]{
|
||||
@@ -42,11 +48,54 @@ func InitRequest[T Auditable](w http.ResponseWriter, p *RequestParams) (*Request
|
||||
|
||||
return req, func() {
|
||||
ctx := context.Background()
|
||||
code := sw.Status()
|
||||
|
||||
err := p.Audit.Export(ctx, database.AuditLog{StatusCode: int32(code)})
|
||||
diff := Diff(p.Audit, req.Old, req.New)
|
||||
diffRaw, _ := json.Marshal(diff)
|
||||
|
||||
ip, err := parseIP(p.Request.RemoteAddr)
|
||||
if err != nil {
|
||||
p.Log.Warn(ctx, "parse ip", slog.Error(err))
|
||||
}
|
||||
|
||||
err = p.Audit.Export(ctx, database.AuditLog{
|
||||
ID: uuid.New(),
|
||||
Time: database.Now(),
|
||||
UserID: p.Actor,
|
||||
Ip: ip,
|
||||
UserAgent: p.Request.UserAgent(),
|
||||
ResourceType: p.ResourceType,
|
||||
ResourceID: p.ResourceID,
|
||||
ResourceTarget: p.ResourceTarget,
|
||||
Action: p.Action,
|
||||
Diff: diffRaw,
|
||||
StatusCode: int32(sw.Status),
|
||||
})
|
||||
if err != nil {
|
||||
p.Log.Error(ctx, "export audit log", slog.Error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseIP(ipStr string) (pqtype.Inet, error) {
|
||||
var err error
|
||||
|
||||
ipStr, _, err = net.SplitHostPort(ipStr)
|
||||
if err != nil {
|
||||
return pqtype.Inet{}, err
|
||||
}
|
||||
|
||||
ip := net.ParseIP(ipStr)
|
||||
|
||||
ipNet := net.IPNet{}
|
||||
if ip != nil {
|
||||
ipNet = net.IPNet{
|
||||
IP: ip,
|
||||
Mask: net.CIDRMask(len(ip)*8, len(ip)*8),
|
||||
}
|
||||
}
|
||||
|
||||
return pqtype.Inet{
|
||||
IPNet: ipNet,
|
||||
Valid: ip != nil,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -4,5 +4,11 @@ import "time"
|
||||
|
||||
// Now returns a standardized timezone used for database resources.
|
||||
func Now() time.Time {
|
||||
return time.Now().UTC()
|
||||
return Time(time.Now().UTC())
|
||||
}
|
||||
|
||||
// Time returns a time compatible with Postgres. Postgres only stores dates with
|
||||
// microsecond precision.
|
||||
func Time(t time.Time) time.Time {
|
||||
return t.Round(time.Microsecond)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user