diff --git a/cmd/memos/config.go b/cmd/memos/config.go index b51881c90..c8c0399c8 100644 --- a/cmd/memos/config.go +++ b/cmd/memos/config.go @@ -169,8 +169,8 @@ func runConfigValidate(dir string, resolver configuration.Resolver, stdout, stde return err } config := desired.Configuration - fmt.Fprintf(stdout, "Configuration in %s is valid: %d identity providers, %d instance settings, %d users.\n", - dir, len(config.IdentityProviders), len(config.InstanceSettings), len(config.Users)) + fmt.Fprintf(stdout, "Configuration in %s is valid: %d identity providers, %d instance settings, %d users, %d linked identities.\n", + dir, len(config.IdentityProviders), len(config.InstanceSettings), len(config.Users), len(config.LinkedIdentities)) return nil } diff --git a/core/configuration/apply.go b/core/configuration/apply.go index 706fc5c09..fba27e3a2 100644 --- a/core/configuration/apply.go +++ b/core/configuration/apply.go @@ -114,11 +114,40 @@ func applyOperation(ctx context.Context, tx *store.ConfigurationTransaction, op }) } return tx.DeleteInstanceSetting(ctx, op.settingKey) + case KindLinkedIdentity: + return applyLinkedIdentity(ctx, tx, op) default: return applyUser(ctx, tx, op, now) } } +// applyLinkedIdentity writes the one field a link has by replacing the row, +// after resolving the user, who may have been created earlier in this apply. +func applyLinkedIdentity(ctx context.Context, tx *store.ConfigurationTransaction, op *operation) error { + var userID int32 + if op.actualUser != nil { + userID = op.actualUser.ID + } else { + users, err := tx.ListUsers(ctx, &store.FindUser{Username: &op.identityUsername}) + if err != nil { + return errors.Wrap(err, "failed to read user") + } + if len(users) == 0 { + return errors.Errorf("user %s does not exist", op.identityUsername) + } + userID = users[0].ID + } + if op.actualIdentity != nil { + if err := tx.DeleteUserIdentities(ctx, &store.DeleteUserIdentity{UserID: &userID, Provider: &op.actualIdentity.Provider}); err != nil { + return err + } + } + if op.change.Action == apipb.ResourceChange_DESTROY { + return nil + } + return tx.CreateUserIdentity(ctx, &store.UserIdentity{UserID: userID, Provider: op.identity.Provider, ExternUID: op.identity.ExternUID}) +} + // applyUser writes exactly the fields the plan lists, which already leave out // ignored fields, undeclared profile fields, and values that did not change. func applyUser(ctx context.Context, tx *store.ConfigurationTransaction, op *operation, now time.Time) error { @@ -133,6 +162,13 @@ func applyUser(ctx context.Context, tx *store.ConfigurationTransaction, op *oper passwordHash = string(hash) } } + if op.randomPassword { + hash, err := coreuser.RandomPasswordHash() + if err != nil { + return err + } + passwordHash = hash + } if op.actualUser == nil { _, err := tx.CreateUser(ctx, &store.User{ diff --git a/core/configuration/apply_test.go b/core/configuration/apply_test.go index ecfcc8ef1..a1e9c23bb 100644 --- a/core/configuration/apply_test.go +++ b/core/configuration/apply_test.go @@ -166,6 +166,51 @@ func TestApplyRemovals(t *testing.T) { require.Equal(t, []string{"👍"}, memoRelated.GetMemoRelatedSetting().GetReactions(), "a released setting is left as it is") } +func TestApplyLinkedIdentities(t *testing.T) { + ctx := context.Background() + s := newTestStore(t) + files := func(subject string) map[string]string { + return map[string]string{"all.json": `{ + "identityProviders":[` + validIDP + `], + "users":[{"name":"users/admin","username":"admin","role":"ADMIN"}], + "linkedIdentities":[{"name":"users/admin/linkedIdentities/sso","externalUid":"` + subject + `"}]}`} + } + linked := func() *store.UserIdentity { + username := "admin" + user, err := s.GetUser(ctx, &store.FindUser{Username: &username}) + require.NoError(t, err) + require.NotNil(t, user) + identity, err := s.GetUserIdentity(ctx, &store.FindUserIdentity{UserID: &user.ID, Provider: new("sso")}) + require.NoError(t, err) + return identity + } + + // The user and its link are created in one apply; without a declared + // password the user gets one nobody knows, as SSO provisioning does. + plan, state := applyFor(t, loadDesired(t, files("subject-1")), s) + require.True(t, plan.Valid(), plan.Message.Errors) + require.Len(t, state.Resources, 3) + require.Equal(t, "subject-1", linked().ExternUID) + username := "admin" + admin, err := s.GetUser(ctx, &store.FindUser{Username: &username}) + require.NoError(t, err) + require.NotEmpty(t, admin.PasswordHash) + require.Error(t, bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(""))) + + again, _ := applyFor(t, loadDesired(t, files("subject-1")), s) + require.False(t, again.HasChanges(), "a second apply changes nothing") + + _, _ = applyFor(t, loadDesired(t, files("subject-2")), s) + require.Equal(t, "subject-2", linked().ExternUID, "a changed subject replaces the link") + + _, state = applyFor(t, loadDesired(t, map[string]string{"all.json": `{ + "identityProviders":[` + validIDP + `], + "users":[{"name":"users/admin","username":"admin","role":"ADMIN"}], + "removed":[{"resource":"users/admin/linkedIdentities/sso","destroy":true}]}`}), s) + require.Len(t, state.Resources, 2) + require.Nil(t, linked(), "a destroyed link is deleted") +} + func TestApplyFailureRollsBack(t *testing.T) { ctx := context.Background() s := newTestStore(t) diff --git a/core/configuration/configuration_test.go b/core/configuration/configuration_test.go index 3f9e42555..9d666475e 100644 --- a/core/configuration/configuration_test.go +++ b/core/configuration/configuration_test.go @@ -211,7 +211,14 @@ func TestLoadChecksSchema(t *testing.T) { "path through list": {`{"identityProviders":[{"name":"identity-providers/sso"}],"lifecycle":[{"resource":"identity-providers/sso","ignoreChanges":["config.oauth2Config.scopes.x"]}]}`, "is not a message field"}, "removed bad name": {`{"removed":[{"resource":"memos/123"}]}`, "removed[0].resource"}, "lifecycle dangling": {`{"lifecycle":[{"resource":"users/admin"}]}`, "names users/admin, which no file declares"}, - "removed declared": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"removed":[{"resource":"users/admin"}]}`, "is removed but still declared"}, + "identity no uid": {`{"linkedIdentities":[{"name":"users/admin/linkedIdentities/sso"}]}`, "linkedIdentities[0].externalUid is required"}, + "identity bad name": {`{"linkedIdentities":[{"name":"users/admin/linkedIdentities/-sso","externalUid":"s"}]}`, "invalid linked identity name"}, + "identity provider": {`{"linkedIdentities":[{"name":"users/admin/linkedIdentities/sso","externalUid":"s","identityProvider":"identity-providers/sso"}]}`, "linkedIdentities[0].identityProvider is output only"}, + "identity no user": {`{"linkedIdentities":[{"name":"users/admin/linkedIdentities/sso","externalUid":"s"}]}`, "users/admin/linkedIdentities/sso is declared for users/admin, which no file declares"}, + "identity ignore": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"linkedIdentities":[{"name":"users/admin/linkedIdentities/sso","externalUid":"s"}],"lifecycle":[{"resource":"users/admin/linkedIdentities/sso","ignoreChanges":["externalUid"]}]}`, "ignoreChanges does not apply to linked identities"}, + "identity twice": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"},{"name":"users/root","username":"root","role":"ADMIN"}], + "linkedIdentities":[{"name":"users/admin/linkedIdentities/sso","externalUid":"s"},{"name":"users/root/linkedIdentities/sso","externalUid":"s"}]}`, "users/root/linkedIdentities/sso declares the same identity-providers/sso subject as users/admin/linkedIdentities/sso"}, + "removed declared": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"removed":[{"resource":"users/admin"}]}`, "is removed but still declared"}, } for name, test := range tests { t.Run(name, func(t *testing.T) { diff --git a/core/configuration/plan.go b/core/configuration/plan.go index b4d4f602a..6d03c48b6 100644 --- a/core/configuration/plan.go +++ b/core/configuration/plan.go @@ -25,6 +25,7 @@ type Reader interface { ListIdentityProviders(ctx context.Context, find *store.FindIdentityProvider) ([]*storepb.IdentityProvider, error) GetUncachedInstanceSetting(ctx context.Context, find *store.FindInstanceSetting) (*storepb.InstanceSetting, error) ListUsers(ctx context.Context, find *store.FindUser) ([]*store.User, error) + ListUserIdentities(ctx context.Context, find *store.FindUserIdentity) ([]*store.UserIdentity, error) } // Plan is what apply would change. @@ -51,8 +52,16 @@ type operation struct { settingKey storepb.InstanceSettingKey // The managed part of a declared user, and the stored user when it exists. - user *apipb.User - actualUser *store.User + // A user created without a declared password gets an unusable random one. + user *apipb.User + actualUser *store.User + randomPassword bool + + // The identity link to write, without its user ID, which apply resolves + // from identityUsername once the user exists; and the stored link, if any. + identity *store.UserIdentity + identityUsername string + actualIdentity *store.UserIdentity } // Valid reports whether the plan can be applied. @@ -66,11 +75,14 @@ func (p *Plan) HasChanges() bool { } // Apply order: identity providers are created and updated first, so a GENERAL -// setting that needs one finds it; users are destroyed before providers. +// setting that needs one finds it; linked identities follow the users they +// belong to; users are destroyed before providers. const ( rankIdentityProvider = iota rankInstanceSetting rankUser + rankLinkedIdentity + rankLinkedIdentityDestroy rankUserDestroy rankIdentityProviderDestroy ) @@ -109,7 +121,7 @@ func ComputePlan(ctx context.Context, desired *Desired, reader Reader) (*Plan, e p.removed[removed.Resource] = removed } - steps := []func() error{p.planIdentityProviders, p.planInstanceSettings, p.planUsers, p.planUndeclared, p.checkAuthentication} + steps := []func() error{p.planIdentityProviders, p.planInstanceSettings, p.planUsers, p.planLinkedIdentities, p.planUndeclared, p.checkAuthentication} for _, step := range steps { if err := step(); err != nil { return nil, err @@ -131,6 +143,8 @@ type planner struct { next []*storepb.InstanceConfigurationState_ManagedResource providersByUID map[string]*storepb.IdentityProvider + // The stored users the configuration declares, by username. + declaredUsers map[string]*store.User // What the authentication invariant needs about the planned end state. providersAfter map[string]bool @@ -364,6 +378,13 @@ func (p *planner) planUsers() error { actualByName[user.Username] = user } } + p.declaredUsers = actualByName + + linkedUsers := map[string]bool{} + for _, identity := range p.desired.Configuration.LinkedIdentities { + userName, _ := splitLinkedIdentityName(identity.GetName()) + linkedUsers[userName] = true + } for _, declared := range declaredUsers { name := declared.Name @@ -373,9 +394,16 @@ func (p *planner) planUsers() error { version := lifecycle.GetWriteOnlyVersion() recorded := p.managed[name].GetWriteOnlyVersion() sendPassword := actual == nil || version > recorded + // A user with a declared linked identity signs in through its provider, + // so it may be created without a password, as SSO provisioning creates + // users: with a random password nobody knows. + randomPassword := actual == nil && declared.Password == "" && linkedUsers[name] + if randomPassword { + sendPassword = false + } if sendPassword && declared.Password == "" { if actual == nil { - p.fail(name, "password is required to create the user") + p.fail(name, "password is required to create the user, unless a linked identity is declared for it") } else { p.fail(name, "writeOnlyVersion is %d, above the %d last applied, but no password is declared", version, recorded) } @@ -389,7 +417,11 @@ func (p *planner) planUsers() error { Digest: digest(managedView, lifecycle), WriteOnlyVersion: max(version, recorded), } - p.declared(rankUser, name, KindUser, actual != nil, changes, entry, &operation{user: managedView, actualUser: actual}) + op := &operation{user: managedView, actualUser: actual, randomPassword: randomPassword} + p.declared(rankUser, name, KindUser, actual != nil, changes, entry, op) + if randomPassword { + op.change.Message = "created without a password; signs in through its linked identity" + } } return nil } @@ -449,6 +481,101 @@ func (p *planner) userChanges(view *apipb.User, actual *store.User, sendPassword return changes } +// planLinkedIdentities plans the identity links of declared users. The user is +// declared, so the schema layer already guarantees planUsers saw it; the +// provider must exist after apply; and a subject already linked to another +// user is never taken over, since the plan cannot know which binding is right. +func (p *planner) planLinkedIdentities() error { + for _, declared := range sortedByName(p.desired.Configuration.LinkedIdentities, (*apipb.LinkedIdentity).GetName) { + name := declared.Name + userName, providerName := splitLinkedIdentityName(name) + username := strings.TrimPrefix(userName, coreuser.NamePrefix) + uid := strings.TrimPrefix(providerName, identityprovider.NamePrefix) + if !p.providersAfter[uid] { + p.fail(name, "names %s, which would not exist after apply", providerName) + continue + } + user := p.declaredUsers[username] + holders, err := p.reader.ListUserIdentities(p.ctx, &store.FindUserIdentity{Provider: &uid, ExternUID: &declared.ExternalUid}) + if err != nil { + return errors.Wrapf(err, "failed to read the identity links of %s", providerName) + } + if len(holders) > 0 && (user == nil || holders[0].UserID != user.ID) { + holder, err := p.userName(holders[0].UserID) + if err != nil { + return err + } + p.fail(name, "the %s subject is already linked to %s; unlink it there first", providerName, holder) + continue + } + + var actual *store.UserIdentity + if user != nil { + links, err := p.reader.ListUserIdentities(p.ctx, &store.FindUserIdentity{UserID: &user.ID, Provider: &uid}) + if err != nil { + return errors.Wrapf(err, "failed to read the identity links of %s", userName) + } + if len(links) > 0 { + actual = links[0] + } + } + desiredAPI := &apipb.LinkedIdentity{Name: name, ExternalUid: declared.ExternalUid} + var actualAPI proto.Message + if actual != nil { + actualAPI = &apipb.LinkedIdentity{Name: name, ExternalUid: actual.ExternUID} + } + changes := diffResource(actualAPI, desiredAPI, nil) + entry := &storepb.InstanceConfigurationState_ManagedResource{ + ManagedFields: []string{"*"}, + Digest: digest(desiredAPI, p.lifecycle[name]), + References: []string{providerName}, + } + op := &operation{ + identity: &store.UserIdentity{Provider: uid, ExternUID: declared.ExternalUid}, + identityUsername: username, + actualIdentity: actual, + actualUser: user, + } + p.declared(rankLinkedIdentity, name, KindLinkedIdentity, actual != nil, changes, entry, op) + } + return nil +} + +// userName returns the resource name of the stored user with id. +func (p *planner) userName(id int32) (string, error) { + users, err := p.reader.ListUsers(p.ctx, &store.FindUser{ID: &id}) + if err != nil { + return "", errors.Wrap(err, "failed to read user") + } + if len(users) == 0 { + return "a deleted user", nil + } + return coreuser.NamePrefix + users[0].Username, nil +} + +// storedLinkedIdentity returns the identity link a managed linked identity +// name describes, or nil when the user or the link is gone. +func (p *planner) storedLinkedIdentity(name string) (*store.User, *store.UserIdentity, error) { + userName, providerName := splitLinkedIdentityName(name) + username := strings.TrimPrefix(userName, coreuser.NamePrefix) + uid := strings.TrimPrefix(providerName, identityprovider.NamePrefix) + users, err := p.reader.ListUsers(p.ctx, &store.FindUser{Username: &username}) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to read user") + } + if len(users) == 0 { + return nil, nil, nil + } + links, err := p.reader.ListUserIdentities(p.ctx, &store.FindUserIdentity{UserID: &users[0].ID, Provider: &uid}) + if err != nil { + return nil, nil, errors.Wrapf(err, "failed to read the identity links of %s", userName) + } + if len(links) == 0 { + return users[0], nil, nil + } + return users[0], links[0], nil +} + // planUndeclared handles managed resources no file declares any longer: a // removed entry destroys, resets, or releases them; without one, removal was // not explicit and the plan fails. @@ -466,7 +593,7 @@ func (p *planner) planUndeclared() error { } change := &apipb.ResourceChange{Resource: name} op := &operation{change: change, kind: kind} - rank := map[Kind]int{KindIdentityProvider: rankIdentityProvider, KindInstanceSetting: rankInstanceSetting, KindUser: rankUser}[kind] + rank := map[Kind]int{KindIdentityProvider: rankIdentityProvider, KindInstanceSetting: rankInstanceSetting, KindUser: rankUser, KindLinkedIdentity: rankLinkedIdentity}[kind] switch { case removed == nil: change.Action = apipb.ResourceChange_ERROR @@ -491,6 +618,19 @@ func (p *planner) planUndeclared() error { p.generalAfter = &storepb.InstanceGeneralSetting{} p.generalPlanned = true } + case kind == KindLinkedIdentity: + user, link, err := p.storedLinkedIdentity(name) + if err != nil { + return err + } + if link == nil { + change.Action = apipb.ResourceChange_RELEASE + change.Message = "already deleted outside the configuration" + break + } + change.Action = apipb.ResourceChange_DESTROY + rank = rankLinkedIdentityDestroy + op.actualUser, op.actualIdentity = user, link default: if !p.providersAfter[id] { change.Action = apipb.ResourceChange_RELEASE diff --git a/core/configuration/plan_test.go b/core/configuration/plan_test.go index 2ff993572..358453717 100644 --- a/core/configuration/plan_test.go +++ b/core/configuration/plan_test.go @@ -21,10 +21,11 @@ import ( // fakeReader is an in-memory instance for planning. type fakeReader struct { - state *storepb.InstanceConfigurationState - providers []*storepb.IdentityProvider - settings map[storepb.InstanceSettingKey]*storepb.InstanceSetting - users []*store.User + state *storepb.InstanceConfigurationState + providers []*storepb.IdentityProvider + settings map[storepb.InstanceSettingKey]*storepb.InstanceSetting + users []*store.User + identities []*store.UserIdentity } func newFakeReader() *fakeReader { @@ -54,7 +55,8 @@ func (f *fakeReader) GetUncachedInstanceSetting(_ context.Context, find *store.F func (f *fakeReader) ListUsers(_ context.Context, find *store.FindUser) ([]*store.User, error) { result := []*store.User{} for _, user := range f.users { - if find.Username != nil && user.Username != *find.Username || + if find.ID != nil && user.ID != *find.ID || + find.Username != nil && user.Username != *find.Username || len(find.UsernameList) > 0 && !slices.Contains(find.UsernameList, user.Username) || len(find.IDList) > 0 && !slices.Contains(find.IDList, user.ID) { continue @@ -65,6 +67,20 @@ func (f *fakeReader) ListUsers(_ context.Context, find *store.FindUser) ([]*stor return result, nil } +func (f *fakeReader) ListUserIdentities(_ context.Context, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { + result := []*store.UserIdentity{} + for _, identity := range f.identities { + if find.UserID != nil && identity.UserID != *find.UserID || + find.Provider != nil && identity.Provider != *find.Provider || + find.ExternUID != nil && identity.ExternUID != *find.ExternUID { + continue + } + copied := *identity + result = append(result, &copied) + } + return result, nil +} + // apply stands in for apply: the instance takes the declared values and the // state record becomes the plan's. func (f *fakeReader) apply(t *testing.T, desired *Desired, plan *Plan) { @@ -286,6 +302,72 @@ func TestPlanOrdersActions(t *testing.T) { require.Equal(t, []string{"identity-providers/sso", "instance/settings/ACCESS", "users/admin", "identity-providers/old"}, order) } +func TestPlanLinkedIdentities(t *testing.T) { + admin := func(identity string) map[string]string { + return map[string]string{"all.json": `{ + "identityProviders":[` + validIDP + `], + "users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"pw"}], + "linkedIdentities":[` + identity + `]}`} + } + declared := admin(`{"name":"users/admin/linkedIdentities/sso","externalUid":"subject-1"}`) + + // Everything new: the link is created after its user, and it names its provider. + reader := newFakeReader() + result := planFor(t, loadDesired(t, declared), reader) + require.True(t, result.Valid(), result.Message.Errors) + link := changeFor(t, result, "users/admin/linkedIdentities/sso") + require.Equal(t, apipb.ResourceChange_CREATE, link.Action) + require.Equal(t, []*apipb.FieldChange{{Path: "externalUid", After: `"subject-1"`}}, link.FieldChanges) + order := []string{} + for _, change := range result.Message.ResourceChanges { + order = append(order, change.Resource) + } + require.Equal(t, []string{"identity-providers/sso", "users/admin", "users/admin/linkedIdentities/sso"}, order) + for _, resource := range result.next.Resources { + if resource.Name == "users/admin/linkedIdentities/sso" { + require.Equal(t, "LinkedIdentity", resource.Kind) + require.Equal(t, []string{"identity-providers/sso"}, resource.References) + } + } + + // A link the user made by signing in is adopted; a different subject is replaced. + reader.users = []*store.User{{ID: 1, Username: "admin", Role: store.RoleAdmin}, {ID: 2, Username: "other"}} + reader.identities = []*store.UserIdentity{{ID: 1, UserID: 1, Provider: "sso", ExternUID: "subject-1"}} + require.Equal(t, apipb.ResourceChange_ADOPT, changeFor(t, planFor(t, loadDesired(t, declared), reader), "users/admin/linkedIdentities/sso").Action) + replaced := changeFor(t, planFor(t, loadDesired(t, admin(`{"name":"users/admin/linkedIdentities/sso","externalUid":"subject-2"}`)), reader), "users/admin/linkedIdentities/sso") + require.Equal(t, apipb.ResourceChange_ADOPT, replaced.Action) + require.Equal(t, []*apipb.FieldChange{{Path: "externalUid", Before: `"subject-1"`, After: `"subject-2"`}}, replaced.FieldChanges) + + // A subject another user holds is never taken over. + reader.identities = []*store.UserIdentity{{ID: 1, UserID: 2, Provider: "sso", ExternUID: "subject-1"}} + taken := planFor(t, loadDesired(t, declared), reader) + require.False(t, taken.Valid()) + require.Contains(t, strings.Join(taken.Message.Errors, "\n"), "the identity-providers/sso subject is already linked to users/other; unlink it there first") + + // The provider must exist after apply, declared or stored. + reader.identities = nil + missing := planFor(t, loadDesired(t, admin(`{"name":"users/admin/linkedIdentities/elsewhere","externalUid":"subject-1"}`)), reader) + require.Contains(t, strings.Join(missing.Message.Errors, "\n"), "names identity-providers/elsewhere, which would not exist after apply") + reader.providers = []*storepb.IdentityProvider{{Id: 2, Uid: "elsewhere"}} + require.True(t, planFor(t, loadDesired(t, admin(`{"name":"users/admin/linkedIdentities/elsewhere","externalUid":"subject-1"}`)), reader).Valid()) + + // Undeclared: destroy deletes the stored link, or releases one already gone. + reader.identities = []*store.UserIdentity{{ID: 1, UserID: 1, Provider: "sso", ExternUID: "subject-1"}} + reader.state = &storepb.InstanceConfigurationState{Resources: []*storepb.InstanceConfigurationState_ManagedResource{ + {Name: "users/admin/linkedIdentities/sso", Kind: "LinkedIdentity", ManagedFields: []string{"*"}}, + {Name: "users/admin/linkedIdentities/gone", Kind: "LinkedIdentity", ManagedFields: []string{"*"}}, + {Name: "users/admin/linkedIdentities/kept", Kind: "LinkedIdentity", ManagedFields: []string{"*"}}, + }} + removed := planFor(t, loadDesired(t, map[string]string{"removed.json": `{"removed":[ + {"resource":"users/admin/linkedIdentities/sso","destroy":true}, + {"resource":"users/admin/linkedIdentities/gone","destroy":true}, + {"resource":"users/admin/linkedIdentities/kept"}]}`}), reader) + require.True(t, removed.Valid(), removed.Message.Errors) + require.Equal(t, apipb.ResourceChange_DESTROY, changeFor(t, removed, "users/admin/linkedIdentities/sso").Action) + require.Equal(t, apipb.ResourceChange_RELEASE, changeFor(t, removed, "users/admin/linkedIdentities/gone").Action) + require.Equal(t, apipb.ResourceChange_RELEASE, changeFor(t, removed, "users/admin/linkedIdentities/kept").Action) +} + func TestPlanUsers(t *testing.T) { reader := newFakeReader() require.Contains(t, strings.Join(planFor(t, loadDesired(t, map[string]string{"u.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}]}`}), reader).Message.Errors, ""), @@ -319,6 +401,16 @@ func TestPlanUsers(t *testing.T) { noPassword := loadDesired(t, map[string]string{"u.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"lifecycle":[{"resource":"users/admin","writeOnlyVersion":2}]}`}) require.Contains(t, strings.Join(planFor(t, noPassword, reader).Message.Errors, ""), "no password is declared") + + // A user with a declared linked identity needs no password to be created. + linked := planFor(t, loadDesired(t, map[string]string{"u.json": `{"identityProviders":[` + validIDP + `], + "users":[{"name":"users/sso-admin","username":"sso-admin","role":"ADMIN"}], + "linkedIdentities":[{"name":"users/sso-admin/linkedIdentities/sso","externalUid":"subject"}]}`}), newFakeReader()) + require.True(t, linked.Valid(), linked.Message.Errors) + ssoAdmin := changeFor(t, linked, "users/sso-admin") + require.Equal(t, apipb.ResourceChange_CREATE, ssoAdmin.Action) + require.Equal(t, []*apipb.FieldChange{{Path: "username", After: `"sso-admin"`}, {Path: "role", After: "ADMIN"}}, ssoAdmin.FieldChanges) + require.Equal(t, "created without a password; signs in through its linked identity", ssoAdmin.Message) } func TestPlanAuthenticationInvariant(t *testing.T) { diff --git a/core/configuration/schema.go b/core/configuration/schema.go index b36897181..6ecfbe5ae 100644 --- a/core/configuration/schema.go +++ b/core/configuration/schema.go @@ -23,6 +23,7 @@ const ( KindIdentityProvider Kind = "IdentityProvider" KindInstanceSetting Kind = "InstanceSetting" KindUser Kind = "User" + KindLinkedIdentity Kind = "LinkedIdentity" ) // ConfigurableInstanceSettingKeys are the instance setting keys a file may declare. @@ -32,7 +33,9 @@ var ConfigurableInstanceSettingKeys = []string{"ACCESS", "GENERAL", "STORAGE", " // to the user. var userFields = []protoreflect.Name{"name", "username", "display_name", "email", "password", "role"} -// ParseResourceName returns the kind and identifier of a configurable resource name. +// ParseResourceName returns the kind and identifier of a configurable resource +// name. A linked identity's identifier is {user}/{idp}; splitLinkedIdentityName +// returns the two parts. func ParseResourceName(name string) (Kind, string, error) { switch { case strings.HasPrefix(name, identityprovider.NamePrefix): @@ -56,16 +59,29 @@ func ParseResourceName(name string) (Kind, string, error) { return "", "", errors.Errorf("unknown instance setting %q", name) } case strings.HasPrefix(name, coreuser.NamePrefix): + if username, uid, ok := coreuser.SplitLinkedIdentityName(name); ok { + if coreuser.ValidateUsername(username) != nil || !identifier.UIDMatcher.MatchString(uid) { + return "", "", errors.Errorf("invalid linked identity name %q", name) + } + return KindLinkedIdentity, username + "/" + uid, nil + } username := strings.TrimPrefix(name, coreuser.NamePrefix) if err := coreuser.ValidateUsername(username); err != nil { return "", "", errors.Errorf("invalid user name %q", name) } return KindUser, username, nil default: - return "", "", errors.Errorf("%q is not an identity provider, instance setting, or user name", name) + return "", "", errors.Errorf("%q is not an identity provider, instance setting, user, or linked identity name", name) } } +// splitLinkedIdentityName returns the user and identity provider names a +// linked identity name joins. The name must have parsed as KindLinkedIdentity. +func splitLinkedIdentityName(name string) (userName, providerName string) { + username, uid, _ := coreuser.SplitLinkedIdentityName(name) + return coreuser.NamePrefix + username, identityprovider.NamePrefix + uid +} + // checkDocument checks the rules one file must meet on its own. func checkDocument(document *apipb.Configuration) []string { var problems []string @@ -128,6 +144,14 @@ func checkDocument(document *apipb.Configuration) []string { }) } + for i, identity := range document.LinkedIdentities { + path := fmt.Sprintf("linkedIdentities[%d]", i) + checkName(path, identity.GetName(), KindLinkedIdentity) + if identity.GetExternalUid() == "" { + report("%s.externalUid is required", path) + } + } + for i, lifecycle := range document.Lifecycle { path := fmt.Sprintf("lifecycle[%d]", i) if lifecycle.GetResource() == "" { @@ -145,6 +169,10 @@ func checkDocument(document *apipb.Configuration) []string { if lifecycle.GetWriteOnlyVersion() != 0 && kind != KindUser { report("%s.writeOnlyVersion applies only to users", path) } + if len(lifecycle.GetIgnoreChanges()) > 0 && kind == KindLinkedIdentity { + report("%s.ignoreChanges does not apply to linked identities; externalUid is the whole resource", path) + continue + } for j, fieldPath := range lifecycle.GetIgnoreChanges() { if err := checkFieldPath(kindDescriptor(kind), fieldPath); err != nil { report("%s.ignoreChanges[%d]: %v", path, j, err) @@ -171,6 +199,8 @@ func kindDescriptor(kind Kind) protoreflect.MessageDescriptor { return (&apipb.IdentityProvider{}).ProtoReflect().Descriptor() case KindInstanceSetting: return (&apipb.InstanceSetting{}).ProtoReflect().Descriptor() + case KindLinkedIdentity: + return (&apipb.LinkedIdentity{}).ProtoReflect().Descriptor() default: return (&apipb.User{}).ProtoReflect().Descriptor() } @@ -204,7 +234,8 @@ func checkFieldPath(descriptor protoreflect.MessageDescriptor, path string) erro // merger combines files into one desired state and checks the rules that span // files: one declaration per resource, lifecycle rules for declared resources, -// and removals of resources no file still declares. +// removals of resources no file still declares, and linked identities whose +// user is declared and whose subject is declared once. type merger struct { desired *Desired problems []string @@ -242,6 +273,11 @@ func (m *merger) add(file string, document *apipb.Configuration, userFields map[ m.desired.UserFields[user.GetName()] = userFields[i] } } + for _, identity := range document.LinkedIdentities { + if claim(m.desired.Sources, identity.GetName(), "resource") { + config.LinkedIdentities = append(config.LinkedIdentities, identity) + } + } for _, lifecycle := range document.Lifecycle { if claim(m.lifecycleSources, lifecycle.GetResource(), "a lifecycle rule") { config.Lifecycle = append(config.Lifecycle, lifecycle) @@ -267,4 +303,23 @@ func (m *merger) checkReferences() { m.removedSources[removed.GetResource()], removed.GetResource(), declaredIn)) } } + // A linked identity binds a subject to a declared user: the declaration is + // what makes the binding trustworthy, so an undeclared user cannot have one. + // A subject signs in as one user, so it is declared at most once. + subjects := map[string]string{} + for _, identity := range m.desired.Configuration.LinkedIdentities { + name := identity.GetName() + userName, providerName := splitLinkedIdentityName(name) + if _, ok := m.desired.Sources[userName]; !ok { + m.problems = append(m.problems, fmt.Sprintf("%s: %s is declared for %s, which no file declares; a linked identity needs a declared user", + m.desired.Sources[name], name, userName)) + } + subject := providerName + " " + identity.GetExternalUid() + if previous, ok := subjects[subject]; ok { + m.problems = append(m.problems, fmt.Sprintf("%s: %s declares the same %s subject as %s", + m.desired.Sources[name], name, providerName, previous)) + continue + } + subjects[subject] = name + } } diff --git a/core/configuration/testdata/compat/unreleased/instance.json b/core/configuration/testdata/compat/unreleased/instance.json index 8b236bf83..a2bede50b 100644 --- a/core/configuration/testdata/compat/unreleased/instance.json +++ b/core/configuration/testdata/compat/unreleased/instance.json @@ -31,6 +31,9 @@ "users": [ { "name": "users/admin", "username": "admin", "role": "ADMIN", "password": "${file:/run/secrets/memos-admin-password}" } ], + "linkedIdentities": [ + { "name": "users/admin/linkedIdentities/company-sso", "externalUid": "${env:ADMIN_SSO_SUBJECT}" } + ], "lifecycle": [ { "resource": "users/admin", "preventDestroy": true, "writeOnlyVersion": 1 } ] diff --git a/core/user/user.go b/core/user/user.go index 6d293f1d2..903aebc68 100644 --- a/core/user/user.go +++ b/core/user/user.go @@ -3,9 +3,13 @@ package user import ( + "strings" + "github.com/pkg/errors" + "golang.org/x/crypto/bcrypt" "github.com/usememos/memos/internal/identifier" + "github.com/usememos/memos/internal/random" apipb "github.com/usememos/memos/proto/gen/api" "github.com/usememos/memos/store" ) @@ -13,6 +17,42 @@ import ( // NamePrefix starts every user resource name. const NamePrefix = "users/" +// linkedIdentitiesSegment separates the user from the identity provider in a +// linked identity name. +const linkedIdentitiesSegment = "/linkedIdentities/" + +// LinkedIdentityName is the resource name of the link between the user with +// username and the identity provider with uid provider: +// users/{user}/linkedIdentities/{idp}. +func LinkedIdentityName(username, provider string) string { + return NamePrefix + username + linkedIdentitiesSegment + provider +} + +// SplitLinkedIdentityName returns the username and identity provider uid a +// linked identity name joins, and whether name has that shape. It does not +// validate either part. +func SplitLinkedIdentityName(name string) (username, provider string, ok bool) { + rest, ok := strings.CutPrefix(name, NamePrefix) + if !ok { + return "", "", false + } + return strings.Cut(rest, linkedIdentitiesSegment) +} + +// RandomPasswordHash returns the hash of a password nobody knows, for an +// account that signs in through an identity provider and never with a password. +func RandomPasswordHash() (string, error) { + password, err := random.String(20) + if err != nil { + return "", errors.Wrap(err, "failed to generate a random password") + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return "", errors.Wrap(err, "failed to hash the password") + } + return string(hash), nil +} + // ValidateUsername reports whether username may be written as a new or // changed username. func ValidateUsername(username string) error { diff --git a/docs/design/declarative-configuration.md b/docs/design/declarative-configuration.md index bb8fd573d..5d0c7408d 100644 --- a/docs/design/declarative-configuration.md +++ b/docs/design/declarative-configuration.md @@ -4,7 +4,7 @@ Status: Draft ## Summary -Operators describe the identity providers, instance settings, and bootstrap users an instance should have in configuration files. Memos +Operators describe the identity providers, instance settings, bootstrap users, and those users' SSO identities an instance should have in configuration files. Memos treats those files as the desired state, compares them with the actual state in the database, shows the difference as a plan, and applies the plan as one atomic database transaction. A state record remembers which resources the configuration manages, so Memos can detect drift, release or destroy resources that leave the configuration, and refuse API writes that would silently diverge from the files. @@ -20,7 +20,7 @@ A declarative configuration system has five parts. Every decision below is a cho | Part | Memos | | --- | --- | | Desired state | JSON documents in a configuration directory, merged into one `memos.api.Configuration` | -| Actual state | The `idp`, `system_setting`, and `user` tables, read through the store | +| Actual state | The `idp`, `system_setting`, `user`, and `user_identity` tables, read through the store | | State record | One `CONFIGURATION_STATE` row in `system_setting`: a serial and the list of managed resources, never a value | | Plan | A deterministic list of per-resource actions computed from desired, actual, and state record, printable as text or JSON | | Apply | The plan executed inside one serializable transaction, followed by an update of the state record in the same transaction | @@ -75,7 +75,7 @@ Failing one puts the resource in the UI and API. | `users/*/webhooks/*` | Later | Reproducible wiring for an automation user; content for anyone else | | `users/*/personalAccessTokens/*` | Later, with care | Bootstrapping an MCP client needs a token before anyone signs in; the value would be a write-only field the operator supplies | | `users/*/settings/*`, `users/*/views/*` | Never | Personal preferences | -| `users/*/linkedIdentities/*` | Never | Created by signing in, not declared | +| `users/*/linkedIdentities/*` | In, for declared users | A bootstrap administrator on an SSO-only instance needs a way in before the first sign-in; a declared subject trusts no claim the provider makes. Other users' links are created by signing in | | `users/*/notifications/*`, `users/*/stats`, `users/*/usage`, `spaces/*/invitations/*` | Never | Transient or computed | | `memos/*`, `attachments/*`, reactions, shares, comments | Never | Content | @@ -169,6 +169,9 @@ message Configuration { repeated Lifecycle lifecycle = 4; // Resources to take out of management. repeated Removed removed = 5; + // SSO identities of declared users, by resource name: which identity-provider + // subject signs in as which user. + repeated LinkedIdentity linked_identities = 6; } // Lifecycle adjusts how one declared resource is planned. Mirrors Terraform's @@ -234,6 +237,9 @@ Example `/etc/memos/config/instance.json`: "users": [ { "name": "users/admin", "username": "admin", "role": "ADMIN", "password": "${file:/run/secrets/memos-admin-password}" } ], + "linkedIdentities": [ + { "name": "users/admin/linkedIdentities/company-sso", "externalUid": "${env:ADMIN_SSO_SUBJECT}" } + ], "lifecycle": [ { "resource": "users/admin", "preventDestroy": true, "writeOnlyVersion": 1 } ] @@ -312,7 +318,7 @@ values exactly as to values written through the API, because both paths write th | `username` | managed, must equal the `{user}` segment | | `role` | managed | | `displayName`, `email` | optional: managed only when declared, otherwise left as the user set them | -| `password` | write-only | +| `password` | write-only; required to create the user unless a linked identity is declared for it | Users are included for one purpose: bringing up an instance without a browser. The user owns their profile, so the configuration manages only what it declares. Presence is taken from the JSON document, not from the decoded message, so `"displayName": ""` manages the field as @@ -322,12 +328,38 @@ empty while omitting it leaves the field alone. protected by the API guard, so the administrator can change their own password in the UI. Apply sends it on create and whenever the resource's `lifecycle.writeOnlyVersion` is greater than the version recorded in the state record. Resending on every apply would undo a password change at every restart; resending only on an explicit version bump is the behavior Terraform standardized on for the same reason. +A user with a declared linked identity signs in through its provider, so it may be created without a password: apply then gives it a +random password nobody knows, exactly as the sign-in path provisions a new SSO user. Declaring a password later, with a version bump, +sets one. Configuration never deletes a user. Deleting one deletes their memos and attachment files and must respect the spaces they belong to, which is the deletion flow in Settings, with its confirmations. A `removed` entry with `destroy: true` for a user is therefore a plan error; `destroy: false` releases the user, who can then be deleted in Settings. `preventDestroy` still guards a user's identity provider and settings, and is recommended for every declared user for the day that changes. +### LinkedIdentity + +| Field | Class | +| --- | --- | +| `name` | identity, `users/{user}/linkedIdentities/{idp}`: the user and the identity provider it links | +| `externalUid` | managed: the provider's subject that signs in as the user | +| `identityProvider` | output only; it repeats the name | + +A linked identity exists for one case: an administrator declared in the files, on an instance where sign-in is through an identity +provider. Without it the first sign-in through the provider provisions a new account, because the sign-in path matches a provider and +subject and nothing else. Matching on an email or a username claim instead was rejected: a provider's email claim is not proof of +ownership on this instance, the OAuth2 mapping has no verified-email claim, and a provider username is chosen by whoever signs up there. +A declared subject trusts no claim: the operator reads it once from the provider and writes it down, and the sign-in path is unchanged. + +The user must be declared in the same configuration. The declaration is what makes the binding trustworthy, so a link for an undeclared +user is a schema error, and a link stays managed only while its user is. One subject signs in as one user, so a subject declared twice is +a schema error, and plan fails when the subject is already linked to a different user rather than taking it over. The provider must exist +after apply, declared or stored. A link the user made by signing in with the declared subject is adopted; a different stored subject for +that provider is replaced, since the user has one link per provider. + +Destroy deletes the link; the user keeps the account and can sign in with the password, or link again by signing in through the provider +once the link is released. `ignoreChanges` does not apply, since `externalUid` is the whole resource. + ## State record Terraform keeps a state file because the files alone cannot answer three questions: which existing resources are managed, what was removed @@ -452,14 +484,15 @@ is hidden. ### Ordering and dependencies Actions are ordered so every intermediate state is valid even though apply is atomic (the order matters for the plan text and for the -invariant check): identity provider creates and updates, then instance setting updates and resets, then user creates and updates, then -identity provider destroys. Within a group, resource names sort lexically. +invariant check): identity provider creates and updates, then instance setting updates and resets, then user creates and updates, then linked identity +creates, updates, and destroys, then identity provider destroys. Within a group, resource names sort lexically. ### Validation Validation runs in three layers, and the first two are the same code the API uses: -1. Schema: strict decoding, substitution, resource name format, the `oneof` matching the setting key, `username` matching `{user}`. +1. Schema: strict decoding, substitution, resource name format, the `oneof` matching the setting key, `username` matching `{user}`, a + linked identity's user declared and its subject declared once. 2. Resource: the per-resource rules the API applies on create and update, called from one shared package per resource under `core/` (S3 credentials present for an S3 storage, SMTP host and sender present when email is enabled, AI providers have IDs and keys, `ACCESS` mode is explicit, week start offset in range, `defaultStorageId` names a declared storage, storage IDs unique and non-empty, @@ -469,10 +502,10 @@ Validation runs in three layers, and the first two are the same code the API use does not re-check a storage it leaves unchanged, so a storage stored before a rule existed does not block editing the others; a declared file has no such exemption, since it states the whole value. An OAuth2 provider needs a client ID, absolute HTTP(S) endpoints, and an identifier mapping; a client secret and scopes stay optional because public clients have neither. -3. Cross-resource: rules that hold over the whole desired state. The one such rule today is the authentication invariant: when the - effective `GENERAL` setting disables password sign-in for regular users, at least one identity provider must exist after apply. It is - checked against the planned end state, so a plan that both deletes the last provider and leaves password sign-in disabled fails before - anything is written. +3. Cross-resource: rules that hold over the whole desired state. The authentication invariant: when the effective `GENERAL` setting + disables password sign-in for regular users, at least one identity provider must exist after apply. It is checked against the planned + end state, so a plan that both deletes the last provider and leaves password sign-in disabled fails before anything is written. And a + linked identity's provider must exist after apply, and its subject must not be linked to another user. `memos config validate` runs layer 1 and 2 without a database. `memos config plan` runs all three. Without a database, the users a `USAGE_LIMITS` setting names get stand-in IDs for layer 2, since its rules depend only on the list's shape; whether those users exist is @@ -557,16 +590,17 @@ metadata: resource = identity-providers/company-sso ``` The guard is a rule in `core/configuration` applied by `CreateIdentityProvider`, `UpdateIdentityProvider`, `DeleteIdentityProvider`, -`UpdateInstanceSetting`, `UpdateUser`, and `DeleteUser`. It makes three checks, each refused with the same error: +`UpdateInstanceSetting`, `UpdateUser`, `DeleteUser`, `CreateLinkedIdentity`, and `DeleteLinkedIdentity`. It makes three checks, each +refused with the same error: - **Change.** `UpdateIdentityProvider`, `UpdateInstanceSetting`, and `UpdateUser` compare the request against the stored resource and refuse only when a managed field would change. -- **Existence.** `CreateIdentityProvider` refuses a name the configuration manages, so the resource cannot exist twice; - `DeleteIdentityProvider` and `DeleteUser` refuse to delete a managed resource. +- **Existence.** `CreateIdentityProvider` and `CreateLinkedIdentity` refuse a name the configuration manages, so the resource cannot + exist twice; `DeleteIdentityProvider`, `DeleteUser`, and `DeleteLinkedIdentity` refuse to delete a managed resource. - **Reference.** `UpdateUser` refuses a username change and `DeleteUser` a deletion when a managed resource names the user, such as a - managed usage-limits setting listing it, though the user is not itself managed: the next plan could not resolve the name, and a - startup apply would stop the server. The error names the user, the referring resource in `metadata.referenced_by`, and its file; the - operator removes the name there and applies first. + managed usage-limits setting listing it, though the user is not itself managed; `DeleteIdentityProvider` refuses a provider a managed + linked identity names. The next plan could not resolve the name, and a startup apply would stop the server. The error names the + resource, the referring resource in `metadata.referenced_by`, and its file; the operator removes the name there and applies first. Consequences: @@ -626,7 +660,8 @@ The web app reads the status once per session, and only for administrators. Ever - Disables the controls for managed fields, each by the JSON-name path it edits, so an ignored path stays editable. Storage locks its registry, default storage, and S3 fields together because the page edits them as one value; usage limits lock as one ordered list. - Hides Delete for a managed identity provider or user, and disables Edit for a managed provider. In the user dialog the username and role - of a managed user are disabled; the password stays editable because it is write-only. + of a managed user are disabled; the password stays editable because it is write-only. The linked identities of the account hide Unlink + for a declared link. An administrator-only Configuration section lists the managed resources, their files and managed fields, and the serial and last apply. A write refused anyway, from a second tab or a stale page, shows the server's message, which names the file. The labels and disabled @@ -693,7 +728,7 @@ conditional setting writes. | `core/configuration/` | Reading and substituting files, decoding, the plan engine, the digest, the API guard rule | | `core/identityprovider/`, `core/instancesetting/`, `core/user/` | Per-resource validation shared by the API and the plan engine; API↔store conversion for identity providers and instance settings, since files are API messages and `core` cannot import `server/api` | | `store/configuration_state.go`, `store/transaction.go` | State record read and write; the serializable transaction helper with retries | -| `server/api/instance_service_configuration.go` | `GetConfigurationStatus`; the guard the six mutating handlers call | +| `server/api/instance_service_configuration.go` | `GetConfigurationStatus`; the guard the mutating handlers call | | `cmd/memos/config.go` | The `memos config` subcommands | | `web/src/` | The managed label, disabled controls, and error presentation | diff --git a/proto/api/configuration.proto b/proto/api/configuration.proto index b094a3e24..deb9c83bc 100644 --- a/proto/api/configuration.proto +++ b/proto/api/configuration.proto @@ -22,6 +22,12 @@ message Configuration { // Optional. Users to manage, by resource name. Intended for bootstrap administrators. repeated User users = 3 [(google.api.field_behavior) = OPTIONAL]; + // Optional. SSO identities of declared users, by resource name: which + // identity-provider subject signs in as which user. Only a user the + // configuration declares may have one. Intended for bootstrap administrators + // on instances where sign-in is through an identity provider. + repeated LinkedIdentity linked_identities = 6 [(google.api.field_behavior) = OPTIONAL]; + // Optional. Lifecycle rules for declared resources. repeated Lifecycle lifecycle = 4 [(google.api.field_behavior) = OPTIONAL]; @@ -32,7 +38,8 @@ message Configuration { // Lifecycle adjusts how one declared resource is planned and applied. message Lifecycle { // Required. The resource name of a resource declared in the configuration. - // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user} + // Format: identity-providers/{idp}, instance/settings/{setting}, users/{user}, + // or users/{user}/linkedIdentities/{linked_identity} string resource = 1 [(google.api.field_behavior) = REQUIRED]; // Optional. Field paths, in JSON name form, that the configuration does not manage. @@ -49,7 +56,8 @@ message Lifecycle { // Removed takes a resource out of management. message Removed { // Required. The resource name of a resource the configuration manages. - // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user} + // Format: identity-providers/{idp}, instance/settings/{setting}, users/{user}, + // or users/{user}/linkedIdentities/{linked_identity} string resource = 1 [(google.api.field_behavior) = REQUIRED]; // Optional. Delete the resource, or reset an instance setting group to its defaults, @@ -80,7 +88,8 @@ message Plan { // ResourceChange is what apply would do to one resource. message ResourceChange { // The resource name. - // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user} + // Format: identity-providers/{idp}, instance/settings/{setting}, users/{user}, + // or users/{user}/linkedIdentities/{linked_identity} string resource = 1; // The configuration file that declares the resource; empty for one that is no longer declared. diff --git a/proto/api/user_service.proto b/proto/api/user_service.proto index 5efde1117..3614e2cda 100644 --- a/proto/api/user_service.proto +++ b/proto/api/user_service.proto @@ -1151,8 +1151,10 @@ message LinkedIdentity { (google.api.resource_reference) = {type: "memos.api/IdentityProvider"} ]; - // Output only. The external user identifier from the identity provider. - string external_uid = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + // The external user identifier from the identity provider: the subject that + // signs in as this user. Set by signing in through the provider, or declared + // in a configuration file for a declared user. + string external_uid = 3 [(google.api.field_behavior) = OPTIONAL]; } // Request message for UserService.ListLinkedIdentities. diff --git a/proto/gen/api/configuration.pb.go b/proto/gen/api/configuration.pb.go index 796423877..3a6284fe1 100644 --- a/proto/gen/api/configuration.pb.go +++ b/proto/gen/api/configuration.pb.go @@ -109,6 +109,11 @@ type Configuration struct { InstanceSettings []*InstanceSetting `protobuf:"bytes,2,rep,name=instance_settings,json=instanceSettings,proto3" json:"instance_settings,omitempty"` // Optional. Users to manage, by resource name. Intended for bootstrap administrators. Users []*User `protobuf:"bytes,3,rep,name=users,proto3" json:"users,omitempty"` + // Optional. SSO identities of declared users, by resource name: which + // identity-provider subject signs in as which user. Only a user the + // configuration declares may have one. Intended for bootstrap administrators + // on instances where sign-in is through an identity provider. + LinkedIdentities []*LinkedIdentity `protobuf:"bytes,6,rep,name=linked_identities,json=linkedIdentities,proto3" json:"linked_identities,omitempty"` // Optional. Lifecycle rules for declared resources. Lifecycle []*Lifecycle `protobuf:"bytes,4,rep,name=lifecycle,proto3" json:"lifecycle,omitempty"` // Optional. Resources to take out of management. @@ -168,6 +173,13 @@ func (x *Configuration) GetUsers() []*User { return nil } +func (x *Configuration) GetLinkedIdentities() []*LinkedIdentity { + if x != nil { + return x.LinkedIdentities + } + return nil +} + func (x *Configuration) GetLifecycle() []*Lifecycle { if x != nil { return x.Lifecycle @@ -186,7 +198,8 @@ func (x *Configuration) GetRemoved() []*Removed { type Lifecycle struct { state protoimpl.MessageState `protogen:"open.v1"` // Required. The resource name of a resource declared in the configuration. - // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user} + // Format: identity-providers/{idp}, instance/settings/{setting}, users/{user}, + // or users/{user}/linkedIdentities/{linked_identity} Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` // Optional. Field paths, in JSON name form, that the configuration does not manage. // Apply writes them only when it creates the resource, and the API does not protect them. @@ -261,7 +274,8 @@ func (x *Lifecycle) GetWriteOnlyVersion() int32 { type Removed struct { state protoimpl.MessageState `protogen:"open.v1"` // Required. The resource name of a resource the configuration manages. - // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user} + // Format: identity-providers/{idp}, instance/settings/{setting}, users/{user}, + // or users/{user}/linkedIdentities/{linked_identity} Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` // Optional. Delete the resource, or reset an instance setting group to its defaults, // instead of only releasing it from management. @@ -402,7 +416,8 @@ func (x *Plan) GetWarnings() []string { type ResourceChange struct { state protoimpl.MessageState `protogen:"open.v1"` // The resource name. - // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user} + // Format: identity-providers/{idp}, instance/settings/{setting}, users/{user}, + // or users/{user}/linkedIdentities/{linked_identity} Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` // The configuration file that declares the resource; empty for one that is no longer declared. Source string `protobuf:"bytes,2,opt,name=source,proto3" json:"source,omitempty"` @@ -559,11 +574,12 @@ var File_api_configuration_proto protoreflect.FileDescriptor const file_api_configuration_proto_rawDesc = "" + "\n" + - "\x17api/configuration.proto\x12\tmemos.api\x1a\x15api/idp_service.proto\x1a\x1aapi/instance_service.proto\x1a\x16api/user_service.proto\x1a\x1fgoogle/api/field_behavior.proto\"\xc6\x02\n" + + "\x17api/configuration.proto\x12\tmemos.api\x1a\x15api/idp_service.proto\x1a\x1aapi/instance_service.proto\x1a\x16api/user_service.proto\x1a\x1fgoogle/api/field_behavior.proto\"\x93\x03\n" + "\rConfiguration\x12O\n" + "\x12identity_providers\x18\x01 \x03(\v2\x1b.memos.api.IdentityProviderB\x03\xe0A\x01R\x11identityProviders\x12L\n" + "\x11instance_settings\x18\x02 \x03(\v2\x1a.memos.api.InstanceSettingB\x03\xe0A\x01R\x10instanceSettings\x12*\n" + - "\x05users\x18\x03 \x03(\v2\x0f.memos.api.UserB\x03\xe0A\x01R\x05users\x127\n" + + "\x05users\x18\x03 \x03(\v2\x0f.memos.api.UserB\x03\xe0A\x01R\x05users\x12K\n" + + "\x11linked_identities\x18\x06 \x03(\v2\x19.memos.api.LinkedIdentityB\x03\xe0A\x01R\x10linkedIdentities\x127\n" + "\tlifecycle\x18\x04 \x03(\v2\x14.memos.api.LifecycleB\x03\xe0A\x01R\tlifecycle\x121\n" + "\aremoved\x18\x05 \x03(\v2\x12.memos.api.RemovedB\x03\xe0A\x01R\aremoved\"\xb9\x01\n" + "\tLifecycle\x12\x1f\n" + @@ -631,21 +647,23 @@ var file_api_configuration_proto_goTypes = []any{ (*IdentityProvider)(nil), // 7: memos.api.IdentityProvider (*InstanceSetting)(nil), // 8: memos.api.InstanceSetting (*User)(nil), // 9: memos.api.User + (*LinkedIdentity)(nil), // 10: memos.api.LinkedIdentity } var file_api_configuration_proto_depIdxs = []int32{ - 7, // 0: memos.api.Configuration.identity_providers:type_name -> memos.api.IdentityProvider - 8, // 1: memos.api.Configuration.instance_settings:type_name -> memos.api.InstanceSetting - 9, // 2: memos.api.Configuration.users:type_name -> memos.api.User - 2, // 3: memos.api.Configuration.lifecycle:type_name -> memos.api.Lifecycle - 3, // 4: memos.api.Configuration.removed:type_name -> memos.api.Removed - 5, // 5: memos.api.Plan.resource_changes:type_name -> memos.api.ResourceChange - 0, // 6: memos.api.ResourceChange.action:type_name -> memos.api.ResourceChange.Action - 6, // 7: memos.api.ResourceChange.field_changes:type_name -> memos.api.FieldChange - 8, // [8:8] is the sub-list for method output_type - 8, // [8:8] is the sub-list for method input_type - 8, // [8:8] is the sub-list for extension type_name - 8, // [8:8] is the sub-list for extension extendee - 0, // [0:8] is the sub-list for field type_name + 7, // 0: memos.api.Configuration.identity_providers:type_name -> memos.api.IdentityProvider + 8, // 1: memos.api.Configuration.instance_settings:type_name -> memos.api.InstanceSetting + 9, // 2: memos.api.Configuration.users:type_name -> memos.api.User + 10, // 3: memos.api.Configuration.linked_identities:type_name -> memos.api.LinkedIdentity + 2, // 4: memos.api.Configuration.lifecycle:type_name -> memos.api.Lifecycle + 3, // 5: memos.api.Configuration.removed:type_name -> memos.api.Removed + 5, // 6: memos.api.Plan.resource_changes:type_name -> memos.api.ResourceChange + 0, // 7: memos.api.ResourceChange.action:type_name -> memos.api.ResourceChange.Action + 6, // 8: memos.api.ResourceChange.field_changes:type_name -> memos.api.FieldChange + 9, // [9:9] is the sub-list for method output_type + 9, // [9:9] is the sub-list for method input_type + 9, // [9:9] is the sub-list for extension type_name + 9, // [9:9] is the sub-list for extension extendee + 0, // [0:9] is the sub-list for field type_name } func init() { file_api_configuration_proto_init() } diff --git a/proto/gen/api/user_service.pb.go b/proto/gen/api/user_service.pb.go index 10e5214a4..3cae0072d 100644 --- a/proto/gen/api/user_service.pb.go +++ b/proto/gen/api/user_service.pb.go @@ -2996,7 +2996,9 @@ type LinkedIdentity struct { // Output only. The resource name of the identity provider. // Format: identity-providers/{idp} IdentityProvider string `protobuf:"bytes,2,opt,name=identity_provider,json=identityProvider,proto3" json:"identity_provider,omitempty"` - // Output only. The external user identifier from the identity provider. + // The external user identifier from the identity provider: the subject that + // signs in as this user. Set by signing in through the provider, or declared + // in a configuration file for a declared user. ExternalUid string `protobuf:"bytes,3,opt,name=external_uid,json=externalUid,proto3" json:"external_uid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -5345,7 +5347,7 @@ const file_api_user_service_proto_rawDesc = "" + "\x04name\x18\x01 \x01(\tB\x03\xe0A\bR\x04name\x12O\n" + "\x11identity_provider\x18\x02 \x01(\tB\"\xe0A\x03\xfaA\x1c\n" + "\x1amemos.api/IdentityProviderR\x10identityProvider\x12&\n" + - "\fexternal_uid\x18\x03 \x01(\tB\x03\xe0A\x03R\vexternalUid:p\xeaAm\n" + + "\fexternal_uid\x18\x03 \x01(\tB\x03\xe0A\x01R\vexternalUid:p\xeaAm\n" + "\x18memos.api/LinkedIdentity\x12/users/{user}/linkedIdentities/{linked_identity}*\x10linkedIdentities2\x0elinkedIdentity\"M\n" + "\x1bListLinkedIdentitiesRequest\x12.\n" + "\x06parent\x18\x01 \x01(\tB\x16\xe0A\x02\xfaA\x10\n" + diff --git a/proto/gen/openapi.yaml b/proto/gen/openapi.yaml index 528cbb7f7..acb614e0a 100644 --- a/proto/gen/openapi.yaml +++ b/proto/gen/openapi.yaml @@ -4280,9 +4280,11 @@ components: Output only. The resource name of the identity provider. Format: identity-providers/{idp} externalUid: - readOnly: true type: string - description: Output only. The external user identifier from the identity provider. + description: |- + The external user identifier from the identity provider: the subject that + signs in as this user. Set by signing in through the provider, or declared + in a configuration file for a declared user. description: LinkedIdentity is an SSO identity linked to a user account. ListAttachmentsResponse: type: object diff --git a/proto/gen/store/instance_setting.pb.go b/proto/gen/store/instance_setting.pb.go index a57697018..07f3623ac 100644 --- a/proto/gen/store/instance_setting.pb.go +++ b/proto/gen/store/instance_setting.pb.go @@ -1837,7 +1837,7 @@ type InstanceConfigurationState_ManagedResource struct { state protoimpl.MessageState `protogen:"open.v1"` // name is the API resource name, such as identity-providers/company-sso. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // kind is IdentityProvider, InstanceSetting, or User. + // kind is IdentityProvider, InstanceSetting, User, or LinkedIdentity. Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"` // source is the configuration file that declares the resource. Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"` diff --git a/proto/store/instance_setting.proto b/proto/store/instance_setting.proto index 49ad18726..dd6d0579a 100644 --- a/proto/store/instance_setting.proto +++ b/proto/store/instance_setting.proto @@ -296,7 +296,7 @@ message InstanceConfigurationState { message ManagedResource { // name is the API resource name, such as identity-providers/company-sso. string name = 1; - // kind is IdentityProvider, InstanceSetting, or User. + // kind is IdentityProvider, InstanceSetting, User, or LinkedIdentity. string kind = 2; // source is the configuration file that declares the resource. string source = 3; diff --git a/server/api/auth_service_sso.go b/server/api/auth_service_sso.go index 92bfb9094..e00642274 100644 --- a/server/api/auth_service_sso.go +++ b/server/api/auth_service_sso.go @@ -6,12 +6,10 @@ import ( "regexp" "github.com/pkg/errors" - "golang.org/x/crypto/bcrypt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" coreuser "github.com/usememos/memos/core/user" - "github.com/usememos/memos/internal/random" storepb "github.com/usememos/memos/proto/gen/store" "github.com/usememos/memos/provider/idp" "github.com/usememos/memos/provider/idp/oauth2" @@ -51,16 +49,12 @@ func (s *APIService) resolveSSOUser(ctx context.Context, currentUser *store.User return nil, status.Errorf(codes.PermissionDenied, "user registration is not allowed") } - password, err := random.String(20) + passwordHash, err := coreuser.RandomPasswordHash() if err != nil { - return nil, status.Errorf(codes.Internal, "failed to generate random password, error: %v", err) - } - passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) - if err != nil { - return nil, status.Errorf(codes.Internal, "failed to generate password hash, error: %v", err) + return nil, status.Errorf(codes.Internal, "%v", err) } email := s.resolveSSOEmail(ctx, userInfo.Email, provider, externUID) - user, err = s.createSSOUser(ctx, userInfo, email, string(passwordHash), provider, externUID) + user, err = s.createSSOUser(ctx, userInfo, email, passwordHash, provider, externUID) if err != nil { return nil, status.Errorf(codes.Internal, "failed to create user, error: %v", err) } diff --git a/server/api/idp_service.go b/server/api/idp_service.go index 80538e1eb..ab297feb0 100644 --- a/server/api/idp_service.go +++ b/server/api/idp_service.go @@ -187,6 +187,9 @@ func (s *APIService) DeleteIdentityProvider(ctx context.Context, request *apipb. if err := s.checkManagedExistence(ctx, identityprovider.NamePrefix+uid); err != nil { return nil, err } + if err := s.checkManagedReference(ctx, identityprovider.NamePrefix+uid); err != nil { + return nil, err + } // Look up the IdP by UID to get the internal ID for deletion. identityProvider, err := s.Store.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: &uid}) if err != nil { diff --git a/server/api/test/instance_service_configuration_test.go b/server/api/test/instance_service_configuration_test.go index e5e097f8a..038bf85a8 100644 --- a/server/api/test/instance_service_configuration_test.go +++ b/server/api/test/instance_service_configuration_test.go @@ -180,3 +180,39 @@ func TestGetConfigurationStatus(t *testing.T) { _, err = ts.Service.GetConfigurationStatus(ctx, &apipb.GetConfigurationStatusRequest{}) require.Equal(t, codes.Unauthenticated, status.Code(err)) } + +func TestConfigurationGuardLinkedIdentity(t *testing.T) { + ctx := context.Background() + ts := NewTestService(t) + defer ts.Cleanup() + admin, err := ts.CreateHostUser(ctx, "admin") + require.NoError(t, err) + adminCtx := ts.CreateUserContext(ctx, admin.ID) + applyConfiguration(ctx, t, ts, map[string]string{ + "idp.json": `{"identityProviders":[` + managedProvider + `]}`, + "users.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"pw"}]}`, + "links.json": `{"linkedIdentities":[{"name":"users/admin/linkedIdentities/sso","externalUid":"subject-1"}]}`, + }) + + // The declared link exists and signs the subject in as the admin. + identities, err := ts.Service.ListLinkedIdentities(adminCtx, &apipb.ListLinkedIdentitiesRequest{Parent: "users/admin"}) + require.NoError(t, err) + require.Len(t, identities.LinkedIdentities, 1) + require.Equal(t, "subject-1", identities.LinkedIdentities[0].ExternalUid) + + // A managed link cannot be unlinked in Settings; the error names the file. + _, err = ts.Service.DeleteLinkedIdentity(adminCtx, &apipb.DeleteLinkedIdentityRequest{Name: "users/admin/linkedIdentities/sso"}) + require.Equal(t, "links.json", requireManaged(t, err, "users/admin/linkedIdentities/sso")["source"]) + + // The provider a declared link names cannot be deleted while the link is + // declared, even once the provider itself is released. + applyConfiguration(ctx, t, ts, map[string]string{ + "users.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"pw"}]}`, + "links.json": `{"linkedIdentities":[{"name":"users/admin/linkedIdentities/sso","externalUid":"subject-1"}]}`, + "idp.json": `{"removed":[{"resource":"identity-providers/sso"}]}`, + }) + _, err = ts.Service.DeleteIdentityProvider(adminCtx, &apipb.DeleteIdentityProviderRequest{Name: "identity-providers/sso"}) + metadata := requireManaged(t, err, "identity-providers/sso") + require.Equal(t, "users/admin/linkedIdentities/sso", metadata["referenced_by"]) + require.Equal(t, "links.json", metadata["source"]) +} diff --git a/server/api/user_service.go b/server/api/user_service.go index 6b358e0f2..1204474f1 100644 --- a/server/api/user_service.go +++ b/server/api/user_service.go @@ -3,7 +3,6 @@ package api import ( "context" stderrors "errors" - "fmt" "log/slog" "regexp" "slices" @@ -644,9 +643,15 @@ func (s *APIService) resolveUserAndLinkedIdentityProviderFromName(ctx context.Co return user, parts[3], nil } +// linkedIdentityName is the resource name of user's link to the identity +// provider with uid provider: users/{user}/linkedIdentities/{idp}. +func linkedIdentityName(user *store.User, provider string) string { + return coreuser.LinkedIdentityName(user.Username, provider) +} + func convertLinkedIdentityFromStore(user *store.User, identity *store.UserIdentity) *apipb.LinkedIdentity { return &apipb.LinkedIdentity{ - Name: fmt.Sprintf("%s/linkedIdentities/%s", BuildUserName(user.Username), identity.Provider), + Name: linkedIdentityName(user, identity.Provider), IdentityProvider: IdentityProviderNamePrefix + identity.Provider, ExternalUid: identity.ExternUID, } diff --git a/server/api/user_service_identities.go b/server/api/user_service_identities.go index 4a7e88c19..1eefeafd2 100644 --- a/server/api/user_service_identities.go +++ b/server/api/user_service_identities.go @@ -60,6 +60,9 @@ func (s *APIService) CreateLinkedIdentity(ctx context.Context, request *apipb.Cr provider := identityProvider.Uid externUID := userInfo.Identifier + if err := s.checkManagedExistence(ctx, linkedIdentityName(user, provider)); err != nil { + return nil, err + } if _, err := s.bindSSOIdentityToUser(ctx, currentUser, provider, externUID); err != nil { return nil, err } @@ -124,6 +127,9 @@ func (s *APIService) DeleteLinkedIdentity(ctx context.Context, request *apipb.De if existing == nil { return nil, status.Errorf(codes.NotFound, "linked identity not found") } + if err := s.checkManagedExistence(ctx, linkedIdentityName(user, provider)); err != nil { + return nil, err + } if err := s.Store.DeleteUserIdentities(ctx, &store.DeleteUserIdentity{ UserID: &userID, diff --git a/store/configuration_state.go b/store/configuration_state.go index 9a865aa4d..564071405 100644 --- a/store/configuration_state.go +++ b/store/configuration_state.go @@ -184,6 +184,31 @@ func (t *ConfigurationTransaction) UpdateUser(ctx context.Context, update *Updat return nil } +// ListUserIdentities reads identity links within the transaction. +func (t *ConfigurationTransaction) ListUserIdentities(ctx context.Context, find *FindUserIdentity) ([]*UserIdentity, error) { + return t.store.driver.ListUserIdentitiesTx(ctx, t.tx, find) +} + +// CreateUserIdentity links an identity-provider subject to a user within the +// transaction. A subject already linked elsewhere is ErrUserIdentityTaken. +func (t *ConfigurationTransaction) CreateUserIdentity(ctx context.Context, create *UserIdentity) error { + if _, err := t.store.driver.CreateUserIdentityTx(ctx, t.tx, create); err != nil { + if uniqueErr := classifyUserUniqueViolation(err); uniqueErr != nil { + return uniqueErr + } + return errors.Wrapf(err, "failed to link the %s identity of user %d", create.Provider, create.UserID) + } + return nil +} + +// DeleteUserIdentities removes identity links within the transaction. +func (t *ConfigurationTransaction) DeleteUserIdentities(ctx context.Context, delete *DeleteUserIdentity) error { + if err := t.store.driver.DeleteUserIdentitiesTx(ctx, t.tx, delete); err != nil { + return errors.Wrap(err, "failed to delete identity links") + } + return nil +} + // afterCommit drops what the committed writes made stale. A new password ends // every session of that user, as an administrator's password reset does. func (t *ConfigurationTransaction) afterCommit(ctx context.Context) { diff --git a/store/db/mysql/user_identity.go b/store/db/mysql/user_identity.go index b6241b203..2892b9b4f 100644 --- a/store/db/mysql/user_identity.go +++ b/store/db/mysql/user_identity.go @@ -27,7 +27,16 @@ func insertUserIdentity(ctx context.Context, e execer, create *store.UserIdentit } func (d *DB) CreateUserIdentity(ctx context.Context, create *store.UserIdentity) (*store.UserIdentity, error) { - result, err := insertUserIdentity(ctx, d.db, create) + return createUserIdentity(ctx, d.db, create) +} + +// CreateUserIdentityTx is CreateUserIdentity within tx. +func (*DB) CreateUserIdentityTx(ctx context.Context, tx *sql.Tx, create *store.UserIdentity) (*store.UserIdentity, error) { + return createUserIdentity(ctx, tx, create) +} + +func createUserIdentity(ctx context.Context, q dbExecutor, create *store.UserIdentity) (*store.UserIdentity, error) { + result, err := insertUserIdentity(ctx, q, create) if err != nil { return nil, errors.Wrap(err, "failed to create user identity") } @@ -37,7 +46,7 @@ func (d *DB) CreateUserIdentity(ctx context.Context, create *store.UserIdentity) return nil, err } id := int32(rawID) - list, err := d.ListUserIdentities(ctx, &store.FindUserIdentity{ID: &id}) + list, err := listUserIdentities(ctx, q, &store.FindUserIdentity{ID: &id}) if err != nil { return nil, err } @@ -101,6 +110,15 @@ func (d *DB) CreateUserWithIdentity(ctx context.Context, createUser *store.User, } func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { + return listUserIdentities(ctx, d.db, find) +} + +// ListUserIdentitiesTx is ListUserIdentities within tx. +func (*DB) ListUserIdentitiesTx(ctx context.Context, tx *sql.Tx, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { + return listUserIdentities(ctx, tx, find) +} + +func listUserIdentities(ctx context.Context, q dbExecutor, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { where, args := []string{"1 = 1"}, []any{} if find.ID != nil { @@ -116,7 +134,7 @@ func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentit where, args = append(where, "`extern_uid` = ?"), append(args, *find.ExternUID) } - rows, err := d.db.QueryContext(ctx, ` + rows, err := q.QueryContext(ctx, ` SELECT id, user_id, @@ -157,6 +175,15 @@ func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentit } func (d *DB) DeleteUserIdentities(ctx context.Context, delete *store.DeleteUserIdentity) error { + return deleteUserIdentities(ctx, d.db, delete) +} + +// DeleteUserIdentitiesTx is DeleteUserIdentities within tx. +func (*DB) DeleteUserIdentitiesTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteUserIdentity) error { + return deleteUserIdentities(ctx, tx, delete) +} + +func deleteUserIdentities(ctx context.Context, q dbExecutor, delete *store.DeleteUserIdentity) error { where, args := []string{"1 = 1"}, []any{} if delete.ID != nil { @@ -169,7 +196,7 @@ func (d *DB) DeleteUserIdentities(ctx context.Context, delete *store.DeleteUserI where, args = append(where, "`provider` = ?"), append(args, *delete.Provider) } - if _, err := d.db.ExecContext(ctx, "DELETE FROM `user_identity` WHERE "+strings.Join(where, " AND "), args...); err != nil { + if _, err := q.ExecContext(ctx, "DELETE FROM `user_identity` WHERE "+strings.Join(where, " AND "), args...); err != nil { return err } return nil diff --git a/store/db/postgres/user_identity.go b/store/db/postgres/user_identity.go index 1ac803bb8..7859cb416 100644 --- a/store/db/postgres/user_identity.go +++ b/store/db/postgres/user_identity.go @@ -46,7 +46,16 @@ func insertUserIdentity(ctx context.Context, q rowQuerier, create *store.UserIde } func (d *DB) CreateUserIdentity(ctx context.Context, create *store.UserIdentity) (*store.UserIdentity, error) { - if err := insertUserIdentity(ctx, d.db, create); err != nil { + return createUserIdentity(ctx, d.db, create) +} + +// CreateUserIdentityTx is CreateUserIdentity within tx. +func (*DB) CreateUserIdentityTx(ctx context.Context, tx *sql.Tx, create *store.UserIdentity) (*store.UserIdentity, error) { + return createUserIdentity(ctx, tx, create) +} + +func createUserIdentity(ctx context.Context, q dbExecutor, create *store.UserIdentity) (*store.UserIdentity, error) { + if err := insertUserIdentity(ctx, q, create); err != nil { return nil, errors.Wrap(err, "failed to create user identity") } return create, nil @@ -77,6 +86,15 @@ func (d *DB) CreateUserWithIdentity(ctx context.Context, createUser *store.User, } func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { + return listUserIdentities(ctx, d.db, find) +} + +// ListUserIdentitiesTx is ListUserIdentities within tx. +func (*DB) ListUserIdentitiesTx(ctx context.Context, tx *sql.Tx, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { + return listUserIdentities(ctx, tx, find) +} + +func listUserIdentities(ctx context.Context, q dbExecutor, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { where, args := []string{"1 = 1"}, []any{} if find.ID != nil { @@ -92,7 +110,7 @@ func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentit where, args = append(where, "extern_uid = "+placeholder(len(args)+1)), append(args, *find.ExternUID) } - rows, err := d.db.QueryContext(ctx, ` + rows, err := q.QueryContext(ctx, ` SELECT id, user_id, @@ -133,6 +151,15 @@ func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentit } func (d *DB) DeleteUserIdentities(ctx context.Context, delete *store.DeleteUserIdentity) error { + return deleteUserIdentities(ctx, d.db, delete) +} + +// DeleteUserIdentitiesTx is DeleteUserIdentities within tx. +func (*DB) DeleteUserIdentitiesTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteUserIdentity) error { + return deleteUserIdentities(ctx, tx, delete) +} + +func deleteUserIdentities(ctx context.Context, q dbExecutor, delete *store.DeleteUserIdentity) error { where, args := []string{"1 = 1"}, []any{} if delete.ID != nil { @@ -145,7 +172,7 @@ func (d *DB) DeleteUserIdentities(ctx context.Context, delete *store.DeleteUserI where, args = append(where, "provider = "+placeholder(len(args)+1)), append(args, *delete.Provider) } - if _, err := d.db.ExecContext(ctx, "DELETE FROM user_identity WHERE "+strings.Join(where, " AND "), args...); err != nil { + if _, err := q.ExecContext(ctx, "DELETE FROM user_identity WHERE "+strings.Join(where, " AND "), args...); err != nil { return err } return nil diff --git a/store/db/sqlite/user_identity.go b/store/db/sqlite/user_identity.go index 6854864ae..d7a19c6a2 100644 --- a/store/db/sqlite/user_identity.go +++ b/store/db/sqlite/user_identity.go @@ -46,7 +46,16 @@ func insertUserIdentity(ctx context.Context, q rowQuerier, create *store.UserIde } func (d *DB) CreateUserIdentity(ctx context.Context, create *store.UserIdentity) (*store.UserIdentity, error) { - if err := insertUserIdentity(ctx, d.db, create); err != nil { + return createUserIdentity(ctx, d.db, create) +} + +// CreateUserIdentityTx is CreateUserIdentity within tx. +func (*DB) CreateUserIdentityTx(ctx context.Context, tx *sql.Tx, create *store.UserIdentity) (*store.UserIdentity, error) { + return createUserIdentity(ctx, tx, create) +} + +func createUserIdentity(ctx context.Context, q dbExecutor, create *store.UserIdentity) (*store.UserIdentity, error) { + if err := insertUserIdentity(ctx, q, create); err != nil { return nil, errors.Wrap(err, "failed to create user identity") } return create, nil @@ -77,6 +86,15 @@ func (d *DB) CreateUserWithIdentity(ctx context.Context, createUser *store.User, } func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { + return listUserIdentities(ctx, d.db, find) +} + +// ListUserIdentitiesTx is ListUserIdentities within tx. +func (*DB) ListUserIdentitiesTx(ctx context.Context, tx *sql.Tx, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { + return listUserIdentities(ctx, tx, find) +} + +func listUserIdentities(ctx context.Context, q dbExecutor, find *store.FindUserIdentity) ([]*store.UserIdentity, error) { where, args := []string{"1 = 1"}, []any{} if find.ID != nil { @@ -92,7 +110,7 @@ func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentit where, args = append(where, "`extern_uid` = ?"), append(args, *find.ExternUID) } - rows, err := d.db.QueryContext(ctx, ` + rows, err := q.QueryContext(ctx, ` SELECT id, user_id, @@ -133,6 +151,15 @@ func (d *DB) ListUserIdentities(ctx context.Context, find *store.FindUserIdentit } func (d *DB) DeleteUserIdentities(ctx context.Context, delete *store.DeleteUserIdentity) error { + return deleteUserIdentities(ctx, d.db, delete) +} + +// DeleteUserIdentitiesTx is DeleteUserIdentities within tx. +func (*DB) DeleteUserIdentitiesTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteUserIdentity) error { + return deleteUserIdentities(ctx, tx, delete) +} + +func deleteUserIdentities(ctx context.Context, q dbExecutor, delete *store.DeleteUserIdentity) error { where, args := []string{"1 = 1"}, []any{} if delete.ID != nil { @@ -145,7 +172,7 @@ func (d *DB) DeleteUserIdentities(ctx context.Context, delete *store.DeleteUserI where, args = append(where, "`provider` = ?"), append(args, *delete.Provider) } - if _, err := d.db.ExecContext(ctx, "DELETE FROM `user_identity` WHERE "+strings.Join(where, " AND "), args...); err != nil { + if _, err := q.ExecContext(ctx, "DELETE FROM `user_identity` WHERE "+strings.Join(where, " AND "), args...); err != nil { return err } return nil diff --git a/store/driver.go b/store/driver.go index 41cec070a..3e954090b 100644 --- a/store/driver.go +++ b/store/driver.go @@ -133,4 +133,8 @@ type Driver interface { CreateUserWithIdentity(ctx context.Context, createUser *User, createIdentity *UserIdentity) (*User, error) ListUserIdentities(ctx context.Context, find *FindUserIdentity) ([]*UserIdentity, error) DeleteUserIdentities(ctx context.Context, delete *DeleteUserIdentity) error + // The identity link methods within tx. + CreateUserIdentityTx(ctx context.Context, tx *sql.Tx, create *UserIdentity) (*UserIdentity, error) + ListUserIdentitiesTx(ctx context.Context, tx *sql.Tx, find *FindUserIdentity) ([]*UserIdentity, error) + DeleteUserIdentitiesTx(ctx context.Context, tx *sql.Tx, delete *DeleteUserIdentity) error } diff --git a/web/src/components/Settings/LinkedIdentitySection.tsx b/web/src/components/Settings/LinkedIdentitySection.tsx index 0fc6a4b79..4b5ab3989 100644 --- a/web/src/components/Settings/LinkedIdentitySection.tsx +++ b/web/src/components/Settings/LinkedIdentitySection.tsx @@ -5,6 +5,7 @@ import { getIdentityProviderTypeLabel, getSSOProviderUid } from "@/components/Se import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { identityProviderServiceClient, userServiceClient } from "@/connect"; +import { findManagedResource, useConfigurationStatus } from "@/hooks/useConfigurationQueries"; import useCurrentUser from "@/hooks/useCurrentUser"; import { absolutifyLink } from "@/lib/browser"; import { handleError } from "@/lib/error"; @@ -12,6 +13,7 @@ import { IdentityProvider, IdentityProvider_Type } from "@/types/proto/api/idp_s import { LinkedIdentity } from "@/types/proto/api/user_service_pb"; import { useTranslate } from "@/utils/i18n"; import { storeOAuthState } from "@/utils/oauth"; +import ManagedByConfigurationChip from "./ManagedByConfigurationChip"; import SettingGroup from "./SettingGroup"; import SettingTable from "./SettingTable"; @@ -29,6 +31,7 @@ interface LinkedIdentityRow extends Record { const LinkedIdentitySection = () => { const t = useTranslate(); const currentUser = useCurrentUser(); + const configurationStatus = useConfigurationStatus(); const [identityProviderList, setIdentityProviderList] = useState([]); const [linkedIdentityList, setLinkedIdentityList] = useState([]); @@ -174,6 +177,7 @@ const LinkedIdentitySection = () => { {row.isLinked && row.externalUid ? ( ) : null} +

{row.isLinked ? t("setting.sso.extern-uid-description") : t("setting.sso.not-linked-description")} @@ -187,9 +191,12 @@ const LinkedIdentitySection = () => { className: "w-px text-right", render: (_, row: LinkedIdentityRow) => row.linkedIdentity ? ( - + // A link the configuration declares is unlinked in its file, not here. + findManagedResource(configurationStatus, row.linkedIdentity.name) ? null : ( + + ) ) : (