Skip to content

feat: add session token injection to provisioner #7461

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 12 commits into from
May 18, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
move api key generation to its own package
  • Loading branch information
sreya committed May 16, 2023
commit 3ff4539be2b0380fdb53d4fa558270d56df024ab
88 changes: 9 additions & 79 deletions coderd/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,24 @@ package coderd

import (
"context"
"crypto/sha256"
"fmt"
"net"
"net/http"
"strconv"
"time"

"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/moby/moby/pkg/namesgenerator"
"github.com/tabbed/pqtype"
"golang.org/x/xerrors"

"github.com/coder/coder/coderd/apikey"
"github.com/coder/coder/coderd/audit"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/coderd/httpmw"
"github.com/coder/coder/coderd/rbac"
"github.com/coder/coder/coderd/telemetry"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
)

// Creates a new token API key that effectively doesn't expire.
Expand Down Expand Up @@ -83,7 +80,7 @@ func (api *API) postToken(rw http.ResponseWriter, r *http.Request) {
return
}

cookie, key, err := api.createAPIKey(ctx, createAPIKeyParams{
cookie, key, err := api.createAPIKey(ctx, apikey.CreateParams{
UserID: user.ID,
LoginType: database.LoginTypeToken,
ExpiresAt: database.Now().Add(lifeTime),
Expand Down Expand Up @@ -127,7 +124,7 @@ func (api *API) postAPIKey(rw http.ResponseWriter, r *http.Request) {
user := httpmw.UserParam(r)

lifeTime := time.Hour * 24 * 7
cookie, _, err := api.createAPIKey(ctx, createAPIKeyParams{
cookie, _, err := api.createAPIKey(ctx, apikey.CreateParams{
UserID: user.ID,
LoginType: database.LoginTypePassword,
RemoteAddr: r.RemoteAddr,
Expand Down Expand Up @@ -359,21 +356,6 @@ func (api *API) tokenConfig(rw http.ResponseWriter, r *http.Request) {
)
}

// Generates a new ID and secret for an API key.
func GenerateAPIKeyIDSecret() (id string, secret string, err error) {
// Length of an API Key ID.
id, err = cryptorand.String(10)
if err != nil {
return "", "", err
}
// Length of an API Key secret.
secret, err = cryptorand.String(22)
if err != nil {
return "", "", err
}
return id, secret, nil
}

type createAPIKeyParams struct {
UserID uuid.UUID
RemoteAddr string
Expand Down Expand Up @@ -401,79 +383,27 @@ func (api *API) validateAPIKeyLifetime(lifetime time.Duration) error {
return nil
}

func (api *API) createAPIKey(ctx context.Context, params createAPIKeyParams) (*http.Cookie, *database.APIKey, error) {
keyID, keySecret, err := GenerateAPIKeyIDSecret()
func (api *API) createAPIKey(ctx context.Context, params apikey.CreateParams) (*http.Cookie, *database.APIKey, error) {
secret, key, err := apikey.Generate(params)
if err != nil {
return nil, nil, xerrors.Errorf("generate API key: %w", err)
}
hashed := sha256.Sum256([]byte(keySecret))

// Default expires at to now+lifetime, or use the configured value if not
// set.
if params.ExpiresAt.IsZero() {
if params.LifetimeSeconds != 0 {
params.ExpiresAt = database.Now().Add(time.Duration(params.LifetimeSeconds) * time.Second)
} else {
params.ExpiresAt = database.Now().Add(api.DeploymentValues.SessionDuration.Value())
params.LifetimeSeconds = int64(api.DeploymentValues.SessionDuration.Value().Seconds())
}
}
if params.LifetimeSeconds == 0 {
params.LifetimeSeconds = int64(time.Until(params.ExpiresAt).Seconds())
}

ip := net.ParseIP(params.RemoteAddr)
if ip == nil {
ip = net.IPv4(0, 0, 0, 0)
}
bitlen := len(ip) * 8

scope := database.APIKeyScopeAll
if params.Scope != "" {
scope = params.Scope
}
switch scope {
case database.APIKeyScopeAll, database.APIKeyScopeApplicationConnect:
default:
return nil, nil, xerrors.Errorf("invalid API key scope: %q", scope)
}

key, err := api.Database.InsertAPIKey(ctx, database.InsertAPIKeyParams{
ID: keyID,
UserID: params.UserID,
LifetimeSeconds: params.LifetimeSeconds,
IPAddress: pqtype.Inet{
IPNet: net.IPNet{
IP: ip,
Mask: net.CIDRMask(bitlen, bitlen),
},
Valid: true,
},
// Make sure in UTC time for common time zone
ExpiresAt: params.ExpiresAt.UTC(),
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
HashedSecret: hashed[:],
LoginType: params.LoginType,
Scope: scope,
TokenName: params.TokenName,
})
newkey, err := api.Database.InsertAPIKey(ctx, key)
if err != nil {
return nil, nil, xerrors.Errorf("insert API key: %w", err)
}

api.Telemetry.Report(&telemetry.Snapshot{
APIKeys: []telemetry.APIKey{telemetry.ConvertAPIKey(key)},
APIKeys: []telemetry.APIKey{telemetry.ConvertAPIKey(newkey)},
})

// This format is consumed by the APIKey middleware.
sessionToken := fmt.Sprintf("%s-%s", keyID, keySecret)
return &http.Cookie{
Name: codersdk.SessionTokenCookie,
Value: sessionToken,
Value: secret,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: api.SecureAuthCookie,
}, &key, nil
}, &newkey, nil
}
110 changes: 110 additions & 0 deletions coderd/apikey/apikey.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package apikey

import (
"crypto/sha256"
"fmt"
"net"
"time"

"github.com/google/uuid"
"github.com/tabbed/pqtype"
"golang.org/x/xerrors"

"github.com/coder/coder/coderd/database"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
)

type CreateParams struct {
UserID uuid.UUID
LoginType database.LoginType
DeploymentValues *codersdk.DeploymentValues

// Optional.
ExpiresAt time.Time
LifetimeSeconds int64
Scope database.APIKeyScope
TokenName string
RemoteAddr string
}

// Generate generates an API key, returning the key as a string as well as the
// database representation. It is the responsibility of the caller to insert it
// into the database.
func Generate(params CreateParams) (string, database.InsertAPIKeyParams, error) {
keyID, keySecret, err := generateKey()
if err != nil {
return "", database.InsertAPIKeyParams{}, xerrors.Errorf("generate API key: %w", err)
}

hashed := sha256.Sum256([]byte(keySecret))

// Default expires at to now+lifetime, or use the configured value if not
// set.
if params.ExpiresAt.IsZero() {
if params.LifetimeSeconds != 0 {
params.ExpiresAt = database.Now().Add(time.Duration(params.LifetimeSeconds) * time.Second)
} else {
params.ExpiresAt = database.Now().Add(params.DeploymentValues.SessionDuration.Value())
params.LifetimeSeconds = int64(params.DeploymentValues.SessionDuration.Value().Seconds())
}
}
if params.LifetimeSeconds == 0 {
params.LifetimeSeconds = int64(time.Until(params.ExpiresAt).Seconds())
}

ip := net.ParseIP(params.RemoteAddr)
if ip == nil {
ip = net.IPv4(0, 0, 0, 0)
}

bitlen := len(ip) * 8

scope := database.APIKeyScopeAll
if params.Scope != "" {
scope = params.Scope
}
switch scope {
case database.APIKeyScopeAll, database.APIKeyScopeApplicationConnect:
default:
return "", database.InsertAPIKeyParams{}, xerrors.Errorf("invalid API key scope: %q", scope)
}

keyStr := fmt.Sprintf("%s-%s", keyID, keySecret)

return keyStr, database.InsertAPIKeyParams{
ID: keyID,
UserID: params.UserID,
LifetimeSeconds: params.LifetimeSeconds,
IPAddress: pqtype.Inet{
IPNet: net.IPNet{
IP: ip,
Mask: net.CIDRMask(bitlen, bitlen),
},
Valid: true,
},
// Make sure in UTC time for common time zone
ExpiresAt: params.ExpiresAt.UTC(),
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
HashedSecret: hashed[:],
LoginType: params.LoginType,
Scope: scope,
TokenName: params.TokenName,
}, nil
}

// generateKey a new ID and secret for an API key.
func generateKey() (id string, secret string, err error) {
// Length of an API Key ID.
id, err = cryptorand.String(10)
if err != nil {
return "", "", err
}
// Length of an API Key secret.
secret, err = cryptorand.String(22)
if err != nil {
return "", "", err
}
return id, secret, nil
}
52 changes: 9 additions & 43 deletions coderd/provisionerdserver/provisionerdserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package provisionerdserver

import (
"context"
"crypto/sha256"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"reflect"
Expand All @@ -29,6 +27,7 @@ import (

"cdr.dev/slog"

"github.com/coder/coder/coderd/apikey"
"github.com/coder/coder/coderd/audit"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/database/dbauthz"
Expand All @@ -39,7 +38,6 @@ import (
"github.com/coder/coder/coderd/telemetry"
"github.com/coder/coder/coderd/tracing"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
"github.com/coder/coder/provisioner"
"github.com/coder/coder/provisionerd/proto"
"github.com/coder/coder/provisionersdk"
Expand Down Expand Up @@ -1424,28 +1422,16 @@ func workspaceSessionTokenName(workspace database.Workspace) string {
return fmt.Sprintf("%s_%s_session_token", workspace.OwnerID, workspace.ID)
}

// Generates a new ID and secret for an API key.
// TODO put API key logic in separate package.
func GenerateAPIKeyIDSecret() (id string, secret string, err error) {
// Length of an API Key ID.
id, err = cryptorand.String(10)
if err != nil {
return "", "", err
}
// Length of an API Key secret.
secret, err = cryptorand.String(22)
if err != nil {
return "", "", err
}
return id, secret, nil
}

func (server *Server) regenerateSessionToken(ctx context.Context, user database.User, workspace database.Workspace) (string, error) {
id, secret, err := GenerateAPIKeyIDSecret()
secret, newkey, err := apikey.Generate(apikey.CreateParams{
UserID: user.ID,
LoginType: user.LoginType,
DeploymentValues: server.DeploymentValues,
TokenName: workspaceSessionTokenName(workspace),
})
if err != nil {
return "", xerrors.Errorf("generate API key: %w", err)
}
hashed := sha256.Sum256([]byte(secret))

err = server.Database.InTx(
func(tx database.Store) error {
Expand All @@ -1463,27 +1449,7 @@ func (server *Server) regenerateSessionToken(ctx context.Context, user database.
return xerrors.Errorf("get api key by name: %w", err)
}

ip := net.IPv4(0, 0, 0, 0)
bitlen := len(ip) * 8
_, err = tx.InsertAPIKey(ctx, database.InsertAPIKeyParams{
ID: id,
UserID: workspace.OwnerID,
LifetimeSeconds: int64(server.DeploymentValues.MaxTokenLifetime.Value().Seconds()),
ExpiresAt: database.Now().Add(server.DeploymentValues.MaxTokenLifetime.Value()).UTC(),
IPAddress: pqtype.Inet{
IPNet: net.IPNet{
IP: ip,
Mask: net.CIDRMask(bitlen, bitlen),
},
Valid: true,
},
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
HashedSecret: hashed[:],
LoginType: user.LoginType,
Scope: database.APIKeyScopeAll,
TokenName: workspaceSessionTokenName(workspace),
})
_, err = tx.InsertAPIKey(ctx, newkey)
if err != nil {
return xerrors.Errorf("insert API key: %w", err)
}
Expand All @@ -1493,7 +1459,7 @@ func (server *Server) regenerateSessionToken(ctx context.Context, user database.
if err != nil {
return "", xerrors.Errorf("regenerate API key: %w", err)
}
return fmt.Sprintf("%s-%s", id, secret), nil
return secret, nil
}

// obtainOIDCAccessToken returns a valid OpenID Connect access token
Expand Down
Loading