Skip to content

feat: add auditing to user routes #3961

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions coderd/audit/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,18 @@ func (nop) Export(context.Context, database.AuditLog) error {
}

func (nop) diff(any, any) Map { return Map{} }

func NewMock() *MockAuditor {
return &MockAuditor{}
}

type MockAuditor struct {
AuditLogs []database.AuditLog
}

func (a *MockAuditor) Export(_ context.Context, alog database.AuditLog) error {
a.AuditLogs = append(a.AuditLogs, alog)
return nil
}

func (*MockAuditor) diff(any, any) Map { return Map{} }
131 changes: 106 additions & 25 deletions coderd/audit/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package audit
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"

Expand All @@ -11,20 +12,17 @@ import (

"cdr.dev/slog"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/features"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/coderd/httpmw"
)

type RequestParams struct {
Audit Auditor
Log slog.Logger

Request *http.Request
ResourceID uuid.UUID
ResourceTarget string
Action database.AuditAction
ResourceType database.ResourceType
Actor uuid.UUID
Features features.Service
Log slog.Logger

Request *http.Request
Action database.AuditAction
}

type Request[T Auditable] struct {
Expand All @@ -34,6 +32,63 @@ type Request[T Auditable] struct {
New T
}

func ResourceTarget[T Auditable](tgt T) string {
switch typed := any(tgt).(type) {
case database.Organization:
return typed.Name
case database.Template:
return typed.Name
case database.TemplateVersion:
return typed.Name
case database.User:
return typed.Username
case database.Workspace:
return typed.Name
case database.GitSSHKey:
return typed.PublicKey
default:
panic(fmt.Sprintf("unknown resource %T", tgt))
}
}

func ResourceID[T Auditable](tgt T) uuid.UUID {
switch typed := any(tgt).(type) {
case database.Organization:
return typed.ID
case database.Template:
return typed.ID
case database.TemplateVersion:
return typed.ID
case database.User:
return typed.ID
case database.Workspace:
return typed.ID
case database.GitSSHKey:
return typed.UserID
default:
panic(fmt.Sprintf("unknown resource %T", tgt))
}
}

func ResourceType[T Auditable](tgt T) database.ResourceType {
switch any(tgt).(type) {
case database.Organization:
return database.ResourceTypeOrganization
case database.Template:
return database.ResourceTypeTemplate
case database.TemplateVersion:
return database.ResourceTypeTemplateVersion
case database.User:
return database.ResourceTypeUser
case database.Workspace:
return database.ResourceTypeWorkspace
case database.GitSSHKey:
return database.ResourceTypeGitSshKey
default:
panic(fmt.Sprintf("unknown resource %T", tgt))
}
}

// InitRequest initializes an audit log for a request. It returns a function
// that should be deferred, causing the audit log to be committed when the
// handler returns.
Expand All @@ -47,38 +102,64 @@ func InitRequest[T Auditable](w http.ResponseWriter, p *RequestParams) (*Request
params: p,
}

feats := struct {
Audit Auditor
}{}
err := p.Features.Get(&feats)
if err != nil {
p.Log.Error(p.Request.Context(), "unable to get auditor interface", slog.Error(err))
return req, func() {}
}

return req, func() {
ctx := context.Background()
logCtx := p.Request.Context()

diff := Diff(p.Audit, req.Old, req.New)
// If no resources were provided, there's nothing we can audit.
if ResourceID(req.Old) == uuid.Nil && ResourceID(req.New) == uuid.Nil {
return
}

diff := Diff(feats.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))
p.Log.Warn(logCtx, "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),
RequestID: httpmw.RequestID(p.Request),
err = feats.Audit.Export(ctx, database.AuditLog{
ID: uuid.New(),
Time: database.Now(),
UserID: httpmw.APIKey(p.Request).UserID,
Ip: ip,
UserAgent: p.Request.UserAgent(),
ResourceType: either(req.Old, req.New, ResourceType[T]),
ResourceID: either(req.Old, req.New, ResourceID[T]),
ResourceTarget: either(req.Old, req.New, ResourceTarget[T]),
Action: p.Action,
Diff: diffRaw,
StatusCode: int32(sw.Status),
RequestID: httpmw.RequestID(p.Request),
AdditionalFields: json.RawMessage("{}"),
})
if err != nil {
p.Log.Error(ctx, "export audit log", slog.Error(err))
p.Log.Error(logCtx, "export audit log", slog.Error(err))
return
}
}
}

func either[T Auditable, R any](old, new T, fn func(T) R) R {
if ResourceID(new) != uuid.Nil {
return fn(new)
} else if ResourceID(old) != uuid.Nil {
return fn(old)
} else {
panic("both old and new are nil")
}
}

func parseIP(ipStr string) (pqtype.Inet, error) {
var err error

Expand Down
5 changes: 3 additions & 2 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/coder/coder/buildinfo"
"github.com/coder/coder/coderd/awsidentity"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/features"
"github.com/coder/coder/coderd/gitsshkey"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/coderd/httpmw"
Expand Down Expand Up @@ -72,7 +73,7 @@ type Options struct {
TracerProvider *sdktrace.TracerProvider
AutoImportTemplates []AutoImportTemplate
LicenseHandler http.Handler
FeaturesService FeaturesService
FeaturesService features.Service

TailscaleEnable bool
TailnetCoordinator *tailnet.Coordinator
Expand Down Expand Up @@ -113,7 +114,7 @@ func New(options *Options) *API {
options.LicenseHandler = licenses()
}
if options.FeaturesService == nil {
options.FeaturesService = featuresService{}
options.FeaturesService = &featuresService{}
}

siteCacheDir := options.CacheDir
Expand Down
8 changes: 8 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import (
"cdr.dev/slog"
"cdr.dev/slog/sloggers/slogtest"
"github.com/coder/coder/coderd"
"github.com/coder/coder/coderd/audit"
"github.com/coder/coder/coderd/autobuild/executor"
"github.com/coder/coder/coderd/awsidentity"
"github.com/coder/coder/coderd/database"
Expand Down Expand Up @@ -74,6 +75,7 @@ type Options struct {
AutoImportTemplates []coderd.AutoImportTemplate
AutobuildTicker <-chan time.Time
AutobuildStats chan<- executor.Stats
Auditor audit.Auditor

// IncludeProvisionerDaemon when true means to start an in-memory provisionerD
IncludeProvisionerDaemon bool
Expand Down Expand Up @@ -197,6 +199,11 @@ func newWithAPI(t *testing.T, options *Options) (*codersdk.Client, io.Closer, *c
_ = turnServer.Close()
})

features := coderd.DisabledImplementations
if options.Auditor != nil {
features.Auditor = options.Auditor
}

// We set the handler after server creation for the access URL.
coderAPI := options.APIBuilder(&coderd.Options{
AgentConnectionUpdateFrequency: 150 * time.Millisecond,
Expand Down Expand Up @@ -240,6 +247,7 @@ func newWithAPI(t *testing.T, options *Options) (*codersdk.Client, io.Closer, *c
AutoImportTemplates: options.AutoImportTemplates,
MetricsCacheRefreshInterval: options.MetricsCacheRefreshInterval,
AgentStatsRefreshInterval: options.AgentStatsRefreshInterval,
FeaturesService: coderd.NewMockFeaturesService(features),
})
t.Cleanup(func() {
_ = coderAPI.Close()
Expand Down
38 changes: 21 additions & 17 deletions coderd/features.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,31 @@ import (
"golang.org/x/xerrors"

"github.com/coder/coder/coderd/audit"
"github.com/coder/coder/coderd/features"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/codersdk"
)

// FeaturesService is the interface for interacting with enterprise features.
type FeaturesService interface {
EntitlementsAPI(w http.ResponseWriter, r *http.Request)

// Get returns the implementations for feature interfaces. Parameter `s` must be a pointer to a
// struct type containing feature interfaces as fields. The FeatureService sets all fields to
// the correct implementations depending on whether the features are turned on.
Get(s any) error
func NewMockFeaturesService(feats FeatureInterfaces) features.Service {
return &featuresService{
feats: &feats,
}
}

type featuresService struct{}
type featuresService struct {
feats *FeatureInterfaces
}

func (featuresService) EntitlementsAPI(rw http.ResponseWriter, _ *http.Request) {
features := make(map[string]codersdk.Feature)
func (*featuresService) EntitlementsAPI(rw http.ResponseWriter, _ *http.Request) {
feats := make(map[string]codersdk.Feature)
for _, f := range codersdk.FeatureNames {
features[f] = codersdk.Feature{
feats[f] = codersdk.Feature{
Entitlement: codersdk.EntitlementNotEntitled,
Enabled: false,
}
}
httpapi.Write(rw, http.StatusOK, codersdk.Entitlements{
Features: features,
Features: feats,
Warnings: []string{},
HasLicense: false,
})
Expand All @@ -42,7 +41,7 @@ func (featuresService) EntitlementsAPI(rw http.ResponseWriter, _ *http.Request)
// struct type containing feature interfaces as fields. The AGPL featureService always returns the
// "disabled" version of the feature interface because it doesn't include any enterprise features
// by definition.
func (featuresService) Get(ps any) error {
func (f *featuresService) Get(ps any) error {
if reflect.TypeOf(ps).Kind() != reflect.Pointer {
return xerrors.New("input must be pointer to struct")
}
Expand All @@ -56,7 +55,7 @@ func (featuresService) Get(ps any) error {
if tf.Kind() != reflect.Interface {
return xerrors.Errorf("fields of input struct must be interfaces: %s", tf.String())
}
err := setImplementation(vf, tf)
err := f.setImplementation(vf, tf)
if err != nil {
return err
}
Expand All @@ -66,11 +65,16 @@ func (featuresService) Get(ps any) error {

// setImplementation finds the correct implementation for the field's type, and sets it on the
// struct. It returns an error if unsuccessful
func setImplementation(vf reflect.Value, tf reflect.Type) error {
func (f *featuresService) setImplementation(vf reflect.Value, tf reflect.Type) error {
feats := f.feats
if feats == nil {
feats = &DisabledImplementations
}

// when we get more than a few features it might make sense to have a data structure for finding
// the correct implementation that's faster than just a linear search, but for now just spin
// through the implementations we have.
vd := reflect.ValueOf(DisabledImplementations)
vd := reflect.ValueOf(*feats)
for j := 0; j < vd.NumField(); j++ {
vdf := vd.Field(j)
if vdf.Type() == tf {
Expand Down
13 changes: 13 additions & 0 deletions coderd/features/features.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package features

import "net/http"

// Service is the interface for interacting with enterprise features.
type Service interface {
EntitlementsAPI(w http.ResponseWriter, r *http.Request)

// Get returns the implementations for feature interfaces. Parameter `s` must be a pointer to a
// struct type containing feature interfaces as fields. The FeatureService sets all fields to
// the correct implementations depending on whether the features are turned on.
Get(s any) error
}
2 changes: 1 addition & 1 deletion coderd/features_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestEntitlements(t *testing.T) {
t.Parallel()
r := httptest.NewRequest("GET", "https://example.com/api/v2/entitlements", nil)
rw := httptest.NewRecorder()
featuresService{}.EntitlementsAPI(rw, r)
(&featuresService{}).EntitlementsAPI(rw, r)
resp := rw.Result()
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
Expand Down
Loading