Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: add role-based token lifetime configuration#18179

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
ThomasK33 wants to merge3 commits intomain
base:main
Choose a base branch
Loading
fromthomask33/feat_add_role-based_token_lifetime_configuration
Draft
Show file tree
Hide file tree
Changes fromall 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
2 changes: 2 additions & 0 deletions.swaggo
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,3 +6,5 @@ replace time.Duration int64
replace github.com/coder/coder/v2/codersdk.ProvisionerType string
// Do not render netip.Addr
replace netip.Addr string
// Do not render cel.Program
replace github.com/google/cel-go/cel.Program object
5 changes: 5 additions & 0 deletionscli/server.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -813,6 +813,11 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
return xerrors.Errorf("set deployment id: %w", err)
}

// Compile the role token lifetime CEL expression
if _, err := vals.Sessions.CompiledMaximumTokenDurationProgram(); err != nil {
return xerrors.Errorf("failed to compile token lifetime expression: %w", err)
}

// Manage push notifications.
experiments := coderd.ReadExperiments(options.Logger, options.DeploymentValues.Experiments.Value())
if experiments.Enabled(codersdk.ExperimentWebPush) {
Expand Down
11 changes: 11 additions & 0 deletionscli/testdata/coder_server_--help.golden
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,17 @@ OPTIONS:
Separate multiple experiments with commas, or enter '*' to opt-in to
all available experiments.

--max-token-lifetime-expression string, $CODER_MAX_TOKEN_LIFETIME_EXPRESSION
An expr expression that determines the maximum token lifetime based on
user attributes. The expression has access to 'subject'
(coderd/expr.Subject with fields: ID, Email, Groups, Roles),
'globalMaxDuration' (time.Duration as int64 nanoseconds), and
'defaultDuration' (time.Duration as int64 nanoseconds). Must return a
duration as int64 nanoseconds (e.g., duration("168h")). Example:
'any(subject.Roles, .Name == "owner") ? duration("720h") :
duration("168h")'. See https://github.com/expr-lang/expr for expr
expression syntax and examples.

--postgres-auth password|awsiamrds, $CODER_PG_AUTH (default: password)
Type of auth to use when connecting to postgres. For AWS RDS, using
IAM authentication (awsiamrds) is recommended.
Expand Down
9 changes: 9 additions & 0 deletionscli/testdata/server-config.yaml.golden
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -445,6 +445,15 @@ experiments: []
# performed once per day.
# (default: false, type: bool)
updateCheck: false
# An expr expression that determines the maximum token lifetime based on user
# attributes. The expression has access to 'subject' (coderd/expr.Subject with
# fields: ID, Email, Groups, Roles), 'globalMaxDuration' (time.Duration as int64
# nanoseconds), and 'defaultDuration' (time.Duration as int64 nanoseconds). Must
# return a duration as int64 nanoseconds (e.g., duration("168h")). Example:
# 'any(subject.Roles, .Name == "owner") ? duration("720h") : duration("168h")'.
# See https://github.com/expr-lang/expr for expr expression syntax and examples.
# (default: <unset>, type: string)
maxTokenLifetimeExpression: ""
# The default lifetime duration for API tokens. This value is used when creating a
# token without specifying a duration, such as when authenticating the CLI or an
# IDE plugin.
Expand Down
11 changes: 9 additions & 2 deletionscoderd/apidoc/docs.go
View file
Open in desktop

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

6 changes: 6 additions & 0 deletionscoderd/apidoc/swagger.json
View file
Open in desktop

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

86 changes: 73 additions & 13 deletionscoderd/apikey.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@ package coderd

import (
"context"
"database/sql"
"fmt"
"net/http"
"strconv"
Expand All@@ -12,12 +13,16 @@ import (
"github.com/moby/moby/pkg/namesgenerator"
"golang.org/x/xerrors"

"github.com/expr-lang/expr"

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/apikey"
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"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/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/coderd/telemetry"
"github.com/coder/coder/v2/codersdk"
Expand DownExpand Up@@ -75,8 +80,7 @@ func (api *API) postToken(rw http.ResponseWriter, r *http.Request) {
}

if createToken.Lifetime != 0 {
err := api.validateAPIKeyLifetime(createToken.Lifetime)
if err != nil {
if err := api.validateAPIKeyLifetime(ctx, createToken.Lifetime, user.ID); err != nil {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Failed to validate create API key request.",
Detail: err.Error(),
Expand DownExpand Up@@ -338,35 +342,91 @@ func (api *API) deleteAPIKey(rw http.ResponseWriter, r *http.Request) {
// @Success 200 {object} codersdk.TokenConfig
// @Router /users/{user}/keys/tokens/tokenconfig [get]
func (api *API) tokenConfig(rw http.ResponseWriter, r *http.Request) {
values, err := api.DeploymentValues.WithoutSecrets()
if err != nil {
httpapi.InternalServerError(rw, err)
return
ctx := r.Context()

maxLifetime := api.DeploymentValues.Sessions.MaximumTokenDuration.Value()

user := httpmw.UserParam(r)
subject, _, err := httpmw.UserRBACSubject(ctx, api.Database, user.ID, rbac.ScopeAll)
if err == nil {
maxLifetime = api.getMaxTokenLifetimeForUser(ctx, subject)
}

httpapi.Write(
r.Context(), rw, http.StatusOK,
ctx, rw, http.StatusOK,
codersdk.TokenConfig{
MaxTokenLifetime:values.Sessions.MaximumTokenDuration.Value(),
MaxTokenLifetime:maxLifetime,
},
)
}

func (api *API) validateAPIKeyLifetime(lifetime time.Duration) error {
func (api *API) validateAPIKeyLifetime(ctx context.Context,lifetime time.Duration, userID uuid.UUID) error {
if lifetime <= 0 {
return xerrors.New("lifetime must be positive number greater than 0")
}

if lifetime > api.DeploymentValues.Sessions.MaximumTokenDuration.Value() {
subject, userStatus, err := httpmw.UserRBACSubject(ctx, api.Database, userID, rbac.ScopeAll)
if err != nil {
api.Logger.Error(ctx, "failed to get user RBAC subject during token validation", slog.F("user_id", userID.String()), slog.Error(err))
if xerrors.Is(err, sql.ErrNoRows) {
return xerrors.Errorf("user %s not found", userID)
}
return xerrors.Errorf("internal server error validating token lifetime for user %s", userID)
}

if userStatus != database.UserStatusActive {
return xerrors.Errorf("user %s is suspended or inactive, and cannot create tokens", userID)
}

// Get the maximum token lifetime for this user based on CEL expression
maxAllowedLifetime := api.getMaxTokenLifetimeForUser(ctx, subject)

if lifetime > maxAllowedLifetime {
return xerrors.Errorf(
"lifetime must be less than %v",
api.DeploymentValues.Sessions.MaximumTokenDuration,
"requested lifetime of %v exceeds the maximum allowed %v based on your roles",
lifetime,
maxAllowedLifetime,
)
}

return nil
}

// getMaxTokenLifetimeForUser determines the maximum token lifetime a user is entitled to
// based on their attributes and the expr expression configuration.
func (api *API) getMaxTokenLifetimeForUser(ctx context.Context, subject rbac.Subject) time.Duration {
// Compiled at startup no need to recheck here.
program, _ := api.DeploymentValues.Sessions.CompiledMaximumTokenDurationProgram()
if program == nil {
// No expression configured, use global max
return api.DeploymentValues.Sessions.MaximumTokenDuration.Value()
}

globalMax := api.DeploymentValues.Sessions.MaximumTokenDuration.Value()
defaultDuration := api.DeploymentValues.Sessions.DefaultTokenDuration.Value()

// Evaluate expr expression with typed struct
// TODO: Consider adding timeout protection in future iterations
out, err := expr.Run(program, map[string]interface{}{
"subject": subject.ExprSubject(),
"globalMaxDuration": int64(globalMax),
"defaultDuration": int64(defaultDuration),
})
if err != nil {
api.Logger.Error(ctx, "the expr evaluation failed, using default duration", slog.Error(err))
return defaultDuration
}

// Convert result to time.Duration (expr returns int64 due to AsInt64 constraint)
intVal, ok := out.(int64)
if !ok {
api.Logger.Error(ctx, "the expr expression did not return an int64, using default duration",
slog.F("result_type", fmt.Sprintf("%T", out)),
slog.F("result_value", out))
return defaultDuration
}
return time.Duration(intVal)
}

func (api *API) createAPIKey(ctx context.Context, params apikey.CreateParams) (*http.Cookie, *database.APIKey, error) {
key, sessionToken, err := apikey.Generate(params)
if err != nil {
Expand Down
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp