mirror of
https://github.com/coder/coder.git
synced 2025-07-06 15:41:45 +00:00
feat: Implement list roles & enforce authorize examples (#1273)
This commit is contained in:
122
coderd/httpmw/authorize.go
Normal file
122
coderd/httpmw/authorize.go
Normal file
@ -0,0 +1,122 @@
|
||||
package httpmw
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"github.com/coder/coder/coderd/database"
|
||||
"github.com/coder/coder/coderd/httpapi"
|
||||
"github.com/coder/coder/coderd/rbac"
|
||||
)
|
||||
|
||||
// Authorize will enforce if the user roles can complete the action on the AuthObject.
|
||||
// The organization and owner are found using the ExtractOrganization and
|
||||
// ExtractUser middleware if present.
|
||||
func Authorize(logger slog.Logger, auth *rbac.RegoAuthorizer, action rbac.Action) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
roles := UserRoles(r)
|
||||
object := rbacObject(r)
|
||||
|
||||
if object.Type == "" {
|
||||
panic("developer error: auth object has no type")
|
||||
}
|
||||
|
||||
// First extract the object's owner and organization if present.
|
||||
unknownOrg := r.Context().Value(organizationParamContextKey{})
|
||||
if organization, castOK := unknownOrg.(database.Organization); unknownOrg != nil {
|
||||
if !castOK {
|
||||
panic("developer error: organization param middleware not provided for authorize")
|
||||
}
|
||||
object = object.InOrg(organization.ID)
|
||||
}
|
||||
|
||||
unknownOwner := r.Context().Value(userParamContextKey{})
|
||||
if owner, castOK := unknownOwner.(database.User); unknownOwner != nil {
|
||||
if !castOK {
|
||||
panic("developer error: user param middleware not provided for authorize")
|
||||
}
|
||||
object = object.WithOwner(owner.ID.String())
|
||||
}
|
||||
|
||||
err := auth.AuthorizeByRoleName(r.Context(), roles.ID.String(), roles.Roles, action, object)
|
||||
if err != nil {
|
||||
internalError := new(rbac.UnauthorizedError)
|
||||
if xerrors.As(err, internalError) {
|
||||
logger = logger.With(slog.F("internal", internalError.Internal()))
|
||||
}
|
||||
// Log information for debugging. This will be very helpful
|
||||
// in the early days if we over secure endpoints.
|
||||
logger.Warn(r.Context(), "unauthorized",
|
||||
slog.F("roles", roles.Roles),
|
||||
slog.F("user_id", roles.ID),
|
||||
slog.F("username", roles.Username),
|
||||
slog.F("route", r.URL.Path),
|
||||
slog.F("action", action),
|
||||
slog.F("object", object),
|
||||
)
|
||||
httpapi.Write(rw, http.StatusUnauthorized, httpapi.Response{
|
||||
Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(rw, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type authObjectKey struct{}
|
||||
|
||||
// APIKey returns the API key from the ExtractAPIKey handler.
|
||||
func rbacObject(r *http.Request) rbac.Object {
|
||||
obj, ok := r.Context().Value(authObjectKey{}).(rbac.Object)
|
||||
if !ok {
|
||||
panic("developer error: auth object middleware not provided")
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// WithRBACObject sets the object for 'Authorize()' for all routes handled
|
||||
// by this middleware. The important field to set is 'Type'
|
||||
func WithRBACObject(object rbac.Object) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx := context.WithValue(r.Context(), authObjectKey{}, object)
|
||||
next.ServeHTTP(rw, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// User roles are the 'subject' field of Authorize()
|
||||
type userRolesKey struct{}
|
||||
|
||||
// UserRoles returns the API key from the ExtractUserRoles handler.
|
||||
func UserRoles(r *http.Request) database.GetAllUserRolesRow {
|
||||
apiKey, ok := r.Context().Value(userRolesKey{}).(database.GetAllUserRolesRow)
|
||||
if !ok {
|
||||
panic("developer error: user roles middleware not provided")
|
||||
}
|
||||
return apiKey
|
||||
}
|
||||
|
||||
// ExtractUserRoles requires authentication using a valid API key.
|
||||
func ExtractUserRoles(db database.Store) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
apiKey := APIKey(r)
|
||||
role, err := db.GetAllUserRoles(r.Context(), apiKey.UserID)
|
||||
if err != nil {
|
||||
httpapi.Write(rw, http.StatusUnauthorized, httpapi.Response{
|
||||
Message: "roles not found",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userRolesKey{}, role)
|
||||
next.ServeHTTP(rw, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
131
coderd/httpmw/authorize_test.go
Normal file
131
coderd/httpmw/authorize_test.go
Normal file
@ -0,0 +1,131 @@
|
||||
package httpmw_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/coder/coderd/rbac"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/coder/coder/coderd/database"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/coderd/database/databasefake"
|
||||
"github.com/coder/coder/coderd/httpmw"
|
||||
)
|
||||
|
||||
func TestExtractUserRoles(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := []struct {
|
||||
Name string
|
||||
AddUser func(db database.Store) (database.User, []string, string)
|
||||
}{
|
||||
{
|
||||
Name: "Member",
|
||||
AddUser: func(db database.Store) (database.User, []string, string) {
|
||||
roles := []string{rbac.RoleMember()}
|
||||
user, token := addUser(t, db, roles...)
|
||||
return user, roles, token
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "Admin",
|
||||
AddUser: func(db database.Store) (database.User, []string, string) {
|
||||
roles := []string{rbac.RoleMember(), rbac.RoleAdmin()}
|
||||
user, token := addUser(t, db, roles...)
|
||||
return user, roles, token
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "OrgMember",
|
||||
AddUser: func(db database.Store) (database.User, []string, string) {
|
||||
roles := []string{rbac.RoleMember()}
|
||||
user, token := addUser(t, db, roles...)
|
||||
org, err := db.InsertOrganization(context.Background(), database.InsertOrganizationParams{
|
||||
ID: uuid.New(),
|
||||
Name: "testorg",
|
||||
Description: "test",
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
orgRoles := []string{rbac.RoleOrgMember(org.ID)}
|
||||
_, err = db.InsertOrganizationMember(context.Background(), database.InsertOrganizationMemberParams{
|
||||
OrganizationID: org.ID,
|
||||
UserID: user.ID,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
Roles: orgRoles,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return user, append(roles, orgRoles...), token
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range testCases {
|
||||
c := c
|
||||
t.Run(c.Name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var (
|
||||
db = databasefake.New()
|
||||
user, expRoles, token = c.AddUser(db)
|
||||
rw = httptest.NewRecorder()
|
||||
rtr = chi.NewRouter()
|
||||
)
|
||||
rtr.Use(
|
||||
httpmw.ExtractAPIKey(db, &httpmw.OAuth2Configs{}),
|
||||
httpmw.ExtractUserRoles(db),
|
||||
)
|
||||
rtr.Get("/", func(_ http.ResponseWriter, r *http.Request) {
|
||||
roles := httpmw.UserRoles(r)
|
||||
require.ElementsMatch(t, user.ID, roles.ID)
|
||||
require.ElementsMatch(t, expRoles, roles.Roles)
|
||||
})
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.AddCookie(&http.Cookie{
|
||||
Name: httpmw.AuthCookie,
|
||||
Value: token,
|
||||
})
|
||||
|
||||
rtr.ServeHTTP(rw, req)
|
||||
require.Equal(t, http.StatusOK, rw.Result().StatusCode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func addUser(t *testing.T, db database.Store, roles ...string) (database.User, string) {
|
||||
var (
|
||||
id, secret = randomAPIKeyParts()
|
||||
hashed = sha256.Sum256([]byte(secret))
|
||||
)
|
||||
|
||||
user, err := db.InsertUser(context.Background(), database.InsertUserParams{
|
||||
ID: uuid.New(),
|
||||
Email: "admin@email.com",
|
||||
Username: "admin",
|
||||
RBACRoles: roles,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = db.InsertAPIKey(context.Background(), database.InsertAPIKeyParams{
|
||||
ID: id,
|
||||
UserID: user.ID,
|
||||
HashedSecret: hashed[:],
|
||||
LastUsed: database.Now(),
|
||||
ExpiresAt: database.Now().Add(time.Minute),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
return user, fmt.Sprintf("%s-%s", id, secret)
|
||||
}
|
Reference in New Issue
Block a user