snapshot of https://github.com/cortezaproject/corteza.git (2024.9.x, 2026-09-18; blobs > 131072B omitted)
Some checks failed
SonarQube / SonarQube (push) Failing after 5m28s
E2e test on main branch push / server and client test (map[name:admin port:8080]) (push) Failing after 3m33s
Server and lib tests / Library test (js) (push) Failing after 1m36s
Server and lib tests / Library test (vue) (push) Successful in 2m24s
Server and lib tests / Web client test (admin) (push) Successful in 2m52s
Server and lib tests / Web client test (compose) (push) Successful in 3m23s
Server and lib tests / Web client test (discovery) (push) Successful in 2m49s
Server and lib tests / Web client test (one) (push) Successful in 2m52s
Server and lib tests / Web client test (privacy) (push) Successful in 2m44s
Server and lib tests / Web client test (reporter) (push) Successful in 2m56s
Server and lib tests / Web client test (workflow) (push) Successful in 3m0s
Server and lib tests / Server tests (push) Failing after 4m55s
E2e test on main branch push / notify-failure (push) Failing after 9s
Server and lib tests / Send matrix testing notification (push) Successful in 2s
Mark stale issues and pull requests / stale (push) Successful in 40s
Some checks failed
SonarQube / SonarQube (push) Failing after 5m28s
E2e test on main branch push / server and client test (map[name:admin port:8080]) (push) Failing after 3m33s
Server and lib tests / Library test (js) (push) Failing after 1m36s
Server and lib tests / Library test (vue) (push) Successful in 2m24s
Server and lib tests / Web client test (admin) (push) Successful in 2m52s
Server and lib tests / Web client test (compose) (push) Successful in 3m23s
Server and lib tests / Web client test (discovery) (push) Successful in 2m49s
Server and lib tests / Web client test (one) (push) Successful in 2m52s
Server and lib tests / Web client test (privacy) (push) Successful in 2m44s
Server and lib tests / Web client test (reporter) (push) Successful in 2m56s
Server and lib tests / Web client test (workflow) (push) Successful in 3m0s
Server and lib tests / Server tests (push) Failing after 4m55s
E2e test on main branch push / notify-failure (push) Failing after 9s
Server and lib tests / Send matrix testing notification (push) Successful in 2s
Mark stale issues and pull requests / stale (push) Successful in 40s
This commit is contained in:
6
server/system/scim/README.adoc
Normal file
6
server/system/scim/README.adoc
Normal file
@@ -0,0 +1,6 @@
|
||||
= SCIM Support for Corteza
|
||||
|
||||
Here is a bare minimum support for SCIM.
|
||||
|
||||
NOTE: Experiments with github.com/imulab/go-scim lib failed due to complexity of the implementation
|
||||
and resources needed for bending the lib to our needs.
|
||||
72
server/system/scim/gen_response.go
Normal file
72
server/system/scim/gen_response.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/cortezaproject/corteza/server/system/types"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type (
|
||||
metaResponse struct {
|
||||
ResourceType string `json:"resourceType"`
|
||||
Created time.Time `json:"created"`
|
||||
LastModified *time.Time `json:"lastModified,omitempty"`
|
||||
}
|
||||
|
||||
errorResponse struct {
|
||||
Schemas []string `json:"schemas"`
|
||||
SCIMType string `json:"scimType,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Status int `json:"status,string"`
|
||||
}
|
||||
)
|
||||
|
||||
const (
|
||||
urnError = "urn:ietf:params:scim:api:messages:2.0:Error"
|
||||
)
|
||||
|
||||
func newUserMetaResponse(u *types.User) *metaResponse {
|
||||
rsp := &metaResponse{
|
||||
ResourceType: "User",
|
||||
Created: u.CreatedAt,
|
||||
LastModified: u.UpdatedAt,
|
||||
}
|
||||
|
||||
return rsp
|
||||
}
|
||||
|
||||
func newGroupMetaResponse(u *types.Role) *metaResponse {
|
||||
rsp := &metaResponse{
|
||||
ResourceType: "Group",
|
||||
Created: u.CreatedAt,
|
||||
LastModified: u.UpdatedAt,
|
||||
}
|
||||
|
||||
return rsp
|
||||
}
|
||||
|
||||
func newErrorfResponse(httpStatus int, format string, aa ...interface{}) *errorResponse {
|
||||
return newErrorResponse(httpStatus, fmt.Errorf(format, aa...))
|
||||
}
|
||||
|
||||
func newErrorResponse(httpStatus int, err error) *errorResponse {
|
||||
if httpStatus == 0 {
|
||||
httpStatus = http.StatusInternalServerError
|
||||
}
|
||||
|
||||
er := &errorResponse{
|
||||
Schemas: []string{urnError},
|
||||
Status: httpStatus,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
er.Detail = err.Error()
|
||||
}
|
||||
|
||||
return er
|
||||
}
|
||||
|
||||
func (e *errorResponse) Error() string {
|
||||
return e.Detail
|
||||
}
|
||||
336
server/system/scim/group_handler.go
Normal file
336
server/system/scim/group_handler.go
Normal file
@@ -0,0 +1,336 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"github.com/cortezaproject/corteza/server/pkg/errors"
|
||||
"github.com/cortezaproject/corteza/server/store"
|
||||
"github.com/cortezaproject/corteza/server/system/service"
|
||||
"github.com/cortezaproject/corteza/server/system/types"
|
||||
"github.com/go-chi/chi/v5"
|
||||
labelTypes "github.com/cortezaproject/corteza/server/pkg/label/types"
|
||||
)
|
||||
|
||||
type (
|
||||
groupsHandler struct {
|
||||
externalIdAsPrimary bool
|
||||
externalIdValidator *regexp.Regexp
|
||||
|
||||
svc service.RoleService
|
||||
userSvc service.UserService
|
||||
sec getSecurityContextFn
|
||||
}
|
||||
)
|
||||
|
||||
func (h groupsHandler) get(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
res = h.lookup(h.sec(r), chi.URLParam(r, "id"), w)
|
||||
)
|
||||
|
||||
if res == nil {
|
||||
return
|
||||
}
|
||||
|
||||
send(w, http.StatusOK, newGroupResourceResponse(res))
|
||||
}
|
||||
|
||||
func (h groupsHandler) create(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
|
||||
var (
|
||||
ctx = h.sec(r)
|
||||
svc = h.svc
|
||||
payload = &groupResourceRequest{}
|
||||
err error
|
||||
existing *types.Role
|
||||
)
|
||||
|
||||
if err = payload.decodeJSON(r.Body); err != nil {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
return
|
||||
}
|
||||
|
||||
{
|
||||
// do we need to upsert?
|
||||
if payload.ExternalId != nil {
|
||||
existing, err = h.lookupByExternalId(ctx, *payload.ExternalId)
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
} else if *payload.Name != "" {
|
||||
existing, err = svc.FindByName(ctx, *payload.Name)
|
||||
if err != nil && !errors.Is(err, service.RoleErrNotFound()) {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res, err := h.save(ctx, payload, existing)
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
status := http.StatusOK
|
||||
if res.UpdatedAt == nil {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
|
||||
send(w, status, newGroupResourceResponse(res))
|
||||
}
|
||||
|
||||
func (h groupsHandler) replace(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
|
||||
var (
|
||||
ctx = h.sec(r)
|
||||
existing = h.lookup(ctx, chi.URLParam(r, "id"), w)
|
||||
payload = &groupResourceRequest{}
|
||||
)
|
||||
|
||||
if existing == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := payload.decodeJSON(r.Body); err != nil {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.save(ctx, payload, existing)
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
status := http.StatusOK
|
||||
if res.UpdatedAt == nil {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
|
||||
send(w, status, newGroupResourceResponse(res))
|
||||
}
|
||||
|
||||
// patches group
|
||||
//
|
||||
// only supports adding and removing members
|
||||
func (h groupsHandler) patch(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
|
||||
var (
|
||||
ctx = h.sec(r)
|
||||
svc = h.svc
|
||||
res = h.lookup(ctx, chi.URLParam(r, "id"), w)
|
||||
payload = &operationsRequest{}
|
||||
)
|
||||
|
||||
if res == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := payload.decodeJSON(r.Body); err != nil {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
u *types.User
|
||||
ops = make([]func() error, 0, len(payload.Operations))
|
||||
err error
|
||||
memberships = make(map[string]bool)
|
||||
)
|
||||
|
||||
{
|
||||
// collect all existing memberships into a simple map
|
||||
// to ensure we dont step on our feet (too much)
|
||||
//
|
||||
// this is not 100% bulletproof for concurrent modifications
|
||||
mm, _, err := store.SearchRoleMembers(ctx, service.DefaultStore, types.RoleMemberFilter{RoleID: res.ID})
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, m := range mm {
|
||||
memberships[m.Resource] = true
|
||||
}
|
||||
}
|
||||
|
||||
// validate and collect operations
|
||||
for _, op := range payload.Operations {
|
||||
// iterate through operation's values, load user and schedule op
|
||||
for path, userExternalId := range op.Value {
|
||||
if path != "members" {
|
||||
// allow only "members" path
|
||||
sendError(w, newErrorfResponse(http.StatusBadRequest, "unsupported path: %q", op.Path))
|
||||
return
|
||||
}
|
||||
|
||||
u, err = lookupUserByExternalId(ctx, h.userSvc, h.externalIdValidator, userExternalId)
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if u == nil {
|
||||
sendError(w, newErrorfResponse(http.StatusBadRequest, "no such user: %q", userExternalId))
|
||||
return
|
||||
}
|
||||
|
||||
// making sure u is not overwritten
|
||||
// in the next iteration
|
||||
uID := u.ID
|
||||
memberId := fmt.Sprintf("corteza::system:user/%d", uID)
|
||||
|
||||
switch op.Operation {
|
||||
case patchOpAdd:
|
||||
// support for add operation,
|
||||
// check if there members already exist
|
||||
ops = append(ops, func() error {
|
||||
if memberships[memberId] {
|
||||
// already added
|
||||
return nil
|
||||
}
|
||||
|
||||
memberships[memberId] = true
|
||||
return svc.MemberAdd(ctx, res.ID, uID)
|
||||
})
|
||||
|
||||
case patchOpRemove:
|
||||
// support for remove operation,
|
||||
// check if there members are missing
|
||||
ops = append(ops, func() error {
|
||||
if !memberships[memberId] {
|
||||
// already removed
|
||||
return nil
|
||||
}
|
||||
|
||||
delete(memberships, memberId)
|
||||
return svc.MemberRemove(ctx, res.ID, uID)
|
||||
})
|
||||
|
||||
default:
|
||||
sendError(w, newErrorfResponse(http.StatusBadRequest, "unsupported operation: %q", op.Operation))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// run all scheduled ops
|
||||
for _, op := range ops {
|
||||
if err = op(); err != nil {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
send(w, http.StatusNoContent, nil)
|
||||
}
|
||||
|
||||
func (h groupsHandler) save(ctx context.Context, req *groupResourceRequest, existing *types.Role) (res *types.Role, err error) {
|
||||
var (
|
||||
svc = h.svc
|
||||
)
|
||||
|
||||
if existing == nil {
|
||||
// in case when we did not find a valid group,
|
||||
// start from blank
|
||||
existing = &types.Role{}
|
||||
}
|
||||
|
||||
res = existing
|
||||
req.applyTo(res)
|
||||
|
||||
if res.ID > 0 {
|
||||
res, err = svc.Update(ctx, res)
|
||||
} else {
|
||||
res, err = svc.Create(ctx, res)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, newErrorResponse(http.StatusInternalServerError, err)
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (h groupsHandler) delete(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
ctx = h.sec(r)
|
||||
svc = h.svc
|
||||
res = h.lookup(ctx, chi.URLParam(r, "id"), w)
|
||||
)
|
||||
|
||||
if res == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := svc.Delete(ctx, res.ID); err != nil {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
} else {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// loads role from request path params
|
||||
//
|
||||
// handles errors by writing them to response
|
||||
func (h groupsHandler) lookup(ctx context.Context, id string, w http.ResponseWriter) *types.Role {
|
||||
var (
|
||||
svc = h.svc
|
||||
)
|
||||
|
||||
if h.externalIdAsPrimary {
|
||||
res, err := h.lookupByExternalId(ctx, id)
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
if res == nil {
|
||||
sendError(w, newErrorResponse(http.StatusNotFound, fmt.Errorf("group not found")))
|
||||
}
|
||||
|
||||
return res
|
||||
} else {
|
||||
id, err := strconv.ParseUint(id, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
return nil
|
||||
}
|
||||
|
||||
role, err := svc.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
return nil
|
||||
}
|
||||
|
||||
return role
|
||||
}
|
||||
}
|
||||
|
||||
func (h groupsHandler) lookupByExternalId(ctx context.Context, id string) (r *types.Role, err error) {
|
||||
if h.externalIdValidator != nil && !h.externalIdValidator.MatchString(id) {
|
||||
return nil, newErrorfResponse(http.StatusBadRequest, "invalid external ID")
|
||||
}
|
||||
|
||||
rr, _, err := h.svc.Find(ctx, types.RoleFilter{Labels: map[string]labelTypes.LabelValue{groupLabel_SCIM_externalId: labelTypes.LabelValue{Val: id}}})
|
||||
if err != nil {
|
||||
return nil, newErrorResponse(http.StatusInternalServerError, err)
|
||||
}
|
||||
|
||||
switch len(rr) {
|
||||
case 0:
|
||||
return nil, nil
|
||||
case 1:
|
||||
return rr[0], nil
|
||||
default:
|
||||
return nil, newErrorfResponse(http.StatusPreconditionFailed, "more than one group matches this externalId")
|
||||
}
|
||||
}
|
||||
62
server/system/scim/group_payloads.go
Normal file
62
server/system/scim/group_payloads.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/cortezaproject/corteza/server/system/types"
|
||||
"io"
|
||||
"strconv"
|
||||
labelTypes "github.com/cortezaproject/corteza/server/pkg/label/types"
|
||||
)
|
||||
|
||||
const (
|
||||
urnGroup = "urn:ietf:params:scim:schemas:core:2.0:Group"
|
||||
groupLabel_SCIM_externalId = "SCIM_externalId"
|
||||
)
|
||||
|
||||
type (
|
||||
groupResourceResponse struct {
|
||||
Schemas []string `json:"schemas"`
|
||||
Meta *metaResponse `json:"meta,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
ExternalId string `json:"externalId,omitempty"`
|
||||
Name string `json:"displayName"`
|
||||
}
|
||||
|
||||
groupResourceRequest struct {
|
||||
Schemas []string `json:"schemas"`
|
||||
Meta *metaResponse `json:"meta,omitempty"`
|
||||
ExternalId *string `json:"externalId,omitempty"`
|
||||
Name *string `json:"displayName"`
|
||||
}
|
||||
)
|
||||
|
||||
func newGroupResourceResponse(u *types.Role) *groupResourceResponse {
|
||||
rsp := &groupResourceResponse{
|
||||
Schemas: []string{urnGroup},
|
||||
Meta: newGroupMetaResponse(u),
|
||||
ID: strconv.FormatUint(u.ID, 10),
|
||||
ExternalId: u.Labels[groupLabel_SCIM_externalId].Val,
|
||||
Name: u.Name,
|
||||
}
|
||||
|
||||
return rsp
|
||||
}
|
||||
|
||||
func (req *groupResourceRequest) decodeJSON(r io.Reader) error {
|
||||
if err := json.NewDecoder(r).Decode(req); err != nil {
|
||||
return fmt.Errorf("could not decode group payload: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (req *groupResourceRequest) applyTo(u *types.Role) {
|
||||
if req.Name != nil {
|
||||
u.Name = *req.Name
|
||||
}
|
||||
|
||||
if req.ExternalId != nil {
|
||||
u.SetLabel("SCIM_externalId", labelTypes.LabelValue{Val : *req.ExternalId})
|
||||
}
|
||||
}
|
||||
32
server/system/scim/http.go
Normal file
32
server/system/scim/http.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"go.uber.org/zap"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func send(w http.ResponseWriter, status int, payload interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if status == http.StatusNoContent || payload == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(payload); err != nil {
|
||||
log.Error("could not encode payload", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
func sendError(w http.ResponseWriter, err error) {
|
||||
var (
|
||||
status = http.StatusInternalServerError
|
||||
)
|
||||
|
||||
if er, ok := err.(*errorResponse); ok {
|
||||
status = er.Status
|
||||
}
|
||||
|
||||
send(w, status, err)
|
||||
}
|
||||
38
server/system/scim/patch_payload_test.go
Normal file
38
server/system/scim/patch_payload_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/stretchr/testify/require"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOperationsRequestDecodeJSON(t *testing.T) {
|
||||
const user1Id = `00000000-0000-0000-0000-000000000001`
|
||||
var (
|
||||
req = require.New(t)
|
||||
payload operationsRequest
|
||||
|
||||
s = strings.NewReader(fmt.Sprintf(
|
||||
`{"Operations":[{"op":"add","path":"members[value eq \"%s\"]"}],"schemas":["urn:ietf:params:scim:schemas:core:2.0:PatchOp"]}`,
|
||||
user1Id,
|
||||
))
|
||||
|
||||
expectedPayload = operationsRequest{
|
||||
Schemas: []string{"urn:ietf:params:scim:schemas:core:2.0:PatchOp"},
|
||||
Operations: []operationRequest{
|
||||
{
|
||||
Operation: "add",
|
||||
Path: fmt.Sprintf("members[value eq \"%s\"]", user1Id),
|
||||
Value: map[string]string{
|
||||
"members": user1Id,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
err := payload.decodeJSON(s)
|
||||
req.NoError(err)
|
||||
req.Equal(expectedPayload, payload)
|
||||
}
|
||||
50
server/system/scim/patch_payloads.go
Normal file
50
server/system/scim/patch_payloads.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const (
|
||||
urnPatchOp = "urn:ietf:params:scim:schemas:core:2.0:PatchOp"
|
||||
patchOpAdd = "add"
|
||||
patchOpRemove = "remove"
|
||||
)
|
||||
|
||||
type (
|
||||
// very crud operations support
|
||||
operationsRequest struct {
|
||||
Schemas []string `json:"schemas"`
|
||||
Operations []operationRequest `json:"Operations"`
|
||||
}
|
||||
|
||||
operationRequest struct {
|
||||
Operation string `json:"op"`
|
||||
Path string `json:"path"`
|
||||
Value map[string]string
|
||||
}
|
||||
)
|
||||
|
||||
func (req *operationsRequest) decodeJSON(r io.Reader) error {
|
||||
if err := json.NewDecoder(r).Decode(req); err != nil {
|
||||
return fmt.Errorf("could not decode operations payload: %w", err)
|
||||
}
|
||||
|
||||
// Compiles req.Path and updates req.Value
|
||||
for i, op := range req.Operations {
|
||||
r := regexp.MustCompile(`([a-z]\w+)\[value eq \"([\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})\"\]`)
|
||||
strings := r.FindStringSubmatch(op.Path)
|
||||
if len(strings) == 3 {
|
||||
key := strings[1]
|
||||
if op.Value == nil {
|
||||
op.Value = make(map[string]string)
|
||||
}
|
||||
op.Value[key] = strings[2]
|
||||
req.Operations[i].Value = op.Value
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
76
server/system/scim/routes.go
Normal file
76
server/system/scim/routes.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/cortezaproject/corteza/server/pkg/options"
|
||||
"github.com/cortezaproject/corteza/server/system/service"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type (
|
||||
Config struct {
|
||||
ExternalIdAsPrimary bool
|
||||
ExternalIdValidator *regexp.Regexp
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
log = zap.NewNop()
|
||||
)
|
||||
|
||||
func Guard(opt options.SCIMOpt) func(next http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
// temp authorization mechanism so we do not have to
|
||||
// pre-create users and generate their auth tokens
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authPrefix := "Bearer "
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if (len(authPrefix)+len(opt.Secret)) == len(authHeader) && opt.Secret == authHeader[len(authPrefix):] {
|
||||
// all good, auth header matches the secret
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, "Unauthorized", http.StatusForbidden)
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Routes(r chi.Router, cfg Config) {
|
||||
r.Route("/Users", func(r chi.Router) {
|
||||
uh := &usersHandler{
|
||||
externalIdAsPrimary: cfg.ExternalIdAsPrimary,
|
||||
externalIdValidator: cfg.ExternalIdValidator,
|
||||
|
||||
svc: service.DefaultUser,
|
||||
passSvc: service.DefaultAuth,
|
||||
sec: getSecurityContext,
|
||||
}
|
||||
|
||||
r.Get("/{id}", uh.get)
|
||||
r.Post("/", uh.create)
|
||||
r.Put("/{id}", uh.replace)
|
||||
r.Delete("/{id}", uh.delete)
|
||||
})
|
||||
|
||||
r.Route("/Groups", func(r chi.Router) {
|
||||
gh := &groupsHandler{
|
||||
externalIdAsPrimary: cfg.ExternalIdAsPrimary,
|
||||
externalIdValidator: cfg.ExternalIdValidator,
|
||||
|
||||
svc: service.DefaultRole,
|
||||
userSvc: service.DefaultUser,
|
||||
sec: getSecurityContext,
|
||||
}
|
||||
|
||||
r.Get("/{id}", gh.get)
|
||||
r.Post("/", gh.create)
|
||||
r.Put("/{id}", gh.replace)
|
||||
r.Patch("/{id}", gh.patch)
|
||||
r.Delete("/{id}", gh.delete)
|
||||
})
|
||||
}
|
||||
17
server/system/scim/security.go
Normal file
17
server/system/scim/security.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/cortezaproject/corteza/server/pkg/auth"
|
||||
)
|
||||
|
||||
type (
|
||||
getSecurityContextFn func(r *http.Request) context.Context
|
||||
)
|
||||
|
||||
// Set service user to request's identity
|
||||
func getSecurityContext(r *http.Request) context.Context {
|
||||
return auth.SetIdentityToContext(r.Context(), auth.ServiceUser())
|
||||
}
|
||||
236
server/system/scim/user_handler.go
Normal file
236
server/system/scim/user_handler.go
Normal file
@@ -0,0 +1,236 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"github.com/cortezaproject/corteza/server/pkg/errors"
|
||||
"github.com/cortezaproject/corteza/server/system/service"
|
||||
"github.com/cortezaproject/corteza/server/system/types"
|
||||
"github.com/go-chi/chi/v5"
|
||||
labelTypes "github.com/cortezaproject/corteza/server/pkg/label/types"
|
||||
|
||||
)
|
||||
|
||||
type (
|
||||
passwordSetter interface {
|
||||
SetPassword(context.Context, uint64, string) error
|
||||
}
|
||||
|
||||
usersHandler struct {
|
||||
externalIdAsPrimary bool
|
||||
externalIdValidator *regexp.Regexp
|
||||
|
||||
svc service.UserService
|
||||
passSvc passwordSetter
|
||||
sec getSecurityContextFn
|
||||
}
|
||||
)
|
||||
|
||||
func (h usersHandler) get(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
res = h.lookup(h.sec(r), chi.URLParam(r, "id"), w)
|
||||
)
|
||||
|
||||
if res == nil {
|
||||
return
|
||||
}
|
||||
|
||||
send(w, http.StatusOK, newUserResourceResponse(res))
|
||||
}
|
||||
|
||||
func (h usersHandler) create(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
|
||||
var (
|
||||
ctx = h.sec(r)
|
||||
svc = h.svc
|
||||
payload = &userResourceRequest{}
|
||||
err error
|
||||
existing *types.User
|
||||
code = http.StatusBadRequest
|
||||
)
|
||||
|
||||
if err = payload.decodeJSON(r.Body); err != nil {
|
||||
sendError(w, newErrorResponse(code, err))
|
||||
return
|
||||
}
|
||||
|
||||
{
|
||||
// do we need to upsert?
|
||||
if payload.ExternalId != nil {
|
||||
existing, err = h.lookupByExternalId(ctx, *payload.ExternalId)
|
||||
if err != nil {
|
||||
sendError(w, newErrorResponse(code, err))
|
||||
return
|
||||
}
|
||||
} else if email := payload.Emails.getFirst(); email != "" {
|
||||
existing, err = svc.FindByEmail(ctx, email)
|
||||
if err != nil && !errors.Is(err, service.UserErrNotFound()) {
|
||||
sendError(w, newErrorResponse(http.StatusInternalServerError, err))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res, err := h.save(ctx, payload, existing)
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
status := http.StatusOK
|
||||
if res.UpdatedAt == nil {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
|
||||
send(w, status, newUserResourceResponse(res))
|
||||
}
|
||||
|
||||
func (h usersHandler) replace(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
|
||||
var (
|
||||
ctx = h.sec(r)
|
||||
existing = h.lookup(ctx, chi.URLParam(r, "id"), w)
|
||||
payload = &userResourceRequest{}
|
||||
)
|
||||
|
||||
if existing == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := payload.decodeJSON(r.Body); err != nil {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.save(ctx, payload, existing)
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
status := http.StatusOK
|
||||
if res.UpdatedAt == nil {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
|
||||
send(w, status, newUserResourceResponse(res))
|
||||
}
|
||||
|
||||
func (h usersHandler) save(ctx context.Context, req *userResourceRequest, existing *types.User) (res *types.User, err error) {
|
||||
var (
|
||||
svc = h.svc
|
||||
)
|
||||
|
||||
if existing == nil || !existing.Valid() {
|
||||
// in case when we did not find a valid user,
|
||||
// start from blank
|
||||
existing = &types.User{}
|
||||
}
|
||||
|
||||
res = existing
|
||||
req.applyTo(res)
|
||||
|
||||
if res.ID > 0 {
|
||||
res, err = svc.Update(ctx, res)
|
||||
} else {
|
||||
res, err = svc.Create(ctx, res)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.Password != nil && *req.Password != "" {
|
||||
err = h.passSvc.SetPassword(ctx, res.ID, *req.Password)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (h usersHandler) delete(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
ctx = h.sec(r)
|
||||
svc = h.svc
|
||||
res = h.lookup(ctx, chi.URLParam(r, "id"), w)
|
||||
)
|
||||
|
||||
if res == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := svc.Delete(ctx, res.ID); err != nil {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
} else {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// loads role from request path params
|
||||
//
|
||||
// handles errors by writing them to response
|
||||
func (h usersHandler) lookup(ctx context.Context, id string, w http.ResponseWriter) *types.User {
|
||||
var (
|
||||
svc = h.svc
|
||||
)
|
||||
|
||||
if h.externalIdAsPrimary {
|
||||
res, err := h.lookupByExternalId(ctx, id)
|
||||
if err != nil {
|
||||
sendError(w, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
if res == nil {
|
||||
sendError(w, newErrorResponse(http.StatusNotFound, fmt.Errorf("user not found")))
|
||||
}
|
||||
|
||||
return res
|
||||
} else {
|
||||
groupId, err := strconv.ParseUint(id, 10, 64)
|
||||
if err != nil || groupId == 0 {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
return nil
|
||||
}
|
||||
|
||||
role, err := svc.FindByID(ctx, groupId)
|
||||
if err != nil {
|
||||
sendError(w, newErrorResponse(http.StatusBadRequest, err))
|
||||
return nil
|
||||
}
|
||||
|
||||
return role
|
||||
}
|
||||
}
|
||||
|
||||
func (h usersHandler) lookupByExternalId(ctx context.Context, id string) (r *types.User, err error) {
|
||||
return lookupUserByExternalId(ctx, h.svc, h.externalIdValidator, id)
|
||||
}
|
||||
|
||||
func lookupUserByExternalId(ctx context.Context, svc service.UserService, v *regexp.Regexp, id string) (r *types.User, err error) {
|
||||
if v != nil && !v.MatchString(id) {
|
||||
return nil, newErrorfResponse(http.StatusBadRequest, "invalid external ID")
|
||||
}
|
||||
|
||||
rr, _, err := svc.Find(ctx, types.UserFilter{Labels: map[string]labelTypes.LabelValue{userLabel_SCIM_externalId: labelTypes.LabelValue{Val: id}}})
|
||||
if err != nil {
|
||||
return nil, newErrorResponse(http.StatusInternalServerError, err)
|
||||
}
|
||||
|
||||
switch len(rr) {
|
||||
case 0:
|
||||
return nil, nil
|
||||
case 1:
|
||||
return rr[0], nil
|
||||
default:
|
||||
return nil, newErrorfResponse(http.StatusPreconditionFailed, "more than one user matches this externalId")
|
||||
}
|
||||
}
|
||||
122
server/system/scim/user_payloads.go
Normal file
122
server/system/scim/user_payloads.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/cortezaproject/corteza/server/pkg/handle"
|
||||
"github.com/cortezaproject/corteza/server/system/types"
|
||||
"io"
|
||||
"strconv"
|
||||
labelTypes "github.com/cortezaproject/corteza/server/pkg/label/types"
|
||||
)
|
||||
|
||||
const (
|
||||
urnUser = "urn:ietf:params:scim:schemas:core:2.0:User"
|
||||
userLabel_SCIM_externalId = "SCIM_externalId"
|
||||
)
|
||||
|
||||
type (
|
||||
emailResponse struct {
|
||||
Value string `json:"value"`
|
||||
Primary bool `json:"primary,omitempty"`
|
||||
}
|
||||
|
||||
emailsResponse []*emailResponse
|
||||
|
||||
userNameResponse struct {
|
||||
Formatted string `json:"formatted"`
|
||||
}
|
||||
|
||||
userGroupMembershipRequest struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
userResourceResponse struct {
|
||||
Schemas []string `json:"schemas"`
|
||||
Meta *metaResponse `json:"meta,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
ExternalId string `json:"externalId,omitempty"`
|
||||
UserName string `json:"userName,omitempty"`
|
||||
NickName string `json:"nickName,omitempty"`
|
||||
Name *userNameResponse `json:"displayName"`
|
||||
Emails emailsResponse `json:"emails,omitempty"`
|
||||
}
|
||||
|
||||
userResourceRequest struct {
|
||||
Schemas []string `json:"schemas"`
|
||||
Meta *metaResponse `json:"meta,omitempty"`
|
||||
ExternalId *string `json:"externalId,omitempty"`
|
||||
UserName *string `json:"userName,omitempty"`
|
||||
NickName *string `json:"nickName,omitempty"`
|
||||
Password *string `json:"password,omitempty"`
|
||||
Name *userNameResponse `json:"name"`
|
||||
Emails emailsResponse `json:"emails,omitempty"`
|
||||
|
||||
Groups []*userGroupMembershipRequest `json:"groups,omitempty"`
|
||||
}
|
||||
)
|
||||
|
||||
func newUserResourceResponse(u *types.User) *userResourceResponse {
|
||||
rsp := &userResourceResponse{
|
||||
Schemas: []string{urnUser},
|
||||
Meta: newUserMetaResponse(u),
|
||||
ID: strconv.FormatUint(u.ID, 10),
|
||||
ExternalId: u.Labels[userLabel_SCIM_externalId].Val,
|
||||
UserName: u.Username,
|
||||
NickName: u.Handle,
|
||||
Emails: emailsResponse{{u.Email, true}},
|
||||
}
|
||||
|
||||
if u.Name != "" {
|
||||
rsp.Name = &userNameResponse{Formatted: u.Name}
|
||||
}
|
||||
|
||||
return rsp
|
||||
}
|
||||
|
||||
// returns first (primary) email
|
||||
func (ee emailsResponse) getFirst() string {
|
||||
if len(ee) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var match int
|
||||
for i, e := range ee {
|
||||
if e.Primary {
|
||||
match = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return ee[match].Value
|
||||
}
|
||||
|
||||
func (req *userResourceRequest) decodeJSON(r io.Reader) error {
|
||||
if err := json.NewDecoder(r).Decode(req); err != nil {
|
||||
return fmt.Errorf("could not decode user payload: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (req *userResourceRequest) applyTo(u *types.User) {
|
||||
if v := req.Emails.getFirst(); len(v) > 0 {
|
||||
u.Email = v
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
u.Name = req.Name.Formatted
|
||||
}
|
||||
|
||||
if req.UserName != nil {
|
||||
u.Username = *req.UserName
|
||||
}
|
||||
|
||||
if req.NickName != nil && handle.IsValid(*req.NickName) {
|
||||
u.Handle = *req.NickName
|
||||
}
|
||||
|
||||
if req.ExternalId != nil {
|
||||
u.SetLabel("SCIM_externalId", labelTypes.LabelValue{Val: *req.ExternalId})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user