Skip to content

feat: add audit logs for dormancy events #15298

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 14 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
1 change: 1 addition & 0 deletions cli/server_createadminuser.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ func (r *RootCmd) newCreateAdminUserCommand() *serpent.Command {
UpdatedAt: dbtime.Now(),
RBACRoles: []string{rbac.RoleOwner().String()},
LoginType: database.LoginTypePassword,
Status: "",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we pass "" here? Should we just pass active?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally I would omit it but the linter doesn't like leaving it out. It doesn't really matter what this is created as, so "" just does the default behavior which is dormant.

})
if err != nil {
return xerrors.Errorf("insert user: %w", err)
Expand Down
8 changes: 8 additions & 0 deletions coderd/apidoc/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions coderd/apidoc/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions coderd/audit/fields.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package audit

import (
"context"
"encoding/json"

"cdr.dev/slog"
)

type BackgroundSubsystem string

const (
BackgroundSubsystemDormancy BackgroundSubsystem = "dormancy"
)

func BackgroundTaskFields(ctx context.Context, logger slog.Logger, subsystem BackgroundSubsystem) []byte {
af := map[string]string{
"automatic_actor": "coder",
"automatic_subsystem": string(subsystem),
}

wriBytes, err := json.Marshal(af)
if err != nil {
logger.Error(ctx, "marshal additional fields for dormancy audit", slog.Error(err))
return []byte("{}")
}

return wriBytes
}
13 changes: 7 additions & 6 deletions coderd/audit/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,13 @@ type BackgroundAuditParams[T Auditable] struct {
Audit Auditor
Log slog.Logger

UserID uuid.UUID
RequestID uuid.UUID
Status int
Action database.AuditAction
OrganizationID uuid.UUID
IP string
UserID uuid.UUID
RequestID uuid.UUID
Status int
Action database.AuditAction
OrganizationID uuid.UUID
IP string
// todo: this should automatically marshal an interface{} instead of accepting a raw message.
AdditionalFields json.RawMessage

New T
Expand Down
1 change: 1 addition & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,7 @@ func New(options *Options) *API {

apiKeyMiddleware := httpmw.ExtractAPIKeyMW(httpmw.ExtractAPIKeyConfig{
DB: options.Database,
HandleDormancy: api.ActivateDormantUser,
OAuth2Configs: oauthConfigs,
RedirectToLogin: false,
DisableSessionExpiryRefresh: options.DeploymentValues.Sessions.DisableExpiryRefresh.Value(),
Expand Down
3 changes: 3 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,9 @@ func createAnotherUserRetry(t testing.TB, client *codersdk.Client, organizationI
Name: RandomName(t),
Password: "SomeSecurePassword!",
OrganizationIDs: organizationIDs,
// Always create users as active in tests to ignore an extra audit log
// when logging in.
UserStatus: ptr.Ref(codersdk.UserStatusActive),
}
for _, m := range mutators {
m(&req)
Expand Down
1 change: 1 addition & 0 deletions coderd/database/dbgen/dbgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ func User(t testing.TB, db database.Store, orig database.User) database.User {
UpdatedAt: takeFirst(orig.UpdatedAt, dbtime.Now()),
RBACRoles: takeFirstSlice(orig.RBACRoles, []string{}),
LoginType: takeFirst(orig.LoginType, database.LoginTypePassword),
Status: string(takeFirst(orig.Status, database.UserStatusDormant)),
})
require.NoError(t, err, "insert user")

Expand Down
8 changes: 7 additions & 1 deletion coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -7709,6 +7709,11 @@ func (q *FakeQuerier) InsertUser(_ context.Context, arg database.InsertUserParam
}
}

status := database.UserStatusDormant
if arg.Status != "" {
status = database.UserStatus(arg.Status)
}

user := database.User{
ID: arg.ID,
Email: arg.Email,
Expand All @@ -7717,7 +7722,7 @@ func (q *FakeQuerier) InsertUser(_ context.Context, arg database.InsertUserParam
UpdatedAt: arg.UpdatedAt,
Username: arg.Username,
Name: arg.Name,
Status: database.UserStatusDormant,
Status: status,
RBACRoles: arg.RBACRoles,
LoginType: arg.LoginType,
}
Expand Down Expand Up @@ -8640,6 +8645,7 @@ func (q *FakeQuerier) UpdateInactiveUsersToDormant(_ context.Context, params dat
updated = append(updated, database.UpdateInactiveUsersToDormantRow{
ID: user.ID,
Email: user.Email,
Username: user.Username,
LastSeenAt: user.LastSeenAt,
})
}
Expand Down
21 changes: 17 additions & 4 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 8 additions & 3 deletions coderd/database/queries/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,15 @@ INSERT INTO
created_at,
updated_at,
rbac_roles,
login_type
login_type,
status
)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *;
($1, $2, $3, $4, $5, $6, $7, $8, $9,
-- if the status passed in is empty, fallback to dormant, which is what
-- we were doing before.
COALESCE(NULLIF(@status::text, '')::user_status, 'dormant'::user_status)
) RETURNING *;
Comment on lines +74 to +78
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we handle this as a special case? Shouldn't we expect the status to be provided?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't really want to leak the previous default behavior out into the API code. I think it makes more sense to do the default behavior here, which is what was happening before when it wasn't being inserted.


-- name: UpdateUserProfile :one
UPDATE
Expand Down Expand Up @@ -286,7 +291,7 @@ SET
WHERE
last_seen_at < @last_seen_after :: timestamp
AND status = 'active'::user_status
RETURNING id, email, last_seen_at;
RETURNING id, email, username, last_seen_at;

-- AllUserIDs returns all UserIDs regardless of user status or deletion.
-- name: AllUserIDs :many
Expand Down
21 changes: 7 additions & 14 deletions coderd/httpmw/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ const (

type ExtractAPIKeyConfig struct {
DB database.Store
HandleDormancy func(ctx context.Context, u database.User) database.User
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I generally dislike these passthrough functions and given that we pass the same implementation in the enterprise path, is it reasonable to move this function off this config (and the API struct) and just have it as a package level function somewhere?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reasonable

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah the passthrough is necessary because we can't import audit in httpmw since audit already imports httpmw itself, so I have to result to this jank

OAuth2Configs *OAuth2Configs
RedirectToLogin bool
DisableSessionExpiryRefresh bool
Expand Down Expand Up @@ -414,21 +415,13 @@ func ExtractAPIKey(rw http.ResponseWriter, r *http.Request, cfg ExtractAPIKeyCon
})
}

if userStatus == database.UserStatusDormant {
// If coder confirms that the dormant user is valid, it can switch their account to active.
// nolint:gocritic
u, err := cfg.DB.UpdateUserStatus(dbauthz.AsSystemRestricted(ctx), database.UpdateUserStatusParams{
ID: key.UserID,
Status: database.UserStatusActive,
UpdatedAt: dbtime.Now(),
if userStatus == database.UserStatusDormant && cfg.HandleDormancy != nil {
id, _ := uuid.Parse(actor.ID)
cfg.HandleDormancy(ctx, database.User{
ID: id,
Username: actor.FriendlyName,
Status: userStatus,
})
if err != nil {
return write(http.StatusInternalServerError, codersdk.Response{
Message: internalErrorMessage,
Detail: fmt.Sprintf("can't activate a dormant user: %s", err.Error()),
})
}
userStatus = u.Status
}

if userStatus != database.UserStatusActive {
Expand Down
1 change: 1 addition & 0 deletions coderd/provisionerdserver/provisionerdserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,7 @@ func (s *server) FailJob(ctx context.Context, failJob *proto.FailedJob) (*proto.
wriBytes, err := json.Marshal(buildResourceInfo)
if err != nil {
s.Logger.Error(ctx, "marshal workspace resource info for failed job", slog.Error(err))
wriBytes = []byte("{}")
}

bag := audit.BaggageFromContext(ctx)
Expand Down
65 changes: 35 additions & 30 deletions coderd/userauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/coder/coder/v2/coderd/cryptokeys"
"github.com/coder/coder/v2/coderd/idpsync"
"github.com/coder/coder/v2/coderd/jwtutils"
"github.com/coder/coder/v2/coderd/util/ptr"

"github.com/coder/coder/v2/coderd/apikey"
"github.com/coder/coder/v2/coderd/audit"
Expand Down Expand Up @@ -565,21 +566,7 @@ func (api *API) loginRequest(ctx context.Context, rw http.ResponseWriter, req co
return user, rbac.Subject{}, false
}

if user.Status == database.UserStatusDormant {
//nolint:gocritic // System needs to update status of the user account (dormant -> active).
user, err = api.Database.UpdateUserStatus(dbauthz.AsSystemRestricted(ctx), database.UpdateUserStatusParams{
ID: user.ID,
Status: database.UserStatusActive,
UpdatedAt: dbtime.Now(),
})
if err != nil {
logger.Error(ctx, "unable to update user status to active", slog.Error(err))
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error occurred. Try again later, or contact an admin for assistance.",
})
return user, rbac.Subject{}, false
}
}
user = api.ActivateDormantUser(ctx, user)

subject, userStatus, err := httpmw.UserRBACSubject(ctx, api.Database, user.ID, rbac.ScopeAll)
if err != nil {
Expand All @@ -601,6 +588,36 @@ func (api *API) loginRequest(ctx context.Context, rw http.ResponseWriter, req co
return user, subject, true
}

func (api *API) ActivateDormantUser(ctx context.Context, user database.User) database.User {
if user.ID == uuid.Nil || user.Status != database.UserStatusDormant {
return user
}

//nolint:gocritic // System needs to update status of the user account (dormant -> active).
newUser, err := api.Database.UpdateUserStatus(dbauthz.AsSystemRestricted(ctx), database.UpdateUserStatusParams{
ID: user.ID,
Status: database.UserStatusActive,
UpdatedAt: dbtime.Now(),
})
if err != nil {
api.Logger.Error(ctx, "unable to update user status to active", slog.Error(err))
return user
}

audit.BackgroundAudit(ctx, &audit.BackgroundAuditParams[database.User]{
Audit: *api.Auditor.Load(),
Log: api.Logger,
UserID: user.ID,
Action: database.AuditActionWrite,
Old: user,
New: newUser,
Status: http.StatusOK,
AdditionalFields: audit.BackgroundTaskFields(ctx, api.Logger, audit.BackgroundSubsystemDormancy),
})

return newUser
}

// Clear the user's session cookie.
//
// @Summary Log out user
Expand Down Expand Up @@ -1388,9 +1405,10 @@ func (api *API) oauthLogin(r *http.Request, params *oauthLoginParams) ([]*http.C
ctx = r.Context()
user database.User
cookies []*http.Cookie
logger = api.Logger.Named(userAuthLoggerName)
)

params.User = api.ActivateDormantUser(ctx, params.User)

var isConvertLoginType bool
err := api.Database.InTx(func(tx database.Store) error {
var (
Expand Down Expand Up @@ -1490,6 +1508,7 @@ func (api *API) oauthLogin(r *http.Request, params *oauthLoginParams) ([]*http.C
Email: params.Email,
Username: params.Username,
OrganizationIDs: orgIDs,
UserStatus: ptr.Ref(codersdk.UserStatusActive),
},
LoginType: params.LoginType,
accountCreatorName: "oauth",
Expand All @@ -1499,20 +1518,6 @@ func (api *API) oauthLogin(r *http.Request, params *oauthLoginParams) ([]*http.C
}
}

// Activate dormant user on sign-in
if user.Status == database.UserStatusDormant {
//nolint:gocritic // System needs to update status of the user account (dormant -> active).
user, err = tx.UpdateUserStatus(dbauthz.AsSystemRestricted(ctx), database.UpdateUserStatusParams{
ID: user.ID,
Status: database.UserStatusActive,
UpdatedAt: dbtime.Now(),
})
if err != nil {
logger.Error(ctx, "unable to update user status to active", slog.Error(err))
return xerrors.Errorf("update user status: %w", err)
}
}

debugContext, err := json.Marshal(params.DebugContext)
if err != nil {
return xerrors.Errorf("marshal debug context: %w", err)
Expand Down
Loading
Loading