feat(webui): add a member by provider subject or email
POST /api/orgs/{id}/members binds a person by subject, or by email as a
placeholder. The first sign-in whose provider vouches for that email
claims it: the State Store moves the binding onto the provider's subject
in one statement, so a second account with the same address finds
nothing to claim and later sign-ins rest on the subject alone.
This commit is contained in:
1 parent
9e1a40ce99
commit
37cbf2ef47
17 files changed
+2085
-1505
No files matched your search
@@ -3,6 +3,7 @@ package archieui
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
||||
@@ -62,6 +63,10 @@ func compose(ctx context.Context, d deps) *webui.Server {
|
||||
Health: d.Health,
|
||||
ControlPlane: d.ControlPlane,
|
||||
Identities: d.Identities,
|
||||
Issuer: strings.TrimSpace(d.Options.OidcIssuer),
|
||||
}
|
||||
if subjects, ok := d.Identities.(identity.SubjectBinding); ok {
|
||||
srv.Subjects = subjects
|
||||
}
|
||||
if snapshots, ok := d.Store.(storecontract.ConfigSnapshotStore); ok {
|
||||
srv.ConfigSource = webui.RemoteConfigView(snapshots)
|
||||
|
||||
+1619
-1503
File diff suppressed because it is too large.
Load diff
@@ -42,6 +42,7 @@ const (
|
||||
StateStoreService_RetireIdentity_FullMethodName = "/state.v1.StateStoreService/RetireIdentity"
|
||||
StateStoreService_ResolveIdentitySubject_FullMethodName = "/state.v1.StateStoreService/ResolveIdentitySubject"
|
||||
StateStoreService_BindIdentitySubject_FullMethodName = "/state.v1.StateStoreService/BindIdentitySubject"
|
||||
StateStoreService_ClaimIdentitySubject_FullMethodName = "/state.v1.StateStoreService/ClaimIdentitySubject"
|
||||
StateStoreService_AddPersonalToken_FullMethodName = "/state.v1.StateStoreService/AddPersonalToken"
|
||||
StateStoreService_ListPersonalTokens_FullMethodName = "/state.v1.StateStoreService/ListPersonalTokens"
|
||||
StateStoreService_RevokePersonalToken_FullMethodName = "/state.v1.StateStoreService/RevokePersonalToken"
|
||||
@@ -201,6 +202,7 @@ type StateStoreServiceClient interface {
|
||||
// identity store.
|
||||
ResolveIdentitySubject(ctx context.Context, in *ResolveIdentitySubjectRequest, opts ...grpc.CallOption) (*ResolveIdentitySubjectResponse, error)
|
||||
BindIdentitySubject(ctx context.Context, in *BindIdentitySubjectRequest, opts ...grpc.CallOption) (*BindIdentitySubjectResponse, error)
|
||||
ClaimIdentitySubject(ctx context.Context, in *ClaimIdentitySubjectRequest, opts ...grpc.CallOption) (*ClaimIdentitySubjectResponse, error)
|
||||
// Personal API tokens act on the caller's own principal: the State Store
|
||||
// refuses a call that carries none.
|
||||
AddPersonalToken(ctx context.Context, in *AddPersonalTokenRequest, opts ...grpc.CallOption) (*AddPersonalTokenResponse, error)
|
||||
@@ -641,6 +643,16 @@ func (c *stateStoreServiceClient) BindIdentitySubject(ctx context.Context, in *B
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ClaimIdentitySubject(ctx context.Context, in *ClaimIdentitySubjectRequest, opts ...grpc.CallOption) (*ClaimIdentitySubjectResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ClaimIdentitySubjectResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ClaimIdentitySubject_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) AddPersonalToken(ctx context.Context, in *AddPersonalTokenRequest, opts ...grpc.CallOption) (*AddPersonalTokenResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(AddPersonalTokenResponse)
|
||||
@@ -1788,6 +1800,7 @@ type StateStoreServiceServer interface {
|
||||
// identity store.
|
||||
ResolveIdentitySubject(context.Context, *ResolveIdentitySubjectRequest) (*ResolveIdentitySubjectResponse, error)
|
||||
BindIdentitySubject(context.Context, *BindIdentitySubjectRequest) (*BindIdentitySubjectResponse, error)
|
||||
ClaimIdentitySubject(context.Context, *ClaimIdentitySubjectRequest) (*ClaimIdentitySubjectResponse, error)
|
||||
// Personal API tokens act on the caller's own principal: the State Store
|
||||
// refuses a call that carries none.
|
||||
AddPersonalToken(context.Context, *AddPersonalTokenRequest) (*AddPersonalTokenResponse, error)
|
||||
@@ -2067,6 +2080,9 @@ func (UnimplementedStateStoreServiceServer) ResolveIdentitySubject(context.Conte
|
||||
func (UnimplementedStateStoreServiceServer) BindIdentitySubject(context.Context, *BindIdentitySubjectRequest) (*BindIdentitySubjectResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method BindIdentitySubject not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ClaimIdentitySubject(context.Context, *ClaimIdentitySubjectRequest) (*ClaimIdentitySubjectResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ClaimIdentitySubject not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) AddPersonalToken(context.Context, *AddPersonalTokenRequest) (*AddPersonalTokenResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method AddPersonalToken not implemented")
|
||||
}
|
||||
@@ -2823,6 +2839,24 @@ func _StateStoreService_BindIdentitySubject_Handler(srv interface{}, ctx context
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ClaimIdentitySubject_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ClaimIdentitySubjectRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ClaimIdentitySubject(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ClaimIdentitySubject_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ClaimIdentitySubject(ctx, req.(*ClaimIdentitySubjectRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_AddPersonalToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(AddPersonalTokenRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -4827,6 +4861,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "BindIdentitySubject",
|
||||
Handler: _StateStoreService_BindIdentitySubject_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ClaimIdentitySubject",
|
||||
Handler: _StateStoreService_ClaimIdentitySubject_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "AddPersonalToken",
|
||||
Handler: _StateStoreService_AddPersonalToken_Handler,
|
||||
|
||||
@@ -17,6 +17,12 @@ type Subject struct {
|
||||
Subject string `json:"subject"`
|
||||
}
|
||||
|
||||
// EmailSubject is the placeholder binding of a person added by email: the
|
||||
// issuer's verified address stands in until their first sign-in claims it.
|
||||
func EmailSubject(issuer, email string) Subject {
|
||||
return Subject{Issuer: issuer, Subject: "email:" + strings.ToLower(strings.TrimSpace(email))}
|
||||
}
|
||||
|
||||
func (s Subject) Validate() error {
|
||||
if strings.TrimSpace(s.Issuer) == "" || strings.TrimSpace(s.Subject) == "" {
|
||||
return fmt.Errorf("%w: issuer and subject are required", ErrInvalid)
|
||||
@@ -28,6 +34,9 @@ func (s Subject) Validate() error {
|
||||
// verification, never an assertion from the caller.
|
||||
type Credential struct {
|
||||
Subject Subject
|
||||
// Email is the address the provider vouched for (email_verified), empty
|
||||
// otherwise. It resolves a person added by email before any subject is known.
|
||||
Email string
|
||||
Scopes []string
|
||||
Expires time.Time
|
||||
}
|
||||
@@ -69,6 +78,9 @@ type SubjectResolver interface {
|
||||
// configured with resolves to an identity, and a subject a provider asserts
|
||||
// resolves to the same identity.
|
||||
ResolveSubject(context.Context, Subject) (Identity, error)
|
||||
// ClaimSubject moves a placeholder binding onto subject and returns its
|
||||
// identity; a placeholder that is gone (already claimed) is ErrNotFound.
|
||||
ClaimSubject(ctx context.Context, placeholder, subject Subject) (Identity, error)
|
||||
}
|
||||
|
||||
// ProviderSession is what a completed authorization flow yields: the credential
|
||||
@@ -126,6 +138,11 @@ func Resolve(ctx context.Context, subjects SubjectResolver, credential Credentia
|
||||
return Identity{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err)
|
||||
}
|
||||
value, err := subjects.ResolveSubject(ctx, credential.Subject)
|
||||
if errors.Is(err, ErrNotFound) && credential.Email != "" {
|
||||
// The first sign-in binds the provider's subject in place of the
|
||||
// address, so later sign-ins rest on the subject alone.
|
||||
value, err = subjects.ClaimSubject(ctx, EmailSubject(credential.Subject.Issuer, credential.Email), credential.Subject)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return Identity{}, fmt.Errorf("%w: %s", ErrSubjectUnbound, credential.Subject.Subject)
|
||||
|
||||
@@ -103,14 +103,21 @@ func (v *Verifier) Verify(ctx context.Context, rawToken string) (identity.Creden
|
||||
ClientID string `json:"client_id"`
|
||||
Scope string `json:"scope"`
|
||||
Scopes []string `json:"scp"`
|
||||
Email string `json:"email"`
|
||||
Verified bool `json:"email_verified"`
|
||||
}
|
||||
_ = token.Claims(&claims)
|
||||
subject, err := subjectFor(token.Issuer, claims.Subject, claims.ClientID)
|
||||
if err != nil {
|
||||
return identity.Credential{}, err
|
||||
}
|
||||
email := ""
|
||||
if claims.Verified {
|
||||
email = strings.TrimSpace(claims.Email)
|
||||
}
|
||||
return identity.Credential{
|
||||
Subject: subject,
|
||||
Email: email,
|
||||
Scopes: scopesFor(claims.Scope, claims.Scopes),
|
||||
Expires: token.Expiry,
|
||||
}, nil
|
||||
|
||||
@@ -187,6 +187,38 @@ func (s *Store) ResolveSubject(ctx context.Context, subject identity.Subject) (i
|
||||
return identityFromRow(i), nil
|
||||
}
|
||||
|
||||
// ClaimSubject moves a placeholder binding (a person added by email) onto
|
||||
// the subject the provider asserts. The placeholder is gone afterwards, so a
|
||||
// second account showing the same address finds nothing to claim.
|
||||
func (s *Store) ClaimSubject(ctx context.Context, placeholder, subject identity.Subject) (identity.Identity, error) {
|
||||
if err := subject.Validate(); err != nil {
|
||||
return identity.Identity{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
var claimed identity.Identity
|
||||
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
q := postgresdb.New(tx)
|
||||
id, err := q.ClaimIdentitySubject(ctx, postgresdb.ClaimIdentitySubjectParams{
|
||||
Issuer: placeholder.Issuer, Placeholder: placeholder.Subject, Subject: subject.Subject, BoundAt: now,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return identity.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
row, err := q.GetIdentity(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
claimed = identityFromRow(row)
|
||||
return insertIdentityEvent(ctx, q, claimed.ID, identity.Event{
|
||||
IdentityID: claimed.ID, Type: "claim_subject", From: claimed.Lifecycle, To: claimed.Lifecycle, DisplayName: subject.Subject,
|
||||
}, identity.Audit{ActorID: claimed.ID, Source: "sign-in", RequestID: placeholder.Subject}, now)
|
||||
})
|
||||
return claimed, err
|
||||
}
|
||||
|
||||
// BindSubject binds an identity to the provider subject that asserts it,
|
||||
// moving any prior binding for that subject.
|
||||
func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, audit identity.Audit) error {
|
||||
|
||||
@@ -10,6 +10,33 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const claimIdentitySubject = `-- name: ClaimIdentitySubject :one
|
||||
UPDATE identity_subjects SET subject = $1, bound_at = $2
|
||||
WHERE issuer = $3 AND subject = $4
|
||||
RETURNING identity_id
|
||||
`
|
||||
|
||||
type ClaimIdentitySubjectParams struct {
|
||||
Subject string
|
||||
BoundAt time.Time
|
||||
Issuer string
|
||||
Placeholder string
|
||||
}
|
||||
|
||||
// Moves a placeholder binding onto the subject the provider asserts, in one
|
||||
// statement, so only the first claimant gets it.
|
||||
func (q *Queries) ClaimIdentitySubject(ctx context.Context, arg ClaimIdentitySubjectParams) (string, error) {
|
||||
row := q.db.QueryRow(ctx, claimIdentitySubject,
|
||||
arg.Subject,
|
||||
arg.BoundAt,
|
||||
arg.Issuer,
|
||||
arg.Placeholder,
|
||||
)
|
||||
var identity_id string
|
||||
err := row.Scan(&identity_id)
|
||||
return identity_id, err
|
||||
}
|
||||
|
||||
const deleteIdentitySubject = `-- name: DeleteIdentitySubject :execrows
|
||||
DELETE FROM identity_subjects WHERE identity_id = $1 AND issuer = $2 AND subject = $3
|
||||
`
|
||||
|
||||
@@ -39,6 +39,13 @@ SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.upd
|
||||
FROM identities i JOIN identity_subjects b ON b.identity_id = i.id
|
||||
WHERE b.issuer = $1 AND b.subject = $2;
|
||||
|
||||
-- name: ClaimIdentitySubject :one
|
||||
-- Moves a placeholder binding onto the subject the provider asserts, in one
|
||||
-- statement, so only the first claimant gets it.
|
||||
UPDATE identity_subjects SET subject = @subject, bound_at = @bound_at
|
||||
WHERE issuer = @issuer AND subject = @placeholder
|
||||
RETURNING identity_id;
|
||||
|
||||
-- name: UpsertIdentitySubject :exec
|
||||
INSERT INTO identity_subjects (issuer, subject, identity_id, bound_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
|
||||
@@ -80,6 +80,19 @@ func (s *server) ResolveIdentitySubject(ctx context.Context, request *pb.Resolve
|
||||
return &pb.ResolveIdentitySubjectResponse{Identity: identityProto(value)}, nil
|
||||
}
|
||||
|
||||
func (s *server) ClaimIdentitySubject(ctx context.Context, request *pb.ClaimIdentitySubjectRequest) (*pb.ClaimIdentitySubjectResponse, error) {
|
||||
if s.deps.SubjectBindings == nil {
|
||||
return nil, status.Error(codes.Unavailable, "identity subject bindings unavailable")
|
||||
}
|
||||
value, err := s.deps.SubjectBindings.ClaimSubject(ctx,
|
||||
identity.Subject{Issuer: request.Issuer, Subject: request.Placeholder},
|
||||
identity.Subject{Issuer: request.Issuer, Subject: request.Subject})
|
||||
if err != nil {
|
||||
return nil, identityStatus(err)
|
||||
}
|
||||
return &pb.ClaimIdentitySubjectResponse{Identity: identityProto(value)}, nil
|
||||
}
|
||||
|
||||
func (s *server) BindIdentitySubject(ctx context.Context, request *pb.BindIdentitySubjectRequest) (*pb.BindIdentitySubjectResponse, error) {
|
||||
if s.deps.SubjectBindings == nil {
|
||||
return nil, status.Error(codes.Unavailable, "identity subject bindings unavailable")
|
||||
@@ -103,6 +116,14 @@ func (c *Client) ResolveSubject(ctx context.Context, subject identity.Subject) (
|
||||
return identityValue(response.Identity), nil
|
||||
}
|
||||
|
||||
func (c *Client) ClaimSubject(ctx context.Context, placeholder, subject identity.Subject) (identity.Identity, error) {
|
||||
response, err := c.client.ClaimIdentitySubject(ctx, &pb.ClaimIdentitySubjectRequest{Issuer: subject.Issuer, Placeholder: placeholder.Subject, Subject: subject.Subject})
|
||||
if err != nil {
|
||||
return identity.Identity{}, identityClientError(err)
|
||||
}
|
||||
return identityValue(response.Identity), nil
|
||||
}
|
||||
|
||||
func (c *Client) BindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, audit identity.Audit) error {
|
||||
_, err := c.client.BindIdentitySubject(ctx, &pb.BindIdentitySubjectRequest{Id: string(id), Issuer: subject.Issuer, Subject: subject.Subject, Audit: auditProto(audit)})
|
||||
return identityClientError(err)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
@@ -206,6 +208,112 @@ func (s *Server) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"membership": membership})
|
||||
}
|
||||
|
||||
// handleOrgMemberAdd adds a person by the subject their provider asserts or by
|
||||
// their email, creating the identity and binding it so that person's next
|
||||
// sign-in resolves to it with this role. An already-bound subject keeps its
|
||||
// identity and only gains the membership.
|
||||
func (s *Server) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if s.Subjects == nil || s.Identities == nil || s.Issuer == "" {
|
||||
http.Error(w, "adding a person needs a configured identity provider", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
request, bound, name, ok := s.decodeMemberAdd(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
existing, err := s.Subjects.ResolveSubject(r.Context(), bound)
|
||||
if err != nil && !errors.Is(err, identity.ErrNotFound) {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
}
|
||||
unbound := err != nil
|
||||
membership := org.Membership{
|
||||
IdentityID: existing.ID, OrgID: id,
|
||||
WorkspaceID: org.WorkspaceID(request.Workspace), Role: org.Role(request.Role),
|
||||
}
|
||||
if unbound {
|
||||
if membership.IdentityID, err = randomIdentityID(); err != nil {
|
||||
http.Error(w, "cannot create identity ID", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
if !s.mayChangeMembership(w, r, membership, membership.Role) {
|
||||
return
|
||||
}
|
||||
if unbound && !s.createBoundIdentity(w, r, membership.IdentityID, name, bound) {
|
||||
return
|
||||
}
|
||||
if err := s.Orgs.EnsureMembership(r.Context(), membership); err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, map[string]any{"membership": membership})
|
||||
}
|
||||
|
||||
type memberAddRequest struct {
|
||||
Subject string `json:"subject"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Role string `json:"role"`
|
||||
Workspace string `json:"workspace"`
|
||||
}
|
||||
|
||||
// decodeMemberAdd reads and validates an add-member body, returning the
|
||||
// provider subject it names and the display name to give a new identity. It
|
||||
// has written the error when ok is false.
|
||||
func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (request memberAddRequest, bound identity.Subject, name string, ok bool) {
|
||||
request, ok = decodeBody[memberAddRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
name = strings.TrimSpace(request.DisplayName)
|
||||
subject, email := strings.TrimSpace(request.Subject), strings.TrimSpace(request.Email)
|
||||
switch {
|
||||
case (subject == "") == (email == ""):
|
||||
http.Error(w, "give either a subject or an email", http.StatusBadRequest)
|
||||
return request, bound, name, false
|
||||
case subject != "":
|
||||
bound, name = identity.Subject{Issuer: s.Issuer, Subject: subject}, cmp.Or(name, subject)
|
||||
default:
|
||||
bound, name = identity.EmailSubject(s.Issuer, email), cmp.Or(name, email)
|
||||
}
|
||||
if err := org.Role(request.Role).Validate(); err != nil {
|
||||
writeOrgError(w, err)
|
||||
return request, bound, name, false
|
||||
}
|
||||
return request, bound, name, true
|
||||
}
|
||||
|
||||
// createBoundIdentity makes a user identity and binds subject to it, having
|
||||
// written the error and returned false when either step fails.
|
||||
func (s *Server) createBoundIdentity(w http.ResponseWriter, r *http.Request, id identity.IdentityID, name string, subject identity.Subject) bool {
|
||||
audit, err := webAudit(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
|
||||
return false
|
||||
}
|
||||
value, err := identity.New(id, identity.KindUser, name)
|
||||
if err == nil {
|
||||
_, err = s.Identities.Create(r.Context(), value, audit)
|
||||
}
|
||||
if err == nil {
|
||||
err = s.Subjects.BindSubject(r.Context(), id, subject, audit)
|
||||
}
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) handleOrgMemberRemove(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
return
|
||||
|
||||
@@ -2,6 +2,7 @@ package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -111,6 +112,7 @@ func orgRoutes(s *Server) http.Handler {
|
||||
mux.HandleFunc("GET /api/orgs/{id}/workspaces", s.handleOrgWorkspacesList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/workspaces", s.handleOrgWorkspaceCreate)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/members", s.handleOrgMemberAdd)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet)
|
||||
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", s.handleOrgAgentAssign)
|
||||
@@ -281,3 +283,144 @@ func TestInstanceAdminOrgs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// fakeSubjects is an in-memory identity store with subject bindings.
|
||||
type fakeSubjects struct {
|
||||
identity.Repository
|
||||
byID map[identity.IdentityID]identity.Identity
|
||||
bindings map[identity.Subject]identity.IdentityID
|
||||
}
|
||||
|
||||
func (f *fakeSubjects) Create(_ context.Context, v identity.Identity, _ identity.Audit) (identity.Identity, error) {
|
||||
f.byID[v.ID] = v
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (f *fakeSubjects) ResolveSubject(_ context.Context, s identity.Subject) (identity.Identity, error) {
|
||||
if id, ok := f.bindings[s]; ok {
|
||||
return f.byID[id], nil
|
||||
}
|
||||
return identity.Identity{}, identity.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeSubjects) ClaimSubject(_ context.Context, placeholder, s identity.Subject) (identity.Identity, error) {
|
||||
id, ok := f.bindings[placeholder]
|
||||
if !ok {
|
||||
return identity.Identity{}, identity.ErrNotFound
|
||||
}
|
||||
delete(f.bindings, placeholder)
|
||||
f.bindings[s] = id
|
||||
return f.byID[id], nil
|
||||
}
|
||||
|
||||
func (f *fakeSubjects) BindSubject(_ context.Context, id identity.IdentityID, s identity.Subject, _ identity.Audit) error {
|
||||
f.bindings[s] = id
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestOrgMemberAdd holds adding a person by provider subject or email: it
|
||||
// needs the admin grant, owner needs an owner, one identifier is required, and
|
||||
// the person who was added signs in as the identity the membership names, by
|
||||
// subject or by the provider's verified email.
|
||||
func TestOrgMemberAdd(t *testing.T) {
|
||||
const issuer = "https://idp.example"
|
||||
engine := infraaccess.New(access.ShippedOrgPolicies(org.DefaultOrgID))
|
||||
members := "/api/orgs/" + string(org.DefaultOrgID) + "/members"
|
||||
tests := []struct {
|
||||
name string
|
||||
caller string
|
||||
body string
|
||||
wantStatus int
|
||||
signIn identity.Credential
|
||||
wantRole org.Role
|
||||
// later is a second account showing the same verified email after
|
||||
// the first sign-in claimed it; it must not sign in.
|
||||
later identity.Credential
|
||||
}{
|
||||
{
|
||||
"an admin adds by subject", "admin", `{"subject":"sub-1","role":"developer"}`, http.StatusCreated,
|
||||
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "sub-1"}},
|
||||
org.RoleDeveloper,
|
||||
identity.Credential{},
|
||||
},
|
||||
{
|
||||
"an admin adds by email and the verified email signs in", "admin", `{"email":"Ann@Example.com","role":"viewer"}`, http.StatusCreated,
|
||||
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "unseen"}, Email: "ann@example.com"},
|
||||
org.RoleViewer,
|
||||
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "impostor"}, Email: "ann@example.com"},
|
||||
},
|
||||
{
|
||||
"an unverified email does not sign in", "admin", `{"email":"ann@example.com","role":"viewer"}`, http.StatusCreated,
|
||||
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "unseen"}},
|
||||
"",
|
||||
identity.Credential{},
|
||||
},
|
||||
{"an admin cannot add an owner", "admin", `{"subject":"sub-1","role":"owner"}`, http.StatusForbidden, identity.Credential{}, "", identity.Credential{}},
|
||||
{
|
||||
"an owner adds an owner", "owner", `{"subject":"sub-1","role":"owner"}`, http.StatusCreated,
|
||||
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "sub-1"}},
|
||||
org.RoleOwner,
|
||||
identity.Credential{},
|
||||
},
|
||||
{"a developer cannot add", "developer", `{"subject":"sub-1","role":"viewer"}`, http.StatusForbidden, identity.Credential{}, "", identity.Credential{}},
|
||||
{"both identifiers are refused", "admin", `{"subject":"a","email":"a@b.c","role":"viewer"}`, http.StatusBadRequest, identity.Credential{}, "", identity.Credential{}},
|
||||
{"neither identifier is refused", "admin", `{"role":"viewer"}`, http.StatusBadRequest, identity.Credential{}, "", identity.Credential{}},
|
||||
{"an unknown role is refused", "admin", `{"subject":"sub-1","role":"superuser"}`, http.StatusBadRequest, identity.Credential{}, "", identity.Credential{}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
orgs := newFakeOrgs()
|
||||
store := &fakeSubjects{byID: map[identity.IdentityID]identity.Identity{}, bindings: map[identity.Subject]identity.IdentityID{}}
|
||||
s := &Server{
|
||||
Access: engine, Principals: rolePrincipals{}, Orgs: orgs,
|
||||
Identities: store, Subjects: store, Issuer: issuer,
|
||||
Authenticate: func(_ context.Context, token string) (identity.Identity, error) {
|
||||
return identity.Identity{ID: identity.IdentityID(token), Kind: identity.KindUser}, nil
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, members, strings.NewReader(tt.body))
|
||||
req.Header.Set("Authorization", "Bearer "+tt.caller)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
orgRoutes(s).ServeHTTP(rec, req)
|
||||
if rec.Code != tt.wantStatus {
|
||||
t.Fatalf("status = %d, want %d, body %s", rec.Code, tt.wantStatus, rec.Body.String())
|
||||
}
|
||||
if tt.wantStatus != http.StatusCreated {
|
||||
if len(store.byID) != 0 {
|
||||
t.Fatalf("a refused request created %d identities", len(store.byID))
|
||||
}
|
||||
return
|
||||
}
|
||||
got, err := identity.Resolve(t.Context(), store, tt.signIn)
|
||||
if tt.wantRole == "" {
|
||||
if !errors.Is(err, identity.ErrSubjectUnbound) {
|
||||
t.Fatalf("Resolve = %v, want ErrSubjectUnbound", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
var role org.Role
|
||||
for _, m := range orgs.members[org.DefaultOrgID] {
|
||||
if m.IdentityID == got.ID {
|
||||
role = m.Role
|
||||
}
|
||||
}
|
||||
if role != tt.wantRole {
|
||||
t.Fatalf("signed-in role = %q, want %q", role, tt.wantRole)
|
||||
}
|
||||
if tt.later.Subject.Subject == "" {
|
||||
return
|
||||
}
|
||||
if _, err := identity.Resolve(t.Context(), store, tt.later); !errors.Is(err, identity.ErrSubjectUnbound) {
|
||||
t.Fatalf("second account with the same email: Resolve = %v, want ErrSubjectUnbound", err)
|
||||
}
|
||||
again, err := identity.Resolve(t.Context(), store, identity.Credential{Subject: tt.signIn.Subject})
|
||||
if err != nil || again.ID != got.ID {
|
||||
t.Fatalf("first account by subject alone = %v, %v, want %s", again.ID, err, got.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,12 @@ type Server struct {
|
||||
Principals access.PrincipalSource
|
||||
Denials access.DenialRecorder
|
||||
|
||||
// Subjects binds a provider subject to an identity, and Issuer is the
|
||||
// provider those subjects are asserted under. Nil or empty answers the
|
||||
// add-member route Unavailable.
|
||||
Subjects identity.SubjectBinding
|
||||
Issuer string
|
||||
|
||||
// Orgs serves the org pages: the caller's org, its workspaces, members and
|
||||
// agent assignments. Nil answers the org routes Unavailable.
|
||||
Orgs org.API
|
||||
@@ -333,6 +339,7 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/orgs/{id}/workspaces", s.handleOrgWorkspacesList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/workspaces", s.handleOrgWorkspaceCreate)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/members", s.handleOrgMemberAdd)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet)
|
||||
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", instanceOnly(s.handleOrgAgentAssign))
|
||||
|
||||
Reference in new issue
Block a user