mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
+2
-1
@@ -65,6 +65,7 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/healthcheck/derphealth"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/httpmw"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
||||
"github.com/coder/coder/v2/coderd/metricscache"
|
||||
"github.com/coder/coder/v2/coderd/notifications"
|
||||
"github.com/coder/coder/v2/coderd/portsharing"
|
||||
@@ -811,7 +812,7 @@ func New(options *Options) *API {
|
||||
tracing.Middleware(api.TracerProvider),
|
||||
httpmw.AttachRequestID,
|
||||
httpmw.ExtractRealIP(api.RealIPConfig),
|
||||
httpmw.Logger(api.Logger),
|
||||
loggermw.Logger(api.Logger),
|
||||
singleSlashMW,
|
||||
rolestore.CustomRoleMW,
|
||||
prometheusMW,
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/database/dbtime"
|
||||
"github.com/coder/coder/v2/coderd/httpapi/httpapiconstraints"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
||||
"github.com/coder/coder/v2/coderd/rbac"
|
||||
"github.com/coder/coder/v2/coderd/util/slice"
|
||||
"github.com/coder/coder/v2/provisionersdk"
|
||||
@@ -163,6 +164,7 @@ func ActorFromContext(ctx context.Context) (rbac.Subject, bool) {
|
||||
|
||||
var (
|
||||
subjectProvisionerd = rbac.Subject{
|
||||
Type: rbac.SubjectTypeProvisionerd,
|
||||
FriendlyName: "Provisioner Daemon",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -197,6 +199,7 @@ var (
|
||||
}.WithCachedASTValue()
|
||||
|
||||
subjectAutostart = rbac.Subject{
|
||||
Type: rbac.SubjectTypeAutostart,
|
||||
FriendlyName: "Autostart",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -220,6 +223,7 @@ var (
|
||||
|
||||
// See unhanger package.
|
||||
subjectHangDetector = rbac.Subject{
|
||||
Type: rbac.SubjectTypeHangDetector,
|
||||
FriendlyName: "Hang Detector",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -240,6 +244,7 @@ var (
|
||||
|
||||
// See cryptokeys package.
|
||||
subjectCryptoKeyRotator = rbac.Subject{
|
||||
Type: rbac.SubjectTypeCryptoKeyRotator,
|
||||
FriendlyName: "Crypto Key Rotator",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -258,6 +263,7 @@ var (
|
||||
|
||||
// See cryptokeys package.
|
||||
subjectCryptoKeyReader = rbac.Subject{
|
||||
Type: rbac.SubjectTypeCryptoKeyReader,
|
||||
FriendlyName: "Crypto Key Reader",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -275,6 +281,7 @@ var (
|
||||
}.WithCachedASTValue()
|
||||
|
||||
subjectNotifier = rbac.Subject{
|
||||
Type: rbac.SubjectTypeNotifier,
|
||||
FriendlyName: "Notifier",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -295,6 +302,7 @@ var (
|
||||
}.WithCachedASTValue()
|
||||
|
||||
subjectResourceMonitor = rbac.Subject{
|
||||
Type: rbac.SubjectTypeResourceMonitor,
|
||||
FriendlyName: "Resource Monitor",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -313,6 +321,7 @@ var (
|
||||
}.WithCachedASTValue()
|
||||
|
||||
subjectSystemRestricted = rbac.Subject{
|
||||
Type: rbac.SubjectTypeSystemRestricted,
|
||||
FriendlyName: "System",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -347,6 +356,7 @@ var (
|
||||
}.WithCachedASTValue()
|
||||
|
||||
subjectSystemReadProvisionerDaemons = rbac.Subject{
|
||||
Type: rbac.SubjectTypeSystemReadProvisionerDaemons,
|
||||
FriendlyName: "Provisioner Daemons Reader",
|
||||
ID: uuid.Nil.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -364,6 +374,7 @@ var (
|
||||
}.WithCachedASTValue()
|
||||
|
||||
subjectPrebuildsOrchestrator = rbac.Subject{
|
||||
Type: rbac.SubjectTypePrebuildsOrchestrator,
|
||||
FriendlyName: "Prebuilds Orchestrator",
|
||||
ID: prebuilds.SystemUserID.String(),
|
||||
Roles: rbac.Roles([]rbac.Role{
|
||||
@@ -388,59 +399,59 @@ var (
|
||||
// AsProvisionerd returns a context with an actor that has permissions required
|
||||
// for provisionerd to function.
|
||||
func AsProvisionerd(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectProvisionerd)
|
||||
return As(ctx, subjectProvisionerd)
|
||||
}
|
||||
|
||||
// AsAutostart returns a context with an actor that has permissions required
|
||||
// for autostart to function.
|
||||
func AsAutostart(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectAutostart)
|
||||
return As(ctx, subjectAutostart)
|
||||
}
|
||||
|
||||
// AsHangDetector returns a context with an actor that has permissions required
|
||||
// for unhanger.Detector to function.
|
||||
func AsHangDetector(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectHangDetector)
|
||||
return As(ctx, subjectHangDetector)
|
||||
}
|
||||
|
||||
// AsKeyRotator returns a context with an actor that has permissions required for rotating crypto keys.
|
||||
func AsKeyRotator(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectCryptoKeyRotator)
|
||||
return As(ctx, subjectCryptoKeyRotator)
|
||||
}
|
||||
|
||||
// AsKeyReader returns a context with an actor that has permissions required for reading crypto keys.
|
||||
func AsKeyReader(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectCryptoKeyReader)
|
||||
return As(ctx, subjectCryptoKeyReader)
|
||||
}
|
||||
|
||||
// AsNotifier returns a context with an actor that has permissions required for
|
||||
// creating/reading/updating/deleting notifications.
|
||||
func AsNotifier(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectNotifier)
|
||||
return As(ctx, subjectNotifier)
|
||||
}
|
||||
|
||||
// AsResourceMonitor returns a context with an actor that has permissions required for
|
||||
// updating resource monitors.
|
||||
func AsResourceMonitor(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectResourceMonitor)
|
||||
return As(ctx, subjectResourceMonitor)
|
||||
}
|
||||
|
||||
// AsSystemRestricted returns a context with an actor that has permissions
|
||||
// required for various system operations (login, logout, metrics cache).
|
||||
func AsSystemRestricted(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectSystemRestricted)
|
||||
return As(ctx, subjectSystemRestricted)
|
||||
}
|
||||
|
||||
// AsSystemReadProvisionerDaemons returns a context with an actor that has permissions
|
||||
// to read provisioner daemons.
|
||||
func AsSystemReadProvisionerDaemons(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectSystemReadProvisionerDaemons)
|
||||
return As(ctx, subjectSystemReadProvisionerDaemons)
|
||||
}
|
||||
|
||||
// AsPrebuildsOrchestrator returns a context with an actor that has permissions
|
||||
// to read orchestrator workspace prebuilds.
|
||||
func AsPrebuildsOrchestrator(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, authContextKey{}, subjectPrebuildsOrchestrator)
|
||||
return As(ctx, subjectPrebuildsOrchestrator)
|
||||
}
|
||||
|
||||
var AsRemoveActor = rbac.Subject{
|
||||
@@ -458,6 +469,9 @@ func As(ctx context.Context, actor rbac.Subject) context.Context {
|
||||
// should be removed from the context.
|
||||
return context.WithValue(ctx, authContextKey{}, nil)
|
||||
}
|
||||
if rlogger := loggermw.RequestLoggerFromContext(ctx); rlogger != nil {
|
||||
rlogger.WithAuthContext(actor)
|
||||
}
|
||||
return context.WithValue(ctx, authContextKey{}, actor)
|
||||
}
|
||||
|
||||
|
||||
@@ -12064,10 +12064,10 @@ func (q *sqlQuerier) GetActiveUserCount(ctx context.Context, includeSystem bool)
|
||||
|
||||
const getAuthorizationUserRoles = `-- name: GetAuthorizationUserRoles :one
|
||||
SELECT
|
||||
-- username is returned just to help for logging purposes
|
||||
-- username and email are returned just to help for logging purposes
|
||||
-- status is used to enforce 'suspended' users, as all roles are ignored
|
||||
-- when suspended.
|
||||
id, username, status,
|
||||
id, username, status, email,
|
||||
-- All user roles, including their org roles.
|
||||
array_cat(
|
||||
-- All users are members
|
||||
@@ -12108,6 +12108,7 @@ type GetAuthorizationUserRolesRow struct {
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
Username string `db:"username" json:"username"`
|
||||
Status UserStatus `db:"status" json:"status"`
|
||||
Email string `db:"email" json:"email"`
|
||||
Roles []string `db:"roles" json:"roles"`
|
||||
Groups []string `db:"groups" json:"groups"`
|
||||
}
|
||||
@@ -12121,6 +12122,7 @@ func (q *sqlQuerier) GetAuthorizationUserRoles(ctx context.Context, userID uuid.
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.Status,
|
||||
&i.Email,
|
||||
pq.Array(&i.Roles),
|
||||
pq.Array(&i.Groups),
|
||||
)
|
||||
|
||||
@@ -300,10 +300,10 @@ WHERE
|
||||
-- This function returns roles for authorization purposes. Implied member roles
|
||||
-- are included.
|
||||
SELECT
|
||||
-- username is returned just to help for logging purposes
|
||||
-- username and email are returned just to help for logging purposes
|
||||
-- status is used to enforce 'suspended' users, as all roles are ignored
|
||||
-- when suspended.
|
||||
id, username, status,
|
||||
id, username, status, email,
|
||||
-- All user roles, including their org roles.
|
||||
array_cat(
|
||||
-- All users are members
|
||||
|
||||
@@ -465,7 +465,9 @@ func UserRBACSubject(ctx context.Context, db database.Store, userID uuid.UUID, s
|
||||
}
|
||||
|
||||
actor := rbac.Subject{
|
||||
Type: rbac.SubjectTypeUser,
|
||||
FriendlyName: roles.Username,
|
||||
Email: roles.Email,
|
||||
ID: userID.String(),
|
||||
Roles: rbacRoles,
|
||||
Groups: roles.Groups,
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
package httpmw
|
||||
package loggermw
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/rbac"
|
||||
"github.com/coder/coder/v2/coderd/tracing"
|
||||
)
|
||||
|
||||
@@ -62,6 +66,7 @@ func Logger(log slog.Logger) func(next http.Handler) http.Handler {
|
||||
type RequestLogger interface {
|
||||
WithFields(fields ...slog.Field)
|
||||
WriteLog(ctx context.Context, status int)
|
||||
WithAuthContext(actor rbac.Subject)
|
||||
}
|
||||
|
||||
type SlogRequestLogger struct {
|
||||
@@ -69,6 +74,9 @@ type SlogRequestLogger struct {
|
||||
written bool
|
||||
message string
|
||||
start time.Time
|
||||
// Protects actors map for concurrent writes.
|
||||
mu sync.RWMutex
|
||||
actors map[rbac.SubjectType]rbac.Subject
|
||||
}
|
||||
|
||||
var _ RequestLogger = &SlogRequestLogger{}
|
||||
@@ -79,6 +87,7 @@ func NewRequestLogger(log slog.Logger, message string, start time.Time) RequestL
|
||||
written: false,
|
||||
message: message,
|
||||
start: start,
|
||||
actors: make(map[rbac.SubjectType]rbac.Subject),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +95,52 @@ func (c *SlogRequestLogger) WithFields(fields ...slog.Field) {
|
||||
c.log = c.log.With(fields...)
|
||||
}
|
||||
|
||||
func (c *SlogRequestLogger) WithAuthContext(actor rbac.Subject) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.actors[actor.Type] = actor
|
||||
}
|
||||
|
||||
func (c *SlogRequestLogger) addAuthContextFields() {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
usr, ok := c.actors[rbac.SubjectTypeUser]
|
||||
if ok {
|
||||
c.log = c.log.With(
|
||||
slog.F("requestor_id", usr.ID),
|
||||
slog.F("requestor_name", usr.FriendlyName),
|
||||
slog.F("requestor_email", usr.Email),
|
||||
)
|
||||
} else {
|
||||
// If there is no user, we log the requestor name for the first
|
||||
// actor in a defined order.
|
||||
for _, v := range actorLogOrder {
|
||||
subj, ok := c.actors[v]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
c.log = c.log.With(
|
||||
slog.F("requestor_name", subj.FriendlyName),
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var actorLogOrder = []rbac.SubjectType{
|
||||
rbac.SubjectTypeAutostart,
|
||||
rbac.SubjectTypeCryptoKeyReader,
|
||||
rbac.SubjectTypeCryptoKeyRotator,
|
||||
rbac.SubjectTypeHangDetector,
|
||||
rbac.SubjectTypeNotifier,
|
||||
rbac.SubjectTypePrebuildsOrchestrator,
|
||||
rbac.SubjectTypeProvisionerd,
|
||||
rbac.SubjectTypeResourceMonitor,
|
||||
rbac.SubjectTypeSystemReadProvisionerDaemons,
|
||||
rbac.SubjectTypeSystemRestricted,
|
||||
}
|
||||
|
||||
func (c *SlogRequestLogger) WriteLog(ctx context.Context, status int) {
|
||||
if c.written {
|
||||
return
|
||||
@@ -93,11 +148,32 @@ func (c *SlogRequestLogger) WriteLog(ctx context.Context, status int) {
|
||||
c.written = true
|
||||
end := time.Now()
|
||||
|
||||
// Right before we write the log, we try to find the user in the actors
|
||||
// and add the fields to the log.
|
||||
c.addAuthContextFields()
|
||||
|
||||
logger := c.log.With(
|
||||
slog.F("took", end.Sub(c.start)),
|
||||
slog.F("status_code", status),
|
||||
slog.F("latency_ms", float64(end.Sub(c.start)/time.Millisecond)),
|
||||
)
|
||||
|
||||
// If the request is routed, add the route parameters to the log.
|
||||
if chiCtx := chi.RouteContext(ctx); chiCtx != nil {
|
||||
urlParams := chiCtx.URLParams
|
||||
routeParamsFields := make([]slog.Field, 0, len(urlParams.Keys))
|
||||
|
||||
for k, v := range urlParams.Keys {
|
||||
if urlParams.Values[k] != "" {
|
||||
routeParamsFields = append(routeParamsFields, slog.F("params_"+v, urlParams.Values[k]))
|
||||
}
|
||||
}
|
||||
|
||||
if len(routeParamsFields) > 0 {
|
||||
logger = logger.With(routeParamsFields...)
|
||||
}
|
||||
}
|
||||
|
||||
// We already capture most of this information in the span (minus
|
||||
// the response body which we don't want to capture anyways).
|
||||
tracing.RunWithoutSpan(ctx, func(ctx context.Context) {
|
||||
+139
-2
@@ -1,13 +1,16 @@
|
||||
package httpmw
|
||||
package loggermw
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
@@ -79,7 +82,7 @@ func TestLoggerMiddleware_SingleRequest(t *testing.T) {
|
||||
|
||||
require.Equal(t, sink.entries[0].Message, "GET")
|
||||
|
||||
fieldsMap := make(map[string]interface{})
|
||||
fieldsMap := make(map[string]any)
|
||||
for _, field := range sink.entries[0].Fields {
|
||||
fieldsMap[field.Name] = field.Value
|
||||
}
|
||||
@@ -156,6 +159,140 @@ func TestLoggerMiddleware_WebSocket(t *testing.T) {
|
||||
require.Len(t, sink.entries, 1, "log was written twice")
|
||||
}
|
||||
|
||||
func TestRequestLogger_HTTPRouteParams(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sink := &fakeSink{}
|
||||
logger := slog.Make(sink)
|
||||
logger = logger.Leveled(slog.LevelDebug)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
|
||||
defer cancel()
|
||||
|
||||
chiCtx := chi.NewRouteContext()
|
||||
chiCtx.URLParams.Add("workspace", "test-workspace")
|
||||
chiCtx.URLParams.Add("agent", "test-agent")
|
||||
|
||||
ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
|
||||
|
||||
// Create a test handler to simulate an HTTP request
|
||||
testHandler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
_, _ = rw.Write([]byte("OK"))
|
||||
})
|
||||
|
||||
// Wrap the test handler with the Logger middleware
|
||||
loggerMiddleware := Logger(logger)
|
||||
wrappedHandler := loggerMiddleware(testHandler)
|
||||
|
||||
// Create a test HTTP request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/test-path/}", nil)
|
||||
require.NoError(t, err, "failed to create request")
|
||||
|
||||
sw := &tracing.StatusWriter{ResponseWriter: httptest.NewRecorder()}
|
||||
|
||||
// Serve the request
|
||||
wrappedHandler.ServeHTTP(sw, req)
|
||||
|
||||
fieldsMap := make(map[string]any)
|
||||
for _, field := range sink.entries[0].Fields {
|
||||
fieldsMap[field.Name] = field.Value
|
||||
}
|
||||
|
||||
// Check that the log contains the expected fields
|
||||
requiredFields := []string{"workspace", "agent"}
|
||||
for _, field := range requiredFields {
|
||||
_, exists := fieldsMap["params_"+field]
|
||||
require.True(t, exists, "field %q is missing in log fields", field)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestLogger_RouteParamsLogging(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]string
|
||||
expectedFields []string
|
||||
}{
|
||||
{
|
||||
name: "EmptyParams",
|
||||
params: map[string]string{},
|
||||
expectedFields: []string{},
|
||||
},
|
||||
{
|
||||
name: "SingleParam",
|
||||
params: map[string]string{
|
||||
"workspace": "test-workspace",
|
||||
},
|
||||
expectedFields: []string{"params_workspace"},
|
||||
},
|
||||
{
|
||||
name: "MultipleParams",
|
||||
params: map[string]string{
|
||||
"workspace": "test-workspace",
|
||||
"agent": "test-agent",
|
||||
"user": "test-user",
|
||||
},
|
||||
expectedFields: []string{"params_workspace", "params_agent", "params_user"},
|
||||
},
|
||||
{
|
||||
name: "EmptyValueParam",
|
||||
params: map[string]string{
|
||||
"workspace": "test-workspace",
|
||||
"agent": "",
|
||||
},
|
||||
expectedFields: []string{"params_workspace"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sink := &fakeSink{}
|
||||
logger := slog.Make(sink)
|
||||
logger = logger.Leveled(slog.LevelDebug)
|
||||
|
||||
// Create a route context with the test parameters
|
||||
chiCtx := chi.NewRouteContext()
|
||||
for key, value := range tt.params {
|
||||
chiCtx.URLParams.Add(key, value)
|
||||
}
|
||||
|
||||
ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
|
||||
logCtx := NewRequestLogger(logger, "GET", time.Now())
|
||||
|
||||
// Write the log
|
||||
logCtx.WriteLog(ctx, http.StatusOK)
|
||||
|
||||
require.Len(t, sink.entries, 1, "expected exactly one log entry")
|
||||
|
||||
// Convert fields to map for easier checking
|
||||
fieldsMap := make(map[string]any)
|
||||
for _, field := range sink.entries[0].Fields {
|
||||
fieldsMap[field.Name] = field.Value
|
||||
}
|
||||
|
||||
// Verify expected fields are present
|
||||
for _, field := range tt.expectedFields {
|
||||
value, exists := fieldsMap[field]
|
||||
require.True(t, exists, "field %q should be present in log", field)
|
||||
require.Equal(t, tt.params[strings.TrimPrefix(field, "params_")], value, "field %q has incorrect value", field)
|
||||
}
|
||||
|
||||
// Verify no unexpected fields are present
|
||||
for field := range fieldsMap {
|
||||
if field == "took" || field == "status_code" || field == "latency_ms" {
|
||||
continue // Skip standard fields
|
||||
}
|
||||
require.True(t, slices.Contains(tt.expectedFields, field), "unexpected field %q in log", field)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type fakeSink struct {
|
||||
entries []slog.SinkEntry
|
||||
newEntries chan slog.SinkEntry
|
||||
+14
-1
@@ -1,5 +1,5 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: github.com/coder/coder/v2/coderd/httpmw (interfaces: RequestLogger)
|
||||
// Source: github.com/coder/coder/v2/coderd/httpmw/loggermw (interfaces: RequestLogger)
|
||||
//
|
||||
// Generated by this command:
|
||||
//
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
reflect "reflect"
|
||||
|
||||
slog "cdr.dev/slog"
|
||||
rbac "github.com/coder/coder/v2/coderd/rbac"
|
||||
gomock "go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
@@ -41,6 +42,18 @@ func (m *MockRequestLogger) EXPECT() *MockRequestLoggerMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// WithAuthContext mocks base method.
|
||||
func (m *MockRequestLogger) WithAuthContext(actor rbac.Subject) {
|
||||
m.ctrl.T.Helper()
|
||||
m.ctrl.Call(m, "WithAuthContext", actor)
|
||||
}
|
||||
|
||||
// WithAuthContext indicates an expected call of WithAuthContext.
|
||||
func (mr *MockRequestLoggerMockRecorder) WithAuthContext(actor any) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithAuthContext", reflect.TypeOf((*MockRequestLogger)(nil).WithAuthContext), actor)
|
||||
}
|
||||
|
||||
// WithFields mocks base method.
|
||||
func (m *MockRequestLogger) WithFields(fields ...slog.Field) {
|
||||
m.ctrl.T.Helper()
|
||||
@@ -6,8 +6,11 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"cdr.dev/slog"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
)
|
||||
|
||||
@@ -81,6 +84,14 @@ func ExtractWorkspaceAgentParam(db database.Store) func(http.Handler) http.Handl
|
||||
|
||||
ctx = context.WithValue(ctx, workspaceAgentParamContextKey{}, agent)
|
||||
chi.RouteContext(ctx).URLParams.Add("workspace", build.WorkspaceID.String())
|
||||
|
||||
if rlogger := loggermw.RequestLoggerFromContext(ctx); rlogger != nil {
|
||||
rlogger.WithFields(
|
||||
slog.F("workspace_name", resource.Name),
|
||||
slog.F("agent_name", agent.Name),
|
||||
)
|
||||
}
|
||||
|
||||
next.ServeHTTP(rw, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -9,8 +9,11 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"cdr.dev/slog"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
)
|
||||
|
||||
@@ -48,6 +51,11 @@ func ExtractWorkspaceParam(db database.Store) func(http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
ctx = context.WithValue(ctx, workspaceParamContextKey{}, workspace)
|
||||
|
||||
if rlogger := loggermw.RequestLoggerFromContext(ctx); rlogger != nil {
|
||||
rlogger.WithFields(slog.F("workspace_name", workspace.Name))
|
||||
}
|
||||
|
||||
next.ServeHTTP(rw, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -154,6 +162,13 @@ func ExtractWorkspaceAndAgentParam(db database.Store) func(http.Handler) http.Ha
|
||||
|
||||
ctx = context.WithValue(ctx, workspaceParamContextKey{}, workspace)
|
||||
ctx = context.WithValue(ctx, workspaceAgentParamContextKey{}, agent)
|
||||
|
||||
if rlogger := loggermw.RequestLoggerFromContext(ctx); rlogger != nil {
|
||||
rlogger.WithFields(
|
||||
slog.F("workspace_name", workspace.Name),
|
||||
slog.F("agent_name", agent.Name),
|
||||
)
|
||||
}
|
||||
next.ServeHTTP(rw, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/database/dbtime"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/httpmw"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
||||
"github.com/coder/coder/v2/coderd/notifications"
|
||||
"github.com/coder/coder/v2/coderd/pubsub"
|
||||
markdown "github.com/coder/coder/v2/coderd/render"
|
||||
@@ -220,7 +221,7 @@ func (api *API) watchInboxNotifications(rw http.ResponseWriter, r *http.Request)
|
||||
defer encoder.Close(websocket.StatusNormalClosure)
|
||||
|
||||
// Log the request immediately instead of after it completes.
|
||||
httpmw.RequestLoggerFromContext(ctx).WriteLog(ctx, http.StatusAccepted)
|
||||
loggermw.RequestLoggerFromContext(ctx).WriteLog(ctx, http.StatusAccepted)
|
||||
|
||||
for {
|
||||
select {
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/database/pubsub"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/httpmw"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
||||
"github.com/coder/coder/v2/coderd/rbac"
|
||||
"github.com/coder/coder/v2/coderd/rbac/policy"
|
||||
"github.com/coder/coder/v2/coderd/util/slice"
|
||||
@@ -555,7 +556,7 @@ func (f *logFollower) follow() {
|
||||
}
|
||||
|
||||
// Log the request immediately instead of after it completes.
|
||||
httpmw.RequestLoggerFromContext(f.ctx).WriteLog(f.ctx, http.StatusAccepted)
|
||||
loggermw.RequestLoggerFromContext(f.ctx).WriteLog(f.ctx, http.StatusAccepted)
|
||||
|
||||
// no need to wait if the job is done
|
||||
if f.complete {
|
||||
|
||||
@@ -19,8 +19,8 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/database/dbmock"
|
||||
"github.com/coder/coder/v2/coderd/database/dbtime"
|
||||
"github.com/coder/coder/v2/coderd/database/pubsub"
|
||||
"github.com/coder/coder/v2/coderd/httpmw"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermock"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw/loggermock"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/provisionersdk"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
@@ -309,7 +309,7 @@ func Test_logFollower_EndOfLogs(t *testing.T) {
|
||||
|
||||
mockLogger := loggermock.NewMockRequestLogger(ctrl)
|
||||
mockLogger.EXPECT().WriteLog(gomock.Any(), http.StatusAccepted).Times(1)
|
||||
ctx = httpmw.WithRequestLogger(ctx, mockLogger)
|
||||
ctx = loggermw.WithRequestLogger(ctx, mockLogger)
|
||||
|
||||
// we need an HTTP server to get a websocket
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -58,6 +58,23 @@ func hashAuthorizeCall(actor Subject, action policy.Action, object Object) [32]b
|
||||
return hashOut
|
||||
}
|
||||
|
||||
// SubjectType represents the type of subject in the RBAC system.
|
||||
type SubjectType string
|
||||
|
||||
const (
|
||||
SubjectTypeUser SubjectType = "user"
|
||||
SubjectTypeProvisionerd SubjectType = "provisionerd"
|
||||
SubjectTypeAutostart SubjectType = "autostart"
|
||||
SubjectTypeHangDetector SubjectType = "hang_detector"
|
||||
SubjectTypeResourceMonitor SubjectType = "resource_monitor"
|
||||
SubjectTypeCryptoKeyRotator SubjectType = "crypto_key_rotator"
|
||||
SubjectTypeCryptoKeyReader SubjectType = "crypto_key_reader"
|
||||
SubjectTypePrebuildsOrchestrator SubjectType = "prebuilds_orchestrator"
|
||||
SubjectTypeSystemReadProvisionerDaemons SubjectType = "system_read_provisioner_daemons"
|
||||
SubjectTypeSystemRestricted SubjectType = "system_restricted"
|
||||
SubjectTypeNotifier SubjectType = "notifier"
|
||||
)
|
||||
|
||||
// Subject is a struct that contains all the elements of a subject in an rbac
|
||||
// authorize.
|
||||
type Subject struct {
|
||||
@@ -67,6 +84,14 @@ type Subject struct {
|
||||
// external workspace proxy or other service type actor.
|
||||
FriendlyName string
|
||||
|
||||
// Email is entirely optional and is used for logging and debugging
|
||||
// It is not used in any functional way.
|
||||
Email string
|
||||
|
||||
// Type indicates what kind of subject this is (user, system, provisioner, etc.)
|
||||
// It is not used in any functional way, only for logging.
|
||||
Type SubjectType
|
||||
|
||||
ID string
|
||||
Roles ExpandableRoles
|
||||
Groups []string
|
||||
|
||||
@@ -33,6 +33,7 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/externalauth"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/httpmw"
|
||||
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
||||
"github.com/coder/coder/v2/coderd/jwtutils"
|
||||
"github.com/coder/coder/v2/coderd/rbac"
|
||||
"github.com/coder/coder/v2/coderd/rbac/policy"
|
||||
@@ -551,7 +552,7 @@ func (api *API) workspaceAgentLogs(rw http.ResponseWriter, r *http.Request) {
|
||||
defer t.Stop()
|
||||
|
||||
// Log the request immediately instead of after it completes.
|
||||
httpmw.RequestLoggerFromContext(ctx).WriteLog(ctx, http.StatusAccepted)
|
||||
loggermw.RequestLoggerFromContext(ctx).WriteLog(ctx, http.StatusAccepted)
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
@@ -929,7 +930,7 @@ func (api *API) derpMapUpdates(rw http.ResponseWriter, r *http.Request) {
|
||||
defer encoder.Close(websocket.StatusGoingAway)
|
||||
|
||||
// Log the request immediately instead of after it completes.
|
||||
httpmw.RequestLoggerFromContext(ctx).WriteLog(ctx, http.StatusAccepted)
|
||||
loggermw.RequestLoggerFromContext(ctx).WriteLog(ctx, http.StatusAccepted)
|
||||
|
||||
go func(ctx context.Context) {
|
||||
// TODO(mafredri): Is this too frequent? Use separate ping disconnect timeout?
|
||||
@@ -1329,7 +1330,7 @@ func (api *API) watchWorkspaceAgentMetadata(
|
||||
defer sendTicker.Stop()
|
||||
|
||||
// Log the request immediately instead of after it completes.
|
||||
httpmw.RequestLoggerFromContext(ctx).WriteLog(ctx, http.StatusAccepted)
|
||||
loggermw.RequestLoggerFromContext(ctx).WriteLog(ctx, http.StatusAccepted)
|
||||
|
||||
// Send initial metadata.
|
||||
sendMetadata()
|
||||
|
||||
Reference in New Issue
Block a user